欢迎来到代码驿站!

Linux

当前位置:首页 > 服务器 > Linux

关于AES加密算法在linux下解密失败的解决办法

时间:2021-04-14 09:02:28|栏目:Linux|点击:

前段时间项目要部署到linux上时遇到了这个问题,百度一下找到了解决方案,在这分享一下:

public class RSAEncrypt {
// 密钥
private static Key key;
// KEY种子
private static String KEY_STR = "keyString";
// 常量
public static final String UTF_8 = "UTF-8";
public static final String AES = "AES";
// 静态初始化
static {
try {
// KEY 生成器
KeyGenerator generator = KeyGenerator.getInstance(AES);
// 初始化算法,设置成“SHA1PRNG”是为了防止在linux环境下随机生成算法
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(KEY_STR.getBytes(UTF_8));
//128,192,256
generator.init(128,secureRandom);
// 生成密钥
key = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 对源字符串加密,返回 BASE64编码后的加密字符串
*
* @param source
* 源字符串,明文
* @return 密文字符串
*/
public static String encode(String source) {
try {
// 根据编码格式获取字节数组
byte[] sourceBytes = source.getBytes(UTF_8);
// 加密模式
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE, key);
// 加密后的字节数组
byte[] encryptSourceBytes = cipher.doFinal(sourceBytes);
// Base64编码器
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(encryptSourceBytes);
} catch (Exception e) {
// throw 也算是一种 return 路径
throw new RuntimeException(e);
}
}
/**
* 对本工具类 encode() 方法加密后的字符串进行解码/解密
*
* @param encrypted
* 被加密过的字符串,即密文
* @return 明文字符串
*/
public static String decode(String encrypted) {
// Base64解码器
BASE64Decoder base64Decoder = new BASE64Decoder();
try {
// 先进行base64解码
byte[] cryptedBytes = base64Decoder.decodeBuffer(encrypted);
// 解密模式
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, key);
// 解码后的字节数组
byte[] decryptStrBytes = cipher.doFinal(cryptedBytes);
// 采用给定编码格式将字节数组变成字符串
return new String(decryptStrBytes, UTF_8);
} catch (Exception e) {
// 这种形式确实适合处理工具类
throw new RuntimeException(e);
}
}

上一篇:Wampserver2.5配置虚拟主机出现403 Forbidden的处理方案

栏    目:Linux

下一篇:linux环境不使用hadoop安装单机版spark的方法

本文标题:关于AES加密算法在linux下解密失败的解决办法

本文地址:http://www.codeinn.net/misctech/100724.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有