DES加密解密算法java
时间: 2023-11-10 08:03:23 浏览: 41
DES加密解密算法是一种对称加密算法,在Java中可以使用JDK自带的Cipher类实现。下面是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class DesDemo {
private static final String KEY_ALGORITHM = "DES";
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
public static String encrypt(String content, String password) throws Exception {
SecretKey secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String content, String password) throws Exception {
SecretKey secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.getDecoder().decode(content);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
private static SecretKey generateKey(String password) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
keyGenerator.init(56);
return new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM);
}
public static void main(String[] args) throws Exception {
String content = "Hello, World!";
String password = "12345678";
String encryptedContent = encrypt(content, password);
String decryptedContent = decrypt(encryptedContent, password);
System.out.println("明文:" + content);
System.out.println("密文:" + encryptedContent);
System.out.println("解密后:" + decryptedContent);
}
}
```