溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JDK自帶方法實(shí)現(xiàn)AES對(duì)稱加密

發(fā)布時(shí)間:2020-07-23 17:13:54 來源:網(wǎng)絡(luò) 閱讀:283 作者:jjjyyy66 欄目:網(wǎng)絡(luò)安全

請看代碼。

JDK自帶方法實(shí)現(xiàn)AES對(duì)稱加密

  1 package jdbc.pro.lin;  2   3 import java.security.InvalidAlgorithmParameterException;  4 import java.security.InvalidKeyException;  5 import java.security.NoSuchAlgorithmException;  6   7 import javax.crypto.BadPaddingException;  8 import javax.crypto.Cipher;  9 import javax.crypto.IllegalBlockSizeException; 10 import javax.crypto.KeyGenerator; 11 import javax.crypto.NoSuchPaddingException; 12 import javax.crypto.SecretKey; 13 import javax.crypto.spec.IvParameterSpec; 14 import javax.crypto.spec.SecretKeySpec; 15  16 import org.apache.commons.codec.binary.Base64; 17  18 public class MyAES { 19     /** 20      * 注意key和加密用到的字符串是不一樣的 加密還要指定填充的加密模式和填充模式 AES密鑰可以是128或者256,加密模式包括ECB, CBC等 21      * ECB模式是分組的模式,CBC是分塊加密后,每塊與前一塊的加密結(jié)果異或后再加密 第一塊加密的明文是與IV變量進(jìn)行異或 22      */ 23     public static final String KEY_ALGORITHM = "AES"; 24     public static final String ECB_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; 25     public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; 26     public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world"; 27  28     /** 29      * IV(Initialization Value)是一個(gè)初始值,對(duì)于CBC模式來說,它必須是隨機(jī)選取并且需要保密的 30      * 而且它的長度和密碼分組相同(比如:對(duì)于AES 128為128位,即長度為16的byte類型數(shù)組) 31      * 
 32      */ 33     public static final byte[] IVPARAMETERS = new byte[] { 1, 2, 3, 4, 5, 6, 7, 34             8, 9, 10, 11, 12, 13, 14, 15, 16 }; 35  36     public static void main(String[] arg) { 37         byte[] secretBytes = generateAESSecretKey(); 38         SecretKey key = restoreSecretKey(secretBytes); 39         byte[] encodedText = AesEcbEncode(PLAIN_TEXT.getBytes(), key); 40  41         System.out.println("AES ECB encoded with Base64: " + Base64.encodeBase64String(encodedText)); 42         System.out.println("AES ECB decoded: " 43                 + AesEcbDecode(encodedText, key)); 44  45          46          47         encodedText = AesCbcEncode(PLAIN_TEXT.getBytes(), key, IVPARAMETERS); 48          49          50         System.out.println("AES CBC encoded with Base64: " + Base64.encodeBase64String(encodedText)); 51         System.out.println("AES CBC decoded: " 52                 + AesCbcDecode(encodedText, key, 53                         IVPARAMETERS)); 54     } 55  56     /** 57      * 使用ECB模式進(jìn)行加密。 加密過程三步走: 1. 傳入算法,實(shí)例化一個(gè)加解密器 2. 傳入加密模式和密鑰,初始化一個(gè)加密器 3. 58      * 調(diào)用doFinal方法加密 59      * 
 60      * @param plainText 61      * @return 62      */ 63     public static byte[] AesEcbEncode(byte[] plainText, SecretKey key) { 64  65         try { 66  67             Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM); 68             cipher.init(Cipher.ENCRYPT_MODE, key); 69             return cipher.doFinal(plainText); 70         } catch (NoSuchAlgorithmException | NoSuchPaddingException 71                 | InvalidKeyException | IllegalBlockSizeException 72                 | BadPaddingException e) { 73             // TODO Auto-generated catch block 74             e.printStackTrace(); 75         } 76         return null; 77     } 78  79     /** 80      * 使用ECB解密,三步走,不說了 81      * 
 82      * @param decodedText 83      * @param key 84      * @return 85      */ 86     public static String AesEcbDecode(byte[] decodedText, SecretKey key) { 87         try { 88             Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM); 89             cipher.init(Cipher.DECRYPT_MODE, key); 90             return new String(cipher.doFinal(decodedText)); 91         } catch (NoSuchAlgorithmException | NoSuchPaddingException 92                 | InvalidKeyException | IllegalBlockSizeException 93                 | BadPaddingException e) { 94             // TODO Auto-generated catch block 95             e.printStackTrace(); 96         } 97         return null; 98  99     }100 101     /**102      * CBC加密,三步走,只是在初始化時(shí)加了一個(gè)初始變量103      * 
104      * @param plainText105      * @param key106      * @param IVParameter107      * @return108      */109     public static byte[] AesCbcEncode(byte[] plainText, SecretKey key,110             byte[] IVParameter) {111         try {112             IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);113 114             Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);115             cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);116             return cipher.doFinal(plainText);117 118         } catch (NoSuchAlgorithmException | NoSuchPaddingException119                 | InvalidKeyException | InvalidAlgorithmParameterException120                 | IllegalBlockSizeException | BadPaddingException e) {121             // TODO Auto-generated catch block122             e.printStackTrace();123         }124         return null;125     }126 127     /**128      * CBC 解密129      * 
130      * @param decodedText131      * @param key132      * @param IVParameter133      * @return134      */135     public static String AesCbcDecode(byte[] decodedText, SecretKey key,136             byte[] IVParameter) {137         IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);138 139         try {140             Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);141             cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);142             return new String(cipher.doFinal(decodedText));143         } catch (NoSuchAlgorithmException | NoSuchPaddingException144                 | InvalidKeyException | InvalidAlgorithmParameterException145                 | IllegalBlockSizeException | BadPaddingException e) {146             // TODO Auto-generated catch block147             e.printStackTrace();148         }149 150         return null;151 152     }153 154     /**155      * 1.創(chuàng)建一個(gè)KeyGenerator 2.調(diào)用KeyGenerator.generateKey方法156      * 由于某些原因,這里只能是128,如果設(shè)置為256會(huì)報(bào)異常,原因在下面文字說明157      * 
158      * @return159      */160     public static byte[] generateAESSecretKey() {161         KeyGenerator keyGenerator;162         try {163             keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);164             // keyGenerator.init(256);165             return keyGenerator.generateKey().getEncoded();166         } catch (NoSuchAlgorithmException e) {167             // TODO Auto-generated catch block168             e.printStackTrace();169         }170         return null;171     }172 173     /**174      * 還原密鑰175      * 
176      * @param secretBytes177      * @return178      */179     public static SecretKey restoreSecretKey(byte[] secretBytes) {180         SecretKey secretKey = new SecretKeySpec(secretBytes, KEY_ALGORITHM);181         return secretKey;182     }183 }

JDK自帶方法實(shí)現(xiàn)AES對(duì)稱加密

 

因?yàn)槟承﹪业倪M(jìn)口管制限制,Java發(fā)布的運(yùn)行環(huán)境包中的加解密有一定的限制。比如默認(rèn)不允許256位密鑰的AES加解密,解決方法就是修改策略文件。

 

 官方網(wǎng)站提供了JCE無限制權(quán)限策略文件的下載:

  JDK6的下載地址:
  ht    tp://w    ww.orac le.com/technetwork/j  ava/javase/downloads/jce-6-download-429243.html

  JDK7的下載地址:
  ht   tp:   //ww    w.oracle.com/tech   network/java/javase/downloads/jce-7-download-432124.html 

下載后解壓,可以看到local_policy.jar和US_export_policy.jar以及readme.txt。

如果安裝了JRE,將兩個(gè)jar文件放到%JRE_HOME%\lib\security下覆蓋原來文件,記得先備份。

如果安裝了JDK,將兩個(gè)jar文件也放到%JDK_HOME%\jre\lib\security下。

 

PS:我也沒試過,不行別找我。

 

KeyFactory最常用的操作就是通過密鑰規(guī)范獲得對(duì)應(yīng)的密鑰。像DES 3DES都是通過這樣獲得的,而AES只要一般的密鑰規(guī)范就可以了,因此不需要KeyFactory.


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI