java aes 工具类_AESUtil Java AES 加密解密工具类

package com.singlee.util;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.net.util.Base64;

/**

* AES工具类

*

* * 因为某些国家的进口管制限制,Java发布的运行环境包中的加解密有一定的限制。比如默认不允许256位密钥的AES加解密,解决方法就是修改策略文件。

* 替换的文件:%JDK_HOME%\jre\lib\security\local_policy.jar

* 参考: http://czj4451.iteye.com/blog/1986483

*/

public class AESUtil {

// 密钥

public static String key = "AD42F6697B035B7580E4FEF93BE20BAD";

private static String charset = "utf-8";

// 偏移量

private static int offset = 16;

private static String transformation = "AES/CBC/PKCS5Padding";

private static String algorithm = "AES";

/**

* 加密

*

* @param content

* @return

*/

public static String encrypt(String content) {

return encrypt(content, key);

}

/**

* 解密

*

* @param content

* @return

*/

public static String decrypt(String content) {

return decrypt(content, key);

}

/**

* 加密

*

* @param content

* 需要加密的内容

* @param key

* 加密密码

* @return

*/

public static String encrypt(String content, String key) {

try {

SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm);

IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);

Cipher cipher = Cipher.getInstance(transformation);

byte[] byteContent = content.getBytes(charset);

cipher.init(Cipher.ENCRYPT_MODE, skey, iv);// 初始化

byte[] result = cipher.doFinal(byteContent);

return new Base64().encodeToString(result); // 加密

} catch (Exception e) {

LogUtil.exception(e);

}

return null;

}

/**

* AES(256)解密

*

* @param content

* 待解密内容

* @param key

* 解密密钥

* @return 解密之后

* @throws Exception

*/

public static String decrypt(String content, String key) {

try {

SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm);

IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset);

Cipher cipher = Cipher.getInstance(transformation);

cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化

byte[] result = cipher.doFinal(new Base64().decode(content));

return new String(result); // 解密

} catch (Exception e) {

LogUtil.exception(e);

}

return null;

}

public static void main(String[] args) throws Exception {

String s = "hello world";

// 加密

System.out.println("加密前:" + s);

String encryptResultStr = encrypt(s);

System.out.println("加密后:" + encryptResultStr);

// 解密

System.out.println("解密后:" + decrypt(encryptResultStr));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值