通常都据说过MD5加密技术,MD5加密确实强大。但那是非对称加密技术,也就是说从密文变成明文不是那么容易。当咱们须要一种对称性加密技术,MD5就不适用了。好比视频加密解密,此时就能够用ASE加密解密了。java
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。加密
补充: 刚学习的时候,看到网上有人把密钥(字节码)转变成字符串保存,而后用来加密解密的时候,颇有可能出错。由于不一样语言的缘由,字符串转变成字节码就有可能再也不是原来的字节码了。code
密钥生成后,在项目目录下能够找到一个key文件。视频
将明文和密钥一块儿,做为参数传入。ip
/** * 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; }
解密就是加密的互逆过程,因此代码很相似。ci
/** * 解密 * @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; }