2016-09-28 59 views
1

我有我的應用程序的UI在Meteor中構建,它從REST API(Spring CXF)獲取併發送數據。我想加密Meteor中的數據,並在REST API代碼中對其進行解密。我使用AES進行加密和解密。在流星我使用https://atmospherejs.com/jparker/crypto-aes包進行加密。我在java中編寫了下面的代碼來解密Meteor發送的加密密鑰。使用流星和Java加密和解密數據

public class AESTest { 
      private static String AESStr = "<Encrypted KEY>"; 
      public static void main(String[] args) throws Exception { 
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
       System.out.println(decrypt(AESStr, "Test")); 
      } 
     public static String decrypt(String responseStr, String passPhrase) throws  GeneralSecurityException { 
      String decryptedStr = ""; 
      try { 
         Cipher cipher = getCipher(Cipher.DECRYPT_MODE, passPhrase); 
         byte[] decoded = Base64.decodeBase64(responseStr.getBytes()); 
         byte[] decryptedWithKey = cipher.doFinal(decoded); 
         byte[] decrypted = Arrays.copyOfRange(decryptedWithKey, 16, decryptedWithKey.length); 
         decryptedStr = new String(decrypted, "UTF-8"); 
       } catch (Exception e) { 
         e.printStackTrace(); 
       } 
       return decryptedStr; 
     } 

     private static Cipher getCipher(int mode, String passPhrase) throws Exception { 
       SecretKeySpec secretKeySpec = new SecretKeySpec(passPhrase.getBytes(), "AES"); 
       byte[] IV = new byte[16]; 
       new Random().nextBytes(IV); 
       AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV); 
       Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 
       cipher.init(mode, secretKeySpec, paramSpec); 
       return cipher; 
     } 
} 

當我跑我得到異常下面的代碼

javax.crypto.BadPaddingException: pad block corrupted 
    at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source) 
    at javax.crypto.Cipher.doFinal(Cipher.java:2165) 
    at com.tph.r3.EncodeTest.decrypt(EncodeTest.java:37) 
    at com.tph.r3.EncodeTest.main(EncodeTest.java:26) 

任何人都可以指導我這個問題?

+0

是否解密的工作是與加密AES裝箱率?我的意思是使用CryptoJS.AES.decrypt()。 – Roshith

+0

是的,它的作品完美 –

回答

0

解密邏輯w.r.t IV存在問題。您正在隨機選擇一個IV來初始化錯誤的解密密碼。您需要使用與用於加密通常形成其前16個字節的responseStr相同的IV。

在當前的表單中,您的getCipher()只能用於隨機選擇IV但不用於解密的加密。最好寫另一種方法。

僞碼解密:

decCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
SecretKeySpec keySpec = new SecretKeySpec(securityKey , "AES"); 

//IV + Cipher 
byte [] cipherWithIV = Base64.decodeBase64(responseStr.getBytes())); 

//Extract IV 
byte [] iv = new byte [16]; 
byte [] cipherWithoutIV = new byte [cipherWithIV.length - 16 ]; 

//First 16 bytes 
for(i < 16; i++) { 
    iv [i] = cipherWithIV [i]; 
} 

//Rest of the cipher ie 16 -> cipherWithIV.length 
for(i < cipherWithIV.length; i++) { 
    cipherWithoutIV [j] = cipherWithIV[i]; 
    j++; 
} 

// 
IvParameterSpec ivParamSpec = new IvParameterSpec(iv); 

// 
decCipher.init(Cipher.DECRYPT_MODE, keySpec, ivParamSpec); 

//Decrypt cipher without IV 
decText = decCipher.doFinal(cipherWithoutIV); 

//Convert to string 
decString = new String(decText,"UTF8");