AesEncryption вызывает другой результат в коде Java и PHP, почему? - PullRequest
0 голосов
/ 11 января 2019

Я подключаю сторонний интерфейс, и они дали мне только демонстрационный пример кода Java, мне нужно подключить его с моей системой PHP. Но я не могу справиться с шифрованием, мой процесс шифрования в PHP всегда дает другой результат с сторонний Java-код.

Я устанавливаю пакет phpseclib / phpseclib через composer для выполнения шифрования AES.

Код шифрования Java:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

public static String encrypt(String content, String encryptKey) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            byte[] byteContent = content.getBytes("utf-8");

            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(encryptKey));
            byte[] result = cipher.doFinal(byteContent);


            return toHexString(result);
        } catch (Exception ex) {
        }

        return null;
    }  

private static SecretKeySpec getSecretKey(final String encryptKey) {
        KeyGenerator kg = null;

        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(encryptKey.getBytes());
            kg.init(128, secureRandom);


            SecretKey secretKey = kg.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
        }

        return null;
    }

public static String toHexString(byte b[]) {
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
        String plainText = Integer.toHexString(0xff & b[i]);
        if (plainText.length() < 2)
            plainText = "0" + plainText;
        hexString.append(plainText);
    }
    return hexString.toString();
}

Код шифрования PHP:

//composer require phpseclib/phpseclib
use phpseclib\Crypt\AES;
function aesEncrypt($message, $key)
{
    $cipher = new AES(AES::MODE_ECB);
    $cipher->setKeyLength(128);
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($message);

    return bin2hex($cryptText);
}

Java Результат:

before:testStringtestString
key:acccd6fa0caf52a0e5e5fda8bd3ff55a
after:2bbd3011eb084c9494228fe913e6e033aaffb1aa04ef9d0f14614c21fd16af9a

PHP Результат:

before:testStringtestString
key:acccd6fa0caf52a0e5e5fda8bd3ff55a
after:d9a683511cdeb174bf51a285140071a8b38b57c6c6133d1b9425846ae0ec333b
...