2016-04-27 126 views
0

使用java AES/CBC/PKCS7Padding進行加密時出現問題。我已經搜索並遵循通過使用BouncyCastle供應商。但我仍然無法得到正確的加密使用AES/CBC/PKCS7Padding進行JAVA加密

咱們說的要求是:

加密類型:對稱
算法:AES
塊大小= 128位(16個字節)
加密模式:CBC
填充模式:PKCS7
加密密鑰長度:256位(32個字節)
向量初始化長度(IV):128位(16個字節)

樣本:

純文本數據= ABC123
加密數據(base64編碼)= CtGtW4hJfXxilSfNR1xmrg ==

和我的代碼是...

public final class StringFunc { 
    final static String key = "jb2a19ou79rws6zknjlr803fvfgiyp1k"; 
    final static String algorithm = "AES/CBC/PKCS7Padding"; 
    final static String iv = "hod74ty97wr97g83"; 
    private static Cipher cipher = null; 
    private static SecretKeySpec skeySpec = null; 
    private static IvParameterSpec ivSpec = null; 

    private static void setUp(){ 
     try{ 
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
      skeySpec = new SecretKeySpec(key.getBytes(), "AES"); 
      ivSpec = new IvParameterSpec(iv.getBytes()); 
      cipher = Cipher.getInstance(algorithm); 
     }catch(NoSuchAlgorithmException | NoSuchPaddingException ex){ 
     } 
    } 

    public static String encrypt(String str){ 
     try{ 
      Integer strL = (int) Math.ceil(str.length()/8.0); 
      Integer strB = strL*8; 
      str = padRight(str, '', strB); 
      setUp(); 
      try { 
       cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); 
      } catch (InvalidAlgorithmParameterException ex) { 
       return ""; 
      } 
      byte[] enc = cipher.doFinal(str.getBytes()); 
      return new String(Base64.encodeBase64(enc)); 
     }catch(InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex){ 
      return "";    
     } 
    } 

    public static String padRight(String msg, char x, int l) { 
     String result = ""; 
     if (!msg.isEmpty()) { 
      for (int i=0; i<(l-msg.length()); i++) { 
       result = result + x; 
      } 
      result = msg + result; 
     } 
     return result; 
    } 
} 

我仍然無法得到正確的加密。任何人都可以提供幫助或給出建議?

+0

什麼問題? –

+0

我測試了你的代碼,我有個例外。你測試了你的代碼?沒有例外 ? –

+0

的問題,我只是不能得到正確的結果,就像給我的例子。由於原因,代碼已經被刪除,因此您不能僅僅複製粘貼來運行它。 – lendir

回答

0

從給定輸入猜測,您應該遇到密鑰長度的Java限制: 由於美國不允許使用硬安全密鑰,因此Java被限制爲每個默認密鑰長度爲128位。

要啓用鍵>你必須改變你的Java版本與官方「無限」的政策(here for SE8

替換已LIB當前策略的策略的128bit /與下載安全應該是足夠的。

+0

我會研究它先生,謝謝,我會盡快更新進度。 – lendir

相關問題