关于AES加密算法在linux下解密失败的解决办法
前段时间项目要部署到linux上时遇到了这个问题,百度一下找到了解决方案,在这分享一下:
publicclassRSAEncrypt{
//密钥
privatestaticKeykey;
//KEY种子
privatestaticStringKEY_STR="keyString";
//常量
publicstaticfinalStringUTF_8="UTF-8";
publicstaticfinalStringAES="AES";
//静态初始化
static{
try{
//KEY生成器
KeyGeneratorgenerator=KeyGenerator.getInstance(AES);
//初始化算法,设置成“SHA1PRNG”是为了防止在linux环境下随机生成算法
SecureRandomsecureRandom=SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(KEY_STR.getBytes(UTF_8));
//128,192,256
generator.init(128,secureRandom);
//生成密钥
key=generator.generateKey();
generator=null;
}catch(Exceptione){
thrownewRuntimeException(e);
}
}
/**
*对源字符串加密,返回BASE64编码后的加密字符串
*
*@paramsource
*源字符串,明文
*@return密文字符串
*/
publicstaticStringencode(Stringsource){
try{
//根据编码格式获取字节数组
byte[]sourceBytes=source.getBytes(UTF_8);
//加密模式
Ciphercipher=Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE,key);
//加密后的字节数组
byte[]encryptSourceBytes=cipher.doFinal(sourceBytes);
//Base64编码器
BASE64Encoderbase64Encoder=newBASE64Encoder();
returnbase64Encoder.encode(encryptSourceBytes);
}catch(Exceptione){
//throw也算是一种return路径
thrownewRuntimeException(e);
}
}
/**
*对本工具类encode()方法加密后的字符串进行解码/解密
*
*@paramencrypted
*被加密过的字符串,即密文
*@return明文字符串
*/
publicstaticStringdecode(Stringencrypted){
//Base64解码器
BASE64Decoderbase64Decoder=newBASE64Decoder();
try{
//先进行base64解码
byte[]cryptedBytes=base64Decoder.decodeBuffer(encrypted);
//解密模式
Ciphercipher=Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE,key);
//解码后的字节数组
byte[]decryptStrBytes=cipher.doFinal(cryptedBytes);
//采用给定编码格式将字节数组变成字符串
returnnewString(decryptStrBytes,UTF_8);
}catch(Exceptione){
//这种形式确实适合处理工具类
thrownewRuntimeException(e);
}
}
以上所述是小编给大家介绍的关于AES加密算法在linux下解密失败的解决办法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!