将 Java的 AES 加解密算法转换为Ruby

狼王_ 2017-07-17 11:07:28

/**
* AES 解密 以String密文输入,String明文输出
*
* @param strMi
* 加密后转换为base64格式的字符串
* @param strKey
* 加密用的Key
* @return 解密的字符串 首先base64解密,而后在用key解密
*/
public static String getDecString(String strMi, String strKey) {

try {
SecretKey secretKey = getKey(strKey);
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] bytes = Base64.decode(strMi);
byte[] result = cipher.doFinal(bytes);
String strMing = new String(result, "utf-8");

return strMing; // 解密
} catch (Exception e) {
e.printStackTrace();
}
return null;

}

/**
*
* @param strKey 密钥
* @return 安全密钥
* 指定具体产生key的算法,跨操作系统产生 SecretKey,如果不指定,各种操作系统产生的安全key不一致。
*/
public static SecretKey getKey(String strKey) {
try {
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("初始化密钥出现异常");
}
}

/**
* 加密以String明文输入,String密文输出
*
* @param strContent
* 待加密字符串
* @param strKey
* 加密用的Key
* @return 加密后转换为base64格式字符串
*/
public static String getEncString(String strContent, String strKey) {
String strMi = "";
try {
SecretKey secretKey = getKey(strKey);
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
byte[] byteContent = strContent.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);

strMi = Base64.encode(result);

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return strMi; // 加密
}
...全文
824 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

2,763

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ruby/Rails
社区管理员
  • Ruby/Rails社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧