2016-09-28 61 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");