直接上代碼
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;
/**
* DES 加解密工具類
*
* @author lixk
*/
public class DES {
//加解密算法名稱
private static final String ALGORITHM = "DES";
//字元編碼
private static final String CHARSET = "UTF-8";
/**
* 生成秘鑰
*
* @param password 加解密的密碼
* @return
* @throws Exception
*/
private static SecretKey getSecretKey(String password) throws Exception {
//擷取密鑰生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
//初始化秘鑰生成器,DES 生成的秘鑰長度必須是 56
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes(CHARSET));
keyGenerator.init(56, secureRandom);
//生成密鑰
return keyGenerator.generateKey();
}
/**
* DES 加密
*
* @param data 待加密的資料
* @param password 密碼
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String password) throws Exception {
//建立密碼器
Cipher cipher = Cipher.getInstance(ALGORITHM);
//初始化為加密模式的密碼器
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));
//傳回加密資料
return cipher.doFinal(data);
}
/**
* DES 加密
*
* @param data 待加密的資料
* @param password 密碼
* @return
* @throws Exception
*/
public static String encrypt(String data, String password) throws Exception {
return Base64.getEncoder().encodeToString(encrypt(data.getBytes(CHARSET), password));
}
/**
* DES 解密
*
* @param data 待解密的資料
* @param password 密碼
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String password) throws Exception {
//建立密碼器
Cipher cipher = Cipher.getInstance(ALGORITHM);
//初始化為解密模式的密碼器
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
//傳回加密資料
return cipher.doFinal(data);
}
/**
* DES 解密
*
* @param data Base64加密的待解密的資料
* @param password 密碼
* @return
* @throws Exception
*/
public static String decrypt(String data, String password) throws Exception {
return new String(decrypt(Base64.getDecoder().decode(data), password), CHARSET);
}
/**
* 測試
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String data = "DES 加解密測試!";
String password = "123456";
String s1 = DES.encrypt(data, password);
System.out.println("加密後的資料:" + s1);
String s2 = DES.decrypt(s1, password);
System.out.println("解密後的資料:" + s2);
}
}
運作結果:
加密後的資料:uzQSod4gIqW7FkVYSeYhFHXNJEsItXDB
解密後的資料:DES 加解密測試!