SecretKeySpec key = new SecretKeySpec(Arrays.copyOf(password.getBytes( "utf-8" ), 16 ), "AES" );
Cipher cipher = Cipher.getInstance( "AES/ECB/PKCS5Padding" );
byte [] byteContent = content.getBytes( "utf-8" );
cipher.init(Cipher.ENCRYPT_MODE, key);
byte [] result = cipher.doFinal(byteContent);
return result;
用Base64處理字節(jié)數(shù)組,,得到加密字符串
CSDN很多加密代碼的key生成的很復雜,,而且和在線加密不一樣,主要區(qū)別在于: 1. SecretKeySpec key = new SecretKeySpec(encodeKey, "AES"); 2. SecretKeySpec key = new SecretKeySpec(password.getBytes( ) , "AES" );
加密網(wǎng)站用的是第2個,,直接用key字符串的字節(jié)數(shù)組(一般取前16個字節(jié),,可用Arrays.copyOf(bytes,16)),。
第1個是先給key進行了一番加密操作,,再把它的字節(jié)數(shù)組給 SecretKeySpec
KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] encodeKey = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(encodeKey, "AES");
Cipher cipher = Cipher.getInstance("AES");//默認ECB模式 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent);
public static String AESDncode(String encodeRules,String content){ try { //1.構(gòu)造密鑰生成器,指定為AES算法,不區(qū)分大小寫 KeyGenerator keygen=KeyGenerator.getInstance("AES"); //2.根據(jù)ecnodeRules規(guī)則初始化密鑰生成器 //生成一個128位的隨機源,根據(jù)傳入的字節(jié)數(shù)組 keygen.init(128, new SecureRandom(encodeRules.getBytes())); //3.產(chǎn)生原始對稱密鑰 SecretKey original_key=keygen.generateKey(); //4.獲得原始對稱密鑰的字節(jié)數(shù)組 byte [] raw=original_key.getEncoded(); //5.根據(jù)字節(jié)數(shù)組生成AES密鑰 SecretKey key=new SecretKeySpec(raw, "AES"); //6.根據(jù)指定算法AES自成密碼器 Cipher cipher=Cipher.getInstance("AES"); //7.初始化密碼器,,第一個參數(shù)為加密(Encrypt_mode)或者解密(Decrypt_mode)操作,,第二個參數(shù)為使用的KEY cipher.init(Cipher.DECRYPT_MODE, key); //8.將加密并編碼后的內(nèi)容解碼成字節(jié)數(shù)組 byte [] byte_content= new BASE64Decoder().decodeBuffer(content); /* * 解密 */ byte [] byte_decode=cipher.doFinal(byte_content); String AES_decode=new String(byte_decode,"utf-8"); return AES_decode; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } //如果有錯就返加nulll return null; }
password就是秘鑰,有的用key,,有的用encodeRules 網(wǎng)站只是截取我們字符串字節(jié)的前16位字節(jié)數(shù)組作為秘鑰進行加密
128位密鑰,,用jdk自帶庫實現(xiàn) [參考1](https://blog.csdn.net/u013871100/article/details/80100992) [參考2](https://blog.csdn.net/qq_18870023/article/details/52183755) AES涉及幾個參數(shù):加密模式、補碼方式,、偏移量 經(jīng)驗證jdk默認的是ECB模式,,并不是參考中所說的CBC 因為,,ECB模式是不需要偏移的,,默認情況下插入偏移,從jdk報錯信息提示來看,,默認確定是ECB 代碼在下,,加密和解密都沒問題??墒羌用芙Y(jié)果和在線加密工具出的結(jié)果不一致 很費解為什么不一致,,參數(shù)設置都已經(jīng)一樣了,只能先這樣了 CBC需要IV,,即秘鑰偏移量
|