? ? ? ? 对称加密算法的加密密钥和解密密钥是完全相同的。它是初等加密算法,常见的有DES、3DES、AES、PEB、IDEA等。
一.对称加密算法DES
? ? ? ? IBM提交的算法,1998年之后不断被破解,实际使用中它不具备安全性。
? ? ? ??DES(Data Encryption Standard)数据加密标准
? ? ? ? 实例:
class="java">package com.bijian.study; import java.security.Key; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import org.apache.commons.codec.binary.Hex; import org.bouncycastle.jce.provider.BouncyCastleProvider; /** * DES实例 */ public class BJDES { private static String src = "bj security des"; public static void main(String[] args) { jdkDES(); bcDES(); } public static void jdkDES() { try { //生成KEY KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); keyGenerator.init(56); SecretKey secretKey = keyGenerator.generateKey(); byte[] bytesKey = secretKey.getEncoded(); //KEY转换 DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); Key convertSecretKey = factory.generateSecret(desKeySpec); //加密 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey); byte[] result = cipher.doFinal(src.getBytes()); System.out.println("jdk des encrypt:" + Hex.encodeHexString(result)); //解密 cipher.init(Cipher.DECRYPT_MODE, convertSecretKey); result = cipher.doFinal(result); System.out.println("jdk des decrypt:" + new String(result)); }catch(Exception e) { e.printStackTrace(); } } public static void bcDES() { try { //推荐这样使用 Security.addProvider(new BouncyCastleProvider()); //生成KEY KeyGenerator keyGenerator = KeyGenerator.getInstance("DES", "BC"); System.out.println(keyGenerator.getProvider()); keyGenerator.init(56); SecretKey secretKey = keyGenerator.generateKey(); byte[] bytesKey = secretKey.getEncoded(); //KEY转换 DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); Key convertSecretKey = factory.generateSecret(desKeySpec); //加密 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey); byte[] result = cipher.doFinal(src.getBytes()); System.out.println("bc des encrypt:" + Hex.encodeHexString(result)); //解密 cipher.init(Cipher.DECRYPT_MODE, convertSecretKey); result = cipher.doFinal(result); System.out.println("bc des decrypt:" + new String(result)); }catch(Exception e) { e.printStackTrace(); } } }
运行结果:
jdk des encrypt:414d69f4caf9663d8e00f02e205fa661 jdk des decrypt:bj security des BC version 1.49 bc des encrypt:978219ab6017700f4fe17157e3ceb233 bc des decrypt:bj security des
? ? ? ? 基于DES典型应用的场景:
二.对称加密算法3DES(3重DES)
? ? ? ? 由于DES的算法是半公开的,这一点违反了柯克霍夫原则,密码机构不推荐使用,而且很多人怀疑美国国家安全局会在DES中安装一些后门以达到窃取信息的目的。
? ? ? ? 3重DES的好处:a.密钥长度增强;b.迭代次数提高。
?
?
三.对称加密算法AES
?
?
四.对称加密算法PBE
?
?
五.小结
?
?
视频学习地址:http://www.imooc.com/learn/287