在Java中解密defuse / php-encryption Crypto :: encryptWithPassword()

时间:2016-07-20 08:05:08

标签: java php encryption cryptography

我有一个PHP应用程序,它将一些敏感信息存储在MySQL数据库中。为了保护这些信息,我使用defuse/php-encryption库的Crypto::encryptWithPassword()方法,如下所示:

<?php

// ... get sensitive data from user ...

$encrypted = base64_encode(Crypto::encryptWithPassword($sensitive, $password, true));

// ... store that data in database ...

我还有另一个需要访问此信息的Java应用程序。但是,我不知道如何从Java解密。这是我尝试过的代码:

byte[] encrypted = DB.getThatEncryptedData();
byte[] salt = Arrays.copyOfRange(encrypted, 4, 35);

String password = SomewhereSafe.getThePassword();
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 100000, 32);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey secret = keyFactory.generateSecret(spec);

Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
c.init(Cipher.DECRYPT_MODE, secret);
byte[] decrypted = c.doFinal(encrypted);

但是,当我运行该代码时,我收到此错误:

Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 4 bytes
    at com.sun.crypto.provider.AESCipher.engineGetKeySize(AESCipher.java:495)
    at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1067)
    at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1025)
    at javax.crypto.Cipher.implInit(Cipher.java:801)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1249)
    at javax.crypto.Cipher.init(Cipher.java:1186)
    at com.example.test.app.Decrypt.main(Decrypt.java:24)

解密该数据的正确方法是什么?

0 个答案:

没有答案