Java 如何實(shí)現(xiàn)AES加密
做360廣告的對(duì)接需要對(duì)密碼進(jìn)行AES加密,下面是點(diǎn)睛平臺(tái)文檔的描述:
(AES模式為CBC,加密算法MCRYPT_RIJNDAEL_128)對(duì)MD5加密后的密碼實(shí)現(xiàn)對(duì)稱加密。秘鑰是apiSecret 的前16位,向量是后16位,加密結(jié)果為64位數(shù)字和小寫字母。
用Java實(shí)現(xiàn)AES需要依賴Java加密擴(kuò)展(The Java Cryptography Extension,簡(jiǎn)稱JCE)的支持——主要是在javax下面的一些包。根據(jù)描述需要使用的算法為“AES/CBC/NoPadding”,實(shí)現(xiàn)方案如下:
public static String encode1(String src, String secretKey, String initialVector)throws Exception {Key key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), 'AES');AlgorithmParameterSpec spec = new IvParameterSpec(initialVector.getBytes(StandardCharsets.UTF_8));Cipher cipher = Cipher.getInstance('AES/CBC/NoPadding'); cipher.init(Cipher.ENCRYPT_MODE, key, spec);byte[] encrypted = cipher.doFinal(src.getBytes());return Hex.encodeHexString(encrypted);}
這里使用的 SecretKeySpec、 AlgorithmParameterSpec、 IvParameterSpec等類都是JCE提供的,通常在JVM環(huán)境下可以直接使用。 Hex.encodeHexString()方法則是由apache-commons-codec提供的。如果不想多引入一個(gè)依賴也可以使用下面的方法:
public static String toHexString(byte[] bytes) {StringBuilder builder = new StringBuilder();for (int i = 0; i < bytes.length; i++) {String hex = Integer.toHexString(0xFF & bytes[i]);if (hex.length() < 2) {builder.append(0);}builder.append(hex);}return builder.toString();}
下面是為這個(gè)加密方法寫的單元測(cè)試:
@Testpublic void encode1() throws Exception {String src = 'http://www.cgvv.com.cn/bcjs/098f6bcd4621d373cade4e832627b4f6';String key = '1234567891234567';String iv = '8912345678912345'; String result = AES.encode1(src, key, iv);String expect = '21fa89586f4a299545307b99036a082e135b52d3f63f93541e4291669a0de1de';Assert.assertEquals(expect, result);}
這里的代碼大體上能夠滿足360廣告的對(duì)接需求了。但是因?yàn)閖dk11偶爾對(duì)一些javax擴(kuò)展包的不支持,我有些不太喜歡這個(gè)方案。另外在一些資料中也了解到j(luò)dk對(duì)AES 256加密是有一些限制的,要響應(yīng)相關(guān)限制需要引入一個(gè)授權(quán)文件或者更換jdk,這就有些難接受了。種種原因吧,我需要一個(gè)替換方案。
最開(kāi)始我以為在apache-common-codec中會(huì)有相關(guān)方案,但是結(jié)果是讓人失望的。不過(guò)還好,最終我找到了Bouncy Castle。以下是關(guān)于Bouncy Castle的一些描述:
Bouncy Castle 是一種用于Java平臺(tái)的開(kāi)放源碼的輕量級(jí)密碼算法包。它支持大量的密碼算法,并提供 JCE 1.2.1 的實(shí)現(xiàn)。Bouncy Castle是輕量級(jí)的,從J2SE 1.4到J2ME(包括MIDP)平臺(tái),它都可以運(yùn)行。它是在MIDP上運(yùn)行的唯一完整的密碼術(shù)包。
使用Bouncy Castle提供的能力必然需要先引入相關(guān)的依賴。針對(duì)不同的jdk版本,Bouncy Castle都有提供對(duì)應(yīng)的Cryptography Provider。比如我使用的是JDK1.8,對(duì)應(yīng)的就是bcprov-jdk15to18,相關(guān)的依賴如下:
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15to18</artifactId> <version>1.66</version></dependency>
基于Bouncy Castle實(shí)現(xiàn)的360點(diǎn)睛平臺(tái)AES加密處理如下:
public static String encode2(String value, String secretKey, String initialVector) {try {BufferedBlockCipher cipher = getCipher(secretKey, initialVector);byte[] bytes = value.getBytes(StandardCharsets.UTF_8);byte[] out = new byte[cipher.getOutputSize(bytes.length)];int len = cipher.processBytes(bytes, 0, bytes.length, out, 0);len += cipher.doFinal(out, len);byte[] arr = new byte[len];System.arraycopy(out, 0, arr, 0, len);return Hex.toHexString(arr);} catch (Exception e) {throw new EncryptException('Data encryption failed. ' + e.getMessage());}} private static BufferedBlockCipher getCipher(String secretKey, String iniVector) {try {byte[] iv = iniVector.getBytes(StandardCharsets.UTF_8);CipherParameters params = new ParametersWithIV(new KeyParameter(secretKey.getBytes(StandardCharsets.UTF_8)), iv);BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine()));cipher.init(true, params);return cipher;} catch (Exception ex) {throw new EncryptException('Cannot intialize Bouncy Castle cipher. ' + ex.getMessage());}}
因?yàn)?60點(diǎn)睛平臺(tái)要求使用的加密key沒(méi)有超過(guò)256位,所以兩個(gè)方案都是行得通的。
我比較喜歡Bouncy Castle這個(gè)方案,這個(gè)方案相對(duì)較輕量,并且不依賴JCE。但是這個(gè)方案的不足之處也恰恰在于此:Java中的SSL層,JSSE和XML加密庫(kù)都依賴到JCE,而且AES Key長(zhǎng)度的校驗(yàn)是在 Cipher類中進(jìn)行的,在這些場(chǎng)景下Bouncy Castle也很難起到作用。
以上就是Java 如何實(shí)現(xiàn)AES加密的詳細(xì)內(nèi)容,更多關(guān)于Java 實(shí)現(xiàn)AES加密的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. vue實(shí)現(xiàn)移動(dòng)端返回頂部2. asp讀取xml文件和記數(shù)3. vue 驗(yàn)證兩次輸入的密碼是否一致的方法示例4. xml中的空格之完全解說(shuō)5. 多個(gè)SpringBoot項(xiàng)目采用redis實(shí)現(xiàn)Session共享功能6. python基于scrapy爬取京東筆記本電腦數(shù)據(jù)并進(jìn)行簡(jiǎn)單處理和分析7. python利用opencv實(shí)現(xiàn)顏色檢測(cè)8. CSS自定義滾動(dòng)條樣式案例詳解9. Python如何實(shí)現(xiàn)感知器的邏輯電路10. PHP實(shí)現(xiàn)基本留言板功能原理與步驟詳解
