一般都听说过MD5加密技术,MD5加密确实强大。但那是非对称加密技术,也就是说从密文变成明文不是那么容易。当我们需要一种对称性加密技术,MD5就不适用了。比如视频加密解密,此时就可以用ASE加密解密了。
AES有更安全、灵活、有效率等优点,使用范围也很广,所以今天就讲讲AES加密如何使用,这里以java开展。
密钥
就是把明文转换为密文,密文转换为明文的一把钥匙。接下来我们会用ASE加密技术生成一把密钥。
public void generateSecretKey() {
KeyGenerator keyGenerator = null;
FileOutputStream fos = null;
try {
keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);//size
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
fos = new FileOutputStream("key");
fos.write(keyBytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
keyGenerator.init(128); 这里是初始化密钥的长度。翻看底层代码,发现密钥支持的长度为:128, 192 or 256。我们这里是128位的长度,也就是16byte。
补充: 刚学习的时候,看到网上有人把密钥(字节码)转变成字符串保存,然后用来加密解密的时候,很有可能出错。因为不同语言的原因,字符串转变成字节码就有可能不再是原来的字节码了。
密钥生成后,在项目目录下可以找到一个key文件。
加密
将明文和密钥一起,作为参数传入。
/**
* ASE 加密
* @param str 明文
* @param key 秘钥
* @return
*/
public static String enStr(String str, byte[] key) {
Cipher cipher = null;
SecretKey generateKey = null;
try {
generateKey = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, generateKey);
byte[] resultBytes = cipher.doFinal(str.getBytes());
return Hex.encodeHexString(resultBytes);
} catch (Exception e) {
logger.error("AES加密出错", e);
}
return null;
}
解密
解密就是加密的互逆过程,所以代码很类似。
/**
* 解密
* @param key 秘钥
* @param str 密文
* @return
*/
public static String deStr(String str, byte[] key) {
Cipher cipher = null;
SecretKey generateKey = null;
try {
generateKey = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, generateKey);
byte[] result = Hex.decodeHex(str.toCharArray());
return new String(cipher.doFinal(result));
} catch(Exception e) {
logger.error("ASE解密出错", e);
}
return null;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。