简体   繁体   English

AES / CBC / PKCS5Padding在PHP中用Java解密

[英]AES/CBC/PKCS5Padding encrypt in PHP decrypt in Java

I have to encrypt one string with given key in PHP. 我必须用给定的密钥在PHP中加密一个字符串。

In Java i've already both metods to decrypt and encrypt. 在Java中,我已经同时需要解密和加密。

Here my Java encrypt method: 这是我的Java加密方法:

public static String encriptB64Aes(String value, String aesKey) {
    String result = null;
    try {

       Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

       //in PHP !?
       SecretKey secretKey = new SecretKeySpec(aesKey.getBytes("UTF-8"), "AES");
       IvParameterSpec ivParameterSpec = new IvParameterSpec(secretKey.getEncoded());

       encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

       // Encrypt
       ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
       CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
       cipherOutputStream.write(value.getBytes());
       cipherOutputStream.flush();
       cipherOutputStream.close();
       byte[] encryptedBytes = outputStream.toByteArray();
       result = encodeBase64(encryptedBytes);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
       e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

I need a method like above in PHP code using mcrypt_module_open. 我需要使用mcrypt_module_open在PHP代码中使用上述方法。

I tried a method like this, but I don't know how to calculate $iv like above 我尝试了这样的方法,但是我不知道如何像上面那样计算$ iv

function encrypt($str, $key) { 
      $str = pkcs5_pad($str);
      $iv = ????;                 
      $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
      mcrypt_generic_init($td, $key, $iv);
      $encrypted = mcrypt_generic($td, $str);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
      return base64_encode($encrypted);
}

function pkcs5_pad ($text) {
      $blocksize = 16;
      $pad = $blocksize - (strlen($text) % $blocksize);
      return $text . str_repeat(chr($pad), $pad);
}

I would greatly appreciate any help you can give me. 我将不胜感激您可以给我任何帮助。

Thanks 谢谢

In the Java code the AES key is used as IV. 在Java代码中,AES密钥用作IV。 Respectively, first block of plaintext data is XORed with the AES key which is used after for encryption. 分别将第一个明文数据块与AES密钥进行异或,然后将其用于加密。 .getEncoded() method just returns the byte[] representation of SecretKey. .getEncoded()方法仅返回SecretKey的byte []表示形式。 In your case IV = $key 在您的情况下IV = $ key

Wbr, Juris Wbr,朱莉斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM