java实现des加解密算法
时间: 2023-05-26 09:03:57 浏览: 186
DES是一种对称加密算法,可以用于加密和解密数据。下面是java实现DES加解密算法的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class DesEncryptionExample {
private static final String ALGORITHM = "DES";
private static final String MODE = "ECB";
private static final String PADDING = "PKCS5Padding";
private static final String SECRET_KEY = "12345678";
// 加密
public static byte[] encrypt(byte[] data) throws Exception {
SecretKey key = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/" + PADDING);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
// 解密
public static byte[] decrypt(byte[] encryptedData) throws Exception {
SecretKey key = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/" + PADDING);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(encryptedData);
}
public static void main(String[] args) {
try {
String data = "Hello World!";
System.out.println("Original data: " + data);
byte[] encryptedData = encrypt(data.getBytes());
System.out.println("Encrypted data: " + new String(encryptedData));
byte[] decryptedData = decrypt(encryptedData);
System.out.println("Decrypted data: " + new String(decryptedData));
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,我们定义了一个字符串`SECRET_KEY`,用于生成密钥。我们使用`SecretKeySpec`类生成DES加密算法所需要的密钥,并使用`Cipher`类的`getInstance`方法创建加密和解密对象。在加密和解密时,我们都使用`Cipher`类的`doFinal`方法。最后,我们可以在控制台上看到加密和解密后的结果。