des算法实现java
时间: 2023-11-10 18:58:34 浏览: 92
DES(Data Encryption Standard)是一种对称加密算法,它的实现可以使用Java提供的标准库中的javax.crypto包。
下面是一个简单的DES加密和解密的实例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DESUtil {
private static final String ALGORITHM = "DES";
private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding";
public static String encrypt(String input, String key) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String input, String key) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(input));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) throws Exception {
String input = "Hello, world!";
String key = "my secret key";
String encrypted = DESUtil.encrypt(input, key);
System.out.println("Encrypted: " + encrypted);
String decrypted = DESUtil.decrypt(encrypted, key);
System.out.println("Decrypted: " + decrypted);
}
}
```
输出:
```
Encrypted: QmYm8Bv6mJ2jMx0oUwW6Uw==
Decrypted: Hello, world!
```
注意:DES算法已经不安全,不推荐使用。可以使用更安全的AES算法代替。
阅读全文