使用Meteor和Java加密和解密数据

时间:2016-09-28 00:06:18

标签: java meteor encryption cryptography aes

我在Meteor中构建了应用程序的UI,它从REST API(Spring CXF)获取并发送数据。我想加密Meteor中的数据,并在REST API代码中对其进行解密。我使用AES进行加密和解密。在Meteor中我使用https://atmospherejs.com/jparker/crypto-aes包进行加密。我在java中编写了以下代码,用于解密Meteor发送的加密密钥。

call

当我运行代码时,我会遇到异常

    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;
        }
}

任何人都可以指导我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

解密逻辑w.r.t IV存在问题。您正在随机选择IV以初始化解密密码,这是错误的。您需要使用用于加密responseStr的相同IV,它通常会形成前16个字节。

在当前形式中,getCipher()仅可用于随机选择IV但不用于解密的加密。最好写另一种方法。

用于解密的Psuedocode:

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");