java安全架构____AES加密原理
2017-03-02 18:48
549 查看
//使用安全数可以增加
SECURITY_STR 安全系数
package demo.security; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * @author God * AES加密解密工具类 */ public class AESUtil { //加密模式 public static final String ALGORITHM_AES="AES"; //安全数 public static final String SECURITY_STR="zhangsan"; /** * 加密 * @param security_str * @param clearText * @return */ public static byte[] AESEncode(String security_str,String clearText){ byte[] cipherBytes=null; try { // 1.构造密钥生成器,指 KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_AES); // 2.初始化秘钥生成器 加安全数 keyGenerator.init(128, new SecureRandom(security_str.getBytes())); //获取安全秘钥 SecretKey secretKey = keyGenerator.generateKey(); ///生成秘钥自己数组 byte[] secretKeyBytes = secretKey.getEncoded(); //根据字节数组生成AES秘钥 SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, ALGORITHM_AES); // 根据AES生成密码器 Cipher cipher = Cipher.getInstance(ALGORITHM_AES); //初始化密码器 加密模式,secretKeySpec cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); //将明文进行自己数组加密处理 cipherBytes=cipher.doFinal(clearText.getBytes()); } catch (Exception e) { e.printStackTrace(); } return cipherBytes; } /** * 解密 安全数 加密的数组 * @return */ public static byte[] AESDecode(String security_str,byte [] cipherBytes){ byte[] clearTextBytes=null; try { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_AES); keyGenerator.init(128, new SecureRandom(security_str.getBytes())); SecretKey secretKey = keyGenerator.generateKey(); byte[] secretKeyBytes = secretKey.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes,ALGORITHM_AES); Cipher cipher = Cipher.getInstance(ALGORITHM_AES);// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化 clearTextBytes = cipher.doFinal(cipherBytes); } catch (Exception e) { e.printStackTrace(); } return clearTextBytes; } /** * 测试AES加密解密 * @param args */ public static void main(String[] args) { String clearText="老司机开车了"; System.out.println("明文是_____:"+clearText); //加密 System.out.println("机密后的密文是___________:"+AESEncode(SECURITY_STR, "老司机开车了")); byte[]bytes=AESDecode(SECURITY_STR, AESEncode(SECURITY_STR, "老司机开车了")); System.out.println("解析的明文是___:"+new String(bytes)); } }
//运行结果
相关文章推荐
- java安全架构____AES加密原理(2)
- java安全架构____RSA加密原理(1)
- java安全架构____AES原理(1)
- java安全架构____RSA加密原理(2)
- java安全架构____MD5加密原理和简介
- java安全架构____java SHA加密原理
- Java安全架构____LinuxSSH公钥登录原理
- java安全架构____java DSA签名原理
- java安全架构____java DSA加密解密
- java安全架构____java HMAC加密
- java安全架构____java DSA数字签名原理
- java安全架构____java 秘钥对原理
- java安全架构____Hmac秘钥加密自己的摘要数据
- Java安全架构____RSA加密配置第三方加密库问题_javax.crypto.BadPaddingException: Decryption error
- java安全AES加密解密
- java安全架构____对称加密和非对称加密区别(对称秘钥,非对称秘钥)
- java安全架构____java SHA加密