java DES算法加密 输入:明文和密钥 输出:密文 解密 输入:密文和密钥 输出:明文
时间: 2024-06-11 07:07:30 浏览: 176
Des___JAVA.rar_DES JAVA_DES 加密_des算法
以下是Java代码实现DES算法加密和解密:
```
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DESUtil {
private static final String ALGORITHM = "DES";
/**
* DES加密
* @param plainText 明文
* @param secretKey 密钥
* @return 密文
*/
public static String encrypt(String plainText, String secretKey) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey key = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(plainText.getBytes());
return new String(result);
}
/**
* DES解密
* @param cipherText 密文
* @param secretKey 密钥
* @return 明文
*/
public static String decrypt(String cipherText, String secretKey) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey key = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(cipherText.getBytes());
return new String(result);
}
}
```
使用示例:
```
public static void main(String[] args) {
String plainText = "hello world";
String secretKey = "12345678";
try {
String cipherText = DESUtil.encrypt(plainText, secretKey);
System.out.println("Cipher text: " + cipherText);
String decryptedText = DESUtil.decrypt(cipherText, secretKey);
System.out.println("Decrypted text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
```
阅读全文