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生成的很復(fù)雜,而且和在線加密不一樣,主要區(qū)別在于: 1. SecretKeySpec key = new SecretKeySpec(encodeKey, "AES"); 2. SecretKeySpec key = new SecretKeySpec(password.getBytes( ) , "AES" );
加密網(wǎng)站用的是第2個(gè),直接用key字符串的字節(jié)數(shù)組(一般取前16個(gè)字節(jié),可用Arrays.copyOf(bytes,16))。
第1個(gè)是先給key進(jìn)行了一番加密操作,再把它的字節(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");//默認(rèn)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ū)分大小寫(xiě) KeyGenerator keygen=KeyGenerator.getInstance("AES"); //2.根據(jù)ecnodeRules規(guī)則初始化密鑰生成器 //生成一個(gè)128位的隨機(jī)源,根據(jù)傳入的字節(jié)數(shù)組 keygen.init(128, new SecureRandom(encodeRules.getBytes())); //3.產(chǎn)生原始對(duì)稱密鑰 SecretKey original_key=keygen.generateKey(); //4.獲得原始對(duì)稱密鑰的字節(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.初始化密碼器,第一個(gè)參數(shù)為加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二個(gè)參數(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(); } //如果有錯(cuò)就返加nulll return null; }
password就是秘鑰,有的用key,有的用encodeRules 網(wǎng)站只是截取我們字符串字節(jié)的前16位字節(jié)數(shù)組作為秘鑰進(jìn)行加密
128位密鑰,用jdk自帶庫(kù)實(shí)現(xiàn) [參考1](https://blog.csdn.net/u013871100/article/details/80100992) [參考2](https://blog.csdn.net/qq_18870023/article/details/52183755) AES涉及幾個(gè)參數(shù):加密模式、補(bǔ)碼方式、偏移量 經(jīng)驗(yàn)證jdk默認(rèn)的是ECB模式,并不是參考中所說(shuō)的CBC 因?yàn)椋珽CB模式是不需要偏移的,默認(rèn)情況下插入偏移,從jdk報(bào)錯(cuò)信息提示來(lái)看,默認(rèn)確定是ECB 代碼在下,加密和解密都沒(méi)問(wèn)題??墒羌用芙Y(jié)果和在線加密工具出的結(jié)果不一致 很費(fèi)解為什么不一致,參數(shù)設(shè)置都已經(jīng)一樣了,只能先這樣了 CBC需要IV,即秘鑰偏移量
|