您的位置:首页 > 其它

加密方式-对称加密(AES)

2016-12-28 11:08 127 查看
对称加密中AES是比较常用,DES因为安全性比不上AES已经用的较少

对称加密:是指加密解密都是一个密钥,通过改密钥加密,也通过它解密。

1.加密

/**
* 加密
*
* @param content 需要加密的内容
* @param key 密钥
* @return
*/
public static byte[] encrypt(String content, String key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keys = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");//创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, keys);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}


2.解密

/**
* 解密
*
* @param content 待解密内容
* @param key 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String key) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec keys = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");//创建密码器
cipher.init(Cipher.DECRYPT_MODE, keys);// 初始化
byte[] result = cipher.doFinal(content);
return 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();
}
return null;
}


3.测试

下面提供两种方式(原来避免转字符串乱码)

1. 通过Base64(强烈推荐)来转
org.apache.commons.codec.binary.Base64

public static void main(String[] args) {

//1.字符串经过加密得到byte数组
String content = "my name is libra_ts";
String key = "1234567812345678";
byte[] result = encrypt(content, key);

//2.将byte数组用base64转码成字符串
String strs = Base64.encodeBase64String(result);

//3.传输(我这里直接打印了,项目中一般是进行网络传输)
System.out.println("==经过加密和BASE64转码后=="+ strs);

//4.将字符串用base64解码成byte数组
byte[]b1 = Base64.decodeBase64(strs);

//5.解密
byte[]j1 = decrypt(b1, key);

//6.输出加密之前的内容
System.out.println(new String(j1));

}

2. 通过进制转换
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}

/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}

public static void main(String[] args) {
String content = "name=\"libra_ts\"";
String key = "FTGYHUJKML56SYTWsddd=8n2ndsn3SE6Bnh";

byte[] result = encrypt(content, key);
// 二进制转16进制
String encryptResultStr = parseByte2HexStr(result);
System.out.println("==加密后==" + new String(results));

// 16进制转二进制
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] results = decrypt(decryptFrom, key);
System.out.println("==解密后==" + new String(results));
}


因为加密后的byte数组是不能强制转换成字符串的,也就是说字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修改,推荐采用Base64转码,也可以考虑将二进制数据转换成十六进制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: