2019独角兽企业重金招聘Python工程师标准>>>
####Java实现代码
//可自定义保证16btye即可private static final byte[] IV = {16, 26, -35, 23, 34, 125, -5, -4, -8, -9, -15, -78, 90, -8, -99, 100};public static byte[] encrypt(String content, String password) {try {SecretKeySpec key = getKey(password);//根据密码生成keyif(key == null){return null;}Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器"算法/模式/补码方式"byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV));//初始化,使用该模式,需要一个向量16byte的IvParameterSpecbyte[] result = cipher.doFinal(byteContent);// 加密return result;} catch (Exception e) {e.printStackTrace();return null;}}public static String encryptToStr(String content, String password) {byte[] bytes = encrypt(content, password);if(bytes == null){return null;}return Base64Util.encode(bytes);}public static byte[] decrypt(byte[] content, String password) {try {SecretKeySpec key = getKey(password);//根据密码生成keyif(key == null){return null;}Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//创建密码器"算法/模式/补码方式"cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));//初始化,使用该模式,需要一个向量16byte的IvParameterSpecbyte[] result = cipher.doFinal(content);// 解密return result;} catch (Exception e) {e.printStackTrace();return null;}}public static String decryptFromStr(String encodeStr, String password) {byte[] encodeBytes = Base64Util.decodeToBytes(encodeStr);byte[] bytes = decrypt(encodeBytes, password);if(bytes == null){return null;}return new String(bytes);}//根据密码生成16byte的keyprivate static SecretKeySpec getKey(String password){try {byte[] passwdBytes = password.getBytes("utf-8");if(passwdBytes.length < 16){return null;}//简单转换为16byte,建议用复杂的转换以防被知道密码后破解byte[] bytes = new byte[16];for(int i = 0; i < 16; i++){bytes[i] = passwdBytes[i];}return new SecretKeySpec(bytes, "AES");}catch(Exception e){e.printStackTrace();return null;}}
####AES加密模式和填充方式 | 算法/模式/填充 | 16字节加密后数据长度 | 不满16字节加密后长度 | | ------------- |:-------------:|:-----:| |AES/CBC/NoPadding|16| 不支持| |AES/CBC/PKCS5Padding|32|16 |AES/CBC/ISO10126Padding|32|16 |AES/CFB/NoPadding|16|原始数据长度 |AES/CFB/PKCS5Padding|32|16 |AES/CFB/ISO10126Padding|32|16 |AES/ECB/NoPadding|16|不支持 |AES/ECB/PKCS5Padding|32|16 |AES/ECB/ISO10126Padding|32|16 |AES/OFB/NoPadding|16|原始数据长度 |AES/OFB/PKCS5Padding|32|16 |AES/OFB/ISO10126Padding|32|16 |AES/PCBC/NoPadding|16|不支持 |AES/PCBC/PKCS5Padding|32|16 |AES/PCBC/ISO10126Padding|32|16