1. 现象

windows操作系统下进行"123456"的AES加密

encrypted message is below :
QLNYZyjRnKF/zxAjzDt/lw==
decrypted message is below :
123456
 
阿里云服务器,同样是"123456"的密码,每次加密结果都不一样,且不是QLNYZyjRnKF/zxAjzDt/lw==,解密是报错的
 
2.解决方法
 
经过检查之后,定位在生成KEY的方法上,如下:
public static Key getSecretKey(String key) throws Exception {
SecretKey secureKey = null;
if (key == null) {
key = "";
}
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(new SecureRandom(key.getBytes()));
secureKey = keyGenerator.generateKey();
return secureKey;
}

修改到如下方式,问题解决:

public static Key getKey(String strKey) {
try {
if (strKey == null) {
strKey = "";
}
KeyGenerator _generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(strKey.getBytes());
_generator.init(128, secureRandom);
return _generator.generateKey();
} catch (Exception e) {
throw new RuntimeException(" 初始化密钥出现异常 ");
}
}
3.原因分析
 
原因一:
SecureRandom 实现完全隨操作系统本身的内部状态,除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。
 
原因二:
 
1、加密完byte[] 后,需要将加密了的byte[] 转换成base64保存,如: 
BASE64Encoder base64encoder = new BASE64Encoder(); 
String encode=base64encoder.encode(bytes);

2、解密前,需要将加密后的字符串从base64转回来再解密,如: 
BASE64Decoder base64decoder = new BASE64Decoder(); 
byte[] encodeByte = base64decoder.decodeBuffer(str); 

 
4. 附录完整代码
package com.binfoo.wechat.util;

import java.security.Key;
import java.security.SecureRandom; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class SecurityUtil {
public static String DES = "AES"; // optional value AES/DES/DESede public static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede public static Key getKey(String strKey) {
try {
if (strKey == null) {
strKey = "";
}
KeyGenerator _generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(strKey.getBytes());
_generator.init(128, secureRandom);
return _generator.generateKey();
} catch (Exception e) {
throw new RuntimeException(" 初始化密钥出现异常 ");
}
} public static String encrypt(String data, String key) throws Exception {
SecureRandom sr = new SecureRandom();
Key secureKey = getKey(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
byte[] bt = cipher.doFinal(data.getBytes());
String strS = new BASE64Encoder().encode(bt);
return strS;
} public static String decrypt(String message, String key) throws Exception {
SecureRandom sr = new SecureRandom();
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
Key secureKey = getKey(key);
cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
byte[] res = new BASE64Decoder().decodeBuffer(message);
res = cipher.doFinal(res);
return new String(res);
} public static void main(String[] args) throws Exception {
String message = "123456";
String key = "landLeaf";
String encryptMsg = encrypt(message, key);
System.out.println("encrypted message is below :");
System.out.println(encryptMsg); String decryptedMsg = decrypt(encryptMsg, key);
System.out.println("decrypted message is below :");
System.out.println(decryptedMsg);
}
}
 

Linux进行AES加密每次结果都不一致并且解密失败报错的更多相关文章

  1. linux 下通过xhost进入图形界面,经常会出现报错“unable to open display”

    linux 下通过xhost进入图形界面,经常会出现报错“unable to  open display” linux下的操作步骤如下: [root@localhost ~]# vncserver N ...

  2. 因OpenCV版本不一致所引发的报错

    目录 一 因OpenCV版本不一致所引发的报错 注:原创不易,转载请务必注明原作者和出处,感谢支持! 一 因OpenCV版本不一致所引发的报错 今天遇到了一个很有意思的报错. 事情是这样的, 在编译& ...

  3. R︱Linux+Rstudio Server尝鲜笔记(打造最佳Rstudio体验+报错的解决方案)

    Rstudio Server 是Rstudio开发的基于R语言的网页版(只能在Linux),你在手机上都可以运行R,还是挺方便的.就是配置起来有点麻烦.      官方下载链接:https://www ...

  4. 进击的java - tomcat的安装,配置都正确之后,还是报错

    1.问题 配置Apatch Tomcat过程报错: The CATALINA_HOME environment variable is not defined correctly.This envir ...

  5. linux查看与修改交换内存配置(解决zabbix-agent启动报错)

    问题 zabbix-agent在一台centos6.5上启动报错: cannot allocate shared memory of size 949056: [28] No space left o ...

  6. HADOOP HA 报错 - 所有 namenode 都是standby --集群报错: Operation category READ is not supported in state standby

    报错: 经过查看集群的jps如下: ==================== hadoop01 jps =================== FsShell ResourceManager Name ...

  7. 环境jdk、编码不一致造成的项目报错

    一个项目在eclipse 中可以运行 , 到另一个eclipse 中不能运行,多是因为jdk过低.包没有引人.环境jdk.编码不一致造成的.或者是因为编译文件在另一个环境里跟JDK等 不匹配. 解决办 ...

  8. linux启动jmeter(二十三),执行./jmeter.sh报错解决方法(转载)

    转载自 http://www.cnblogs.com/yangxia-test 1.l-bash: ./jmeter.sh: Permission denied解决办法:jmeter.sh的执行权限改 ...

  9. android 上AES解密是报错javax.crypto.BadPaddingException: pad block corrupted

    网上看到两种方法: 1.SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(key), "AES"); private sta ...

随机推荐

  1. Golang学习 - strconv 包--数据类型转换

    // 将布尔值转换为字符串 true 或 false func FormatBool(b bool) string // 将字符串转换为布尔值 // 它接受真值:1, t, T, TRUE, true ...

  2. ansible 拷贝文件并重启服务

    Ansible 安装 只需要在ansible 服务器上安装 yum install -y epel-release yum install -y ansible     服务器生成密钥对 ssh-ke ...

  3. mysql中的coalesce用法

    在mysql中,其实有不少方法和函数是很有用的,这次介绍一个叫coalesce的,拼写十分麻烦,但其实作用是将返回传入的参数中第一个非null的值,比如    SELECT COALESCE(NULL ...

  4. table内容强制换行

    为防止文字过长而撑坏表格,一般我们需要通过css使td中内容强制换行.分别给table和td加一条样式即可实现: <meta charset="utf-8"> < ...

  5. 对 url 中含有的中文进行转码操作

    对 url 中含有的中文进行转码操作 一般情况下,将带有中文的 url 拷贝到开发工具,开发工具都会有相应的转码(自动转码), 现在大部分的浏览器也可以对含有中文的 url 进行转码(自动转码) 情景 ...

  6. 有关datatables的非常规教程

    有关datatables的非常规教程 1. //$.fn.dataTable.tables({ visible: true, api: true }).columns.adjust(); table. ...

  7. Angular4图片上传预览路径不安全问题

    在Angular4中,通过input:file上传选择图片本地预览的时候,通过window.URL.createObjectURL获取的url赋值给image的src出现错误: WARNING: sa ...

  8. 搭建VUE项目的准备(利用vue-cli来构建项目)

    首先需要明确的是:Vue.js 不支持 IE8 及其以下 IE 版本,一般用与移动端,基础:开启最高权限的DOS命令(否则会出现意外的错误提示)   注意:个人小推荐如果我们不知道如何才能开启最高权限 ...

  9. Ubuntu下Maven配置与Maven项目创建教程

    一. Ubuntu下Maven配置 windows下Maven配置参考http://www.cnblogs.com/LexMoon/p/JavaMaven.html ubuntu下Maven地址htt ...

  10. 业余草分享100套精选1000G架构师资料课程(超1T的IT学习资料免费送)

    业余草分享100套精选1000G架构师资料课程(超1T的IT学习资料免费送). 超过1024G的IT学习资料免费领取,你值得拥有! 领取资源方式,关注“业余草”公众号,回复对应的关键字 01.回复”我 ...