Java常用對稱加密演算法-DES
阿新 • • 發佈:2019-01-29
直接上程式碼
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 加解密測試!