java web与android互通的aes算法
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
轉載于:https://my.oschina.net/jackruan/blog/538547
總結
以上是生活随笔為你收集整理的java web与android互通的aes算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孕期老是梦到老公出轨怎么回事
- 下一篇: 梦到自己的玉镯断了几段是什么意思