对称加密算法概念
加密密钥和解密密钥相同,大部分算法加密揭秘过程互逆。
特点:算法公开、(相比非对称加密)计算量小、加密速度快、效率高。
弱点:双方都使用同样的密钥,安全性得不到保证。
常用对称加密算法
DES(Data Encryption Standard)
3DES(DES加强版,使用3次DES计算,Triple DES,DESede)
AES(Advanced Encryption Standard,3DES加强版)
JDK版DES/3DES/AES算法调用模板
1. 生成密钥
//KeyGenerator,密钥生成器 KeyGenerator keyGen = KeyGenerator.getInstance("DES");//算法:DES,DESede,AES //初始化密钥生成器 keyGen.init(56); //各算法密钥长度不同,参见说明 //生成密钥 SecretKey secretKey = keyGen.generateKey(); //生产字节码数据 byte[] key = secretKey.getEncoded();
说明:
1.通过「KeyGenerator.getInstance(“DES”)」生成密钥,
2.参数为算法名称:分别对应DES、DESede(即3DES)、AES
3.每种算法密钥长度参数:DES(56),3DES(112,168),AES(192,256)
2.加/解密
//通过字节码数据key 恢复密钥 SecretKey secretKey = new SecretKeySpec(key, "DES"); //Cipher完成加密/解密工作 Cipher cipher = Cipher.getInstance("DES"); //根据密钥,对Cipher初始化,并选择加密还是解密 cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] result = cipher.doFinal(data);
1.加密或解密都通过cipher.init()设置,参数:ENCRYPT_MODE/DECRYPT_MODE
2.加密或解密都通过cipher.doFinal() 执行,获得byte[]类型结果。
代码示例
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class DESUtil { /* * 生成密钥 */ public static byte[] initKey() throws Exception{ KeyGenerator keyGen = KeyGenerator.getInstance("DES"); keyGen.init(56); SecretKey secretKey = keyGen.generateKey(); return secretKey.getEncoded(); } /* * DES 加密 */ public static byte[] encrypt(byte[] data, byte[] key) throws Exception{ SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherBytes = cipher.doFinal(data); return cipherBytes; } /* * DES 解密 */ public static byte[] decrypt(byte[] data, byte[] key) throws Exception{ SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] plainBytes = cipher.doFinal(data); return plainBytes; } //Test public static void main(String[] args) throws Exception { byte[] desKey = DESUtil.initKey(); System.out.println("DES KEY : " + BytesToHex.fromBytesToHex(desKey)); byte[] desResult = DESUtil.encrypt(DATA.getBytes(), desKey); System.out.println(DATA + ">>>DES 加密结果>>>" + BytesToHex.fromBytesToHex(desResult)); byte[] desPlain = DESUtil.decrypt(desResult, desKey); System.out.println(DATA + ">>>DES 解密结果>>>" + new String(desPlain)); } }