在PHP中复制Java的AES / CBC / PKCS5Padding加密

时间:2018-10-12 09:06:08

标签: java php encryption aes

在下面包含了Java和php代码以及输出。目标是获取PHP中的Java校验和值。可以看出,我在php中的输入与在Java中相同,尽管我尝试了php的openssl_encrypt函数中许多参数变体,但无法获得所需的输出。帮助解决此问题将不胜感激!请注意,该Java代码具有权威性,任何所需的更改都只能在php中进行。

Java代码:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.io.ByteArrayOutputStream; 

public class ChecksumGen {

    public static void main(final String[] args) {
        String data = "INPUTDATA";
        String secretKey = "0000000000000000000000000000000000000000000000000000000000000000";
        byte[] iv = new byte[16];
        try {
            byte[] hashedData = getDigest(data);
            byte[] key = hexStringToByteArray(secretKey);
            byte[] checksum = encrypt(key, hashedData, iv);
            showB64("key ", key);
            showB64("iv ", iv);
            showB64("hashedData ", hashedData);
            showB64("checksum ", checksum);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static byte[] getDigest(String checkSumInput) {
        try {
            MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-256");
            byte[] checkSumInputBytes = checkSumInput.getBytes("UTF-8");
            localMessageDigest.update(checkSumInputBytes);
            byte[] digest = localMessageDigest.digest();
            return digest;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static byte[] hexStringToByteArray(String s) {
        byte[] b = new byte[s.length() / 2];
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(s.substring(index, index + 2), 16);
            b[i] = (byte) v;
        }
        return b;
    }

    public static byte[] encrypt(byte[] key,byte[] data, byte[] iv)throws Exception{
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher acipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        acipher.init(Cipher.ENCRYPT_MODE, secretKeySpec,ivSpec);
        byte[] arrayOfByte1 = acipher.doFinal(data);
        return arrayOfByte1;
    }

    public static void showB64(String label, byte[] rawData) {
      System.out.println(label + ":" + Base64.getEncoder().encodeToString(rawData));
    }
}

PHP代码:

<?php
$data  = "INPUTDATA"; 
$hashedData = hash("sha256", $data, true);
$secretKey = "0000000000000000000000000000000000000000000000000000000000000000";
$ivStr = "00000000000000000000000000000000";
$key = pack('H*', $secretKey);
$iv = pack('H*', $ivStr);
$inputData = pkcs5_pad($hashedData, 16);
showB64('key', $key);
showB64('iv', $iv);
showB64('hashedData', $hashedData);
showB64('inputData', $inputData);
$checksum = encrypt($key, $inputData, $iv);
showB64('checksum', $checksum);

function encrypt($key,$data,$iv){
  $cipher = 'AES-128-CBC';
  $options = OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING;
  $raw = openssl_encrypt(
  $data,
  $cipher,
  $key,
  $options,
  $iv
  );
  return $raw;
}

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

function showB64($label, $rawData) {
  echo "{$label} :".base64_encode($rawData)."\n";
}

Java输出:

key :AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
iv :AAAAAAAAAAAAAAAAAAAAAA==
hashedData :ZAgNCUfIbdT9EjdkCb3XDNpMFGV34rXNjcTOQ9cdZ3w=
checksum :9NS/ZKMscpa4V7i2YQQPoycxCwbL1BlK3h9O/1ujoD1iYgjE8tZx+JRGflw5WikH

PHP输出:

key :AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
iv :AAAAAAAAAAAAAAAAAAAAAA==
hashedData :ZAgNCUfIbdT9EjdkCb3XDNpMFGV34rXNjcTOQ9cdZ3w=
inputData :ZAgNCUfIbdT9EjdkCb3XDNpMFGV34rXNjcTOQ9cdZ3wQEBAQEBAQEBAQEBAQEBAQ
checksum :LtdJzSl9UgEpZrpdg7X5g5CYqE3eXQvijazrvkw0XFNY2bxn8zGp1ea8DrUmw/uu

1 个答案:

答案 0 :(得分:0)

最后按以下链接找出解决方案:

https://gist.github.com/odan/c1dc2798ef9cedb9fedd09cdfe6e8e76#gistcomment-2743227

MCRYPT_RIJNDAEL_128AES-128-CBC不同。

MYCRYT_RIJNDAEL_128中,128实际上是指块的大小,而不是密钥的大小;在AES-128-CBC中,128是指密钥的大小,即当与有效的256位一起使用时,它们都是AES-256键。

在PHP代码中,将函数crypto()中的$ cipher从“ AES-128-CBC”更改为“ AES-256-CBC”有助于我们使用openssl_encrypt获得所需的输出。