####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);//根據密碼生成key if(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的IvParameterSpec byte[] 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);//根據密碼生成key if(key == null){ return null; } Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//建立密碼器"算法/模式/補碼方式" cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));//初始化,使用該模式,須要一個向量16byte的IvParameterSpec byte[] 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的key private 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加密