使用PKCS5p添加PHP中的AES 128加密

时间:2015-11-17 07:40:14

标签: java php encryption aes

我一直在尝试使用AES-128 CBC加密字符串,该CBC最初使用JAVA AES加密进行加密。在java中使用PKCS5填充。我试图使用类似的PHP代码加密。但我得到了不同的结果。我想我在IV参数值的某个地方出错了。任何人都可以帮助我。

JAVA代码

package com.idbi.ib.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AESEncryptionDecryptionAlg
{
    public AESEncryptionDecryptionAlg()
    {
    }

    public static String Encrypt(String text, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] keyBytes= new byte[16];
        byte[] b= key.getBytes("UTF-8");
        int len= b.length;
        if (len > keyBytes.length) len = keyBytes.length;
        System.arraycopy(b, 0, keyBytes, 0, len);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivSpec);
        byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(results);
    }
}

和等效的PHP代码。

function mc_encrypt($plaintext,$key) {
    $iv = $key;
    //For PKCS5 padding
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($plaintext) % $block);
    $plaintext .= str_repeat(chr($padding), $padding);

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC);

    $crypttext64 = base64_encode($crypttext);
    $plaintext = $crypttext64;
    return $plaintext;
}

0 个答案:

没有答案