01_DES加密算法
程序员文章站
2024-03-14 13:59:40
...
/**
* <p>Description: DES 算法加密</p>
*
* @author XXX
* @date 2020/11/25 21:56
* @since JDK1.8
*/
public class DESEncryption {
private static Base64.Encoder encoder = Base64.getEncoder();
private static Base64.Decoder decoder = Base64.getDecoder();
private static String desEncrypt(String text, String originKey) throws Exception {
//获取加密算法工具类对象
Cipher cipher = Cipher.getInstance("DES");
//对原始秘钥处理后的秘钥
SecretKeySpec key = getKey(originKey);
cipher.init(Cipher.ENCRYPT_MODE, key);
//用加密算法对明文进行加密
byte[] bytes = cipher.doFinal(text.getBytes());
return new String(encoder.encode(bytes));
}
private static String desDecrypt(String encrypt, String originKey) throws Exception {
//获取加密算法工具类对象
Cipher cipher = Cipher.getInstance("DES");
//对原始秘钥处理后的秘钥
SecretKeySpec key = getKey(originKey);
cipher.init(Cipher.DECRYPT_MODE, key);
//用加密算法对明文进行加密
byte[] bytes = cipher.doFinal(decoder.decode(encrypt.getBytes()));
return new String(bytes);
}
private static SecretKeySpec getKey(String originKey) {
//DES 算法要求为64位,8个字节
byte[] buffer = new byte[8];
byte[] bytes = originKey.getBytes();
for (int i = 0; i < 8 && i < bytes.length; i++) {
buffer[i] = bytes[i];
}
//根据原始秘钥构造一个新的秘钥,要求 buffer.length = 8
return new SecretKeySpec(buffer, "DES");
}
public static void main(String[] args) throws Exception {
String originKey = "ADE43SWIM21";
String text = "hello";
System.out.println("加密前:" + text);
String encrypt = desEncrypt(text, originKey);
System.out.println("加密后:" + encrypt);
String decrypt = desDecrypt(encrypt, originKey);
System.out.println("解密后:" + decrypt);
}
上一篇: DES 加密
下一篇: python实现DES加密,解密