赞
踩
java AES 加密算法
SecureRandom 类中 setSeed()底层调用的是 native 方法.所以 造成了 不同环境之间 随机数出现了差别。导致解密不一致问题
对加密程序 添加如下两行 代码控制 随机数即可解决问题。
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(PASSWORD.getBytes());
文件如下
package com.lyh;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.axis.encoding.Base64;
import org.apache.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AESUtils {
/**
* 加密
*
* @param content 需要加密的内容
* @param secureKey 加密秘钥
* @return
*/
public static String encrypt(String content, String secureKey) {
try {
if (StringUtils.isEmpty(content) || StringUtils.isEmpty(secureKey)) {
return null;
}
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(secureKey.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return encodeBASE64(result); // 加密
} catch (Exception e) {
log.error("加密错误.", e);
}
return null;
}
/**
* 解密
*
* @param content 待解密内容
* @param password secureKey
* @return
*/
public static String decrypt(String content, String secureKey) {
try {
if (StringUtils.isEmpty(content) || StringUtils.isEmpty(secureKey)) {
return null;
}
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(secureKey.getBytes());
kgen.init(128, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] base64Dec = Base64.decode(content);
byte[] result = cipher.doFinal(base64Dec);
return new String(result);
} catch (Exception e) {
log.warn("解密错误,错误信息是:{}", e);
}
return null;
}
public static String encodeBASE64(byte[] content) throws Exception {
if (content == null || content.length == 0)
return null;
try {
return Base64.encode(content);
} catch (Exception e) {
log.error("Base64 encode error.", e);
return null;
}
}
}
文章参考 https://www.oschina.net/question/2000201_2181710
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。