您的位置:首页 > 编程语言 > Java开发

Java中使用AES对数据进行加密

2016-08-29 19:14 459 查看
此处介绍的是Java自带的AES加密算法,并且支持中文,具体参数如下:

算法模式:ECB 密钥

长度:128bits 16位长

偏移量: 默认

补码方式:PKCS5Padding

解密串编码方式:base64

秘钥为16为长度的字符串。

1. 加密函数

/**
* 使用参数中的密钥加密
* @param 明文
* @param 密钥
* @return 密文
*/
public static String Encrypt(String sSrc, String sKey) {
try{
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}catch(Exception e){
e.printStackTrace();
return null;
}
}


2.解密函数

/**
* 使用参数中的密钥解密
* @param 密文
* @param 密钥
* @return 明文
*/
public static String Decrypt(String sSrc, String sKey) {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}


3.测试方法

String password = "ABCDEFGHIJKLMNOP";
String content1 = "我的博客名是geekfly";
System.out.println("加密前:" + content1);
String content2 = Encrypt(content1, password);
System.out.println("加密后:" + content2);
String content3 = Decrypt(content2, password);
System.out.println("解密后:" + content3);


结果

加密前:我的博客名是geekfly

加密后:ef96GdBlS/TAX8R9mGEuA3w+kpcvBDu/8dI1qupbPQA=

解密后:我的博客名是geekfly
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: