您的位置:首页 > 其它

对称加密之AES加密

2016-04-03 11:52 267 查看
加密和解密过程中,我们一般使用byte,因为这样不容易产生乱码,如果直接是String类型,被加密解密后的String,对中文来说,前后的Unicode是否一致,就很难保证了。

之前说了使用异或运算符加密。在Java中,有API提供,让我们实现AES对称加密。

和之前的简单加密相比,AES加密对密钥是有要求的,所以,需要设计算法,使得密钥符合要求

下面在一个类中实现AES对称加密

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

//引用下面的sun.misc.BASE64Decoder和BASE64Encoder包会有限制,不喜欢的,就加入xstream-1.4.3.jar包
import com.thoughtworks.xstream.core.util.Base64Encoder;

//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;
/**
* @author Administrator, 2016年4月2日 下午4:56:27
* AES加密对长度有限制
*/
public class AESEncryption {
private static String charset = "utf-8";

public static String encrypt(String src, String key) {
try {
//创建密钥
byte[] buf_key = key.getBytes(charset);
//创建一个空的16位字节数组,默认0
byte[] buf = new byte[16];
//过短,补零;过长丢弃
for (int i = 0; i < buf_key.length && i < buf.length; i++) {
buf[i] = buf_key[i];
}
SecretKeySpec secretKey = new SecretKeySpec(buf,"AES");

//加密
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] out = cipher.doFinal(src.getBytes(charset));

//转为串
return new Base64Encoder().encode(out);

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

public static String decrypt(String src, String key) {
try {
// 处理密钥
byte[] buf_key = key.getBytes(charset);
// 创建一个空的16位字节数组,默认0
byte[] buf = new byte[16];
// 过短,补零;过长丢弃
for (int i = 0; i < buf_key.length && i < buf.length; i++) {
buf[i] = buf_key[i];
}
SecretKeySpec secretKey = new SecretKeySpec(buf, "AES");

//密码还原
buf = new BASE64Decoder().decodeBuffer(src);

//解密
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] out = cipher.doFinal(buf);
//转为串
return new String(out,charset);

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

public static void main(String[] args) {
String str = "eqwi&434p";
String key = AESEncryption.encrypt(str, "Eng");
System.out.println(key);

String de = AESEncryption.decrypt(key, "Eng");
System.out.println(de);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: