无法使用AES / ECB / PKCS5Padding将加密方法从Java复制到PHP [英] Unable to replicate an encryption method from Java to PHP using AES/ECB/PKCS5Padding

查看:102
本文介绍了无法使用AES / ECB / PKCS5Padding将加密方法从Java复制到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Java代码

  import java.io.IOException; 
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

公共类AESEncryption
{
public static final String AES_TRANSFORMATION = AES / ECB / PKCS5Padding;
public static final String AES_ALGORITHM = AES;
public static final int ENC_BITS = 256;
public static final String CHARACTER_ENCODING = UTF-8;

私有静态密码ENCRYPT_CIPHER;
私有静态密码DECRYPT_CIPHER;
私有静态KeyGenerator KEYGEN;

静态
{
try
{
ENCRYPT_CIPHER = Cipher.getInstance(AES_TRANSFORMATION);
DECRYPT_CIPHER = Cipher.getInstance(AES_TRANSFORMATION);
KEYGEN = KeyGenerator.getInstance(AES_ALGORITHM);
KEYGEN.init(ENC_BITS);
}
catch(NoSuchAlgorithmException | NoSuchPaddingException e)
{
e.printStackTrace();
}
}

/ **
*此方法用于将bytes []编码为base64字符串。
*
* @param字节
*:编码字节
* @return:编码的Base64字符串
* /

private静态字符串encodeBase64String(byte [] bytes)
{
返回新的String(java.util.Base64.getEncoder()。encode(bytes));
}

/ **
*此方法用于将base64编码的字符串解码为byte []
*
* @param stringData
*:要解码的字符串
* @return:已解码的字符串
* @throws UnsupportedEncodingException
* /

私有静态字节[] encodeBase64StringTOByte(String stringData)抛出异常
{
return java.util.Base64.getDecoder()。decode(stringData.getBytes(CHARACTER_ENCODING));
}

/ **
*此方法用于加密作为byte []传递给它的字符串,并返回base64编码的
*加密的字符串
* @param plainText
*:byte []
* @param secret
*:用于加密的密钥
* @return:加密字符串的base64编码。
*
* /

私有静态字符串cryptoEK(byte [] plainText,byte [] secret)
{
try
{
SecretKeySpec sk = new SecretKeySpec(secret,AES_ALGORITHM);
ENCRYPT_CIPHER.init(Cipher.ENCRYPT_MODE,sk);
返回Base64.encodeBase64String(ENCRYPT_CIPHER.doFinal(plainText));
}
catch(异常e)
{
e.printStackTrace();
返回;
}
}

/ **
*此方法用于使用AES 256位密钥解密base64编码的字符串。
*
* @param plainText
*:要解密的纯文本
* @param机密
*:解密密钥
* @return:解密后的字符串
* @throws IOException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* /
公共静态字节[] plainText,byte [] secret)
抛出InvalidKeyException,IOException,IllegalBlockSizeException,
BadPaddingException,Exception
{
SecretKeySpec sk = new SecretKeySpec(secret,AES_ALGORITHM);
DECRYPT_CIPHER.init(Cipher.DECRYPT_MODE,sk);
return DECRYPT_CIPHER.doFinal(Base64.decodeBase64(plainText));
}

public static void main(String args [])引发异常
{
String encKey =;

//客户端asp_secret
字符串asp_secret =;


字节[] enc_key =解密(encKey,asp_secret.getBytes());

字符串enc_asp_secret = encryptEK(asp_secret.getBytes(),decodeBase64StringTOByte(encodeBase64String(enc_key))));

System.out.println( asp机密加密:);
System.out.println(enc_asp_secret);
}
}

我碰巧在StackOverflow中看到了一个与没有答案



无法将AES 256加密代码从Java复制到PHP [重复]



这被标记为与另一个不同的问题重复。



我尝试了一些PHP代码,但没有成功。



我将添加我为此尝试了多年的赏金。



免责声明:使用与上述问题相同的代码段,因为这个代码段更加清晰。



我尝试过的PHP代码

  class AtomAES {

公共函数crypto($ data ='',$ key = NULL,$ salt =){
if($ key!= NULL&& $ data!=&& $ salt!=){

$ method = AES-256-CBC;

//将数组转换为字节
$ iv = [0,1,2,3,4,5,6,7,8,9,10,11,12,13, 14、15];
$ chars = array_map( chr,$ iv);
$ IVbytes = join($ chars);


$ salt1 = mb_convert_encoding($ salt, UTF-8); //编码为UTF-8
$ key1 = mb_convert_encoding($ key, UTF-8); //编码为UTF-8

// PBKDF2WithHmacSHA1的SecretKeyFactory实例Java等效
$ hash = openssl_pbkdf2($ key1,$ salt1,'256','65536','sha1') ;

$ encrypted = openssl_encrypt($ data,$ method,$ hash,OPENSSL_RAW_DATA,$ IVbytes);

return bin2hex($ encrypted);
} else {
return要加密的字符串,需要Salt和Key。;
}
}

公共函数delete($ data =,$ key = NULL,$ salt =){
if($ key!= NULL&& $ data!=&& $ salt!=){
$ dataEncypted = hex2bin($ data);
$ method = AES-256-CBC;

//将数组转换为字节
$ iv = [0,1,2,3,4,5,6,7,8,9,10,11,12,13, 14、15];
$ chars = array_map( chr,$ iv);
$ IVbytes = join($ chars);

$ salt1 = mb_convert_encoding($ salt, UTF-8); //编码为UTF-8
$ key1 = mb_convert_encoding($ key, UTF-8); / /编码为UTF-8

// PBKDF2WithHmacSHA1的SecretKeyFactory实例Java等效
$ hash = openssl_pbkdf2($ key1,$ salt1,'256','65536','sha1');

$ decrypted = openssl_decrypt($ dataEncypted,$ method,$ hash,OPENSSL_RAW_DATA,$ IVbytes);
返回$ decrypted;
} else {

return要解密的加密字符串,必须使用Salt和Key。;

}
}

}

我无法使用此PHP解密使用Java生成的字符串



更新



这是我尝试使用上述Java代码加密的文本和密钥

 随机生成的文本(asp_secret) :DTosv9G179D0cY1985Uh2eF6ND80C95L 
随机生成用于密钥(encKey):VEMwcCYfFpsrXQVIFTDrA / 2zP / 5PYOY6JC1XEkEcLGSk / KLT + HqHzGSr781Yznku
。使用上面的Java代码加密字符串(enc_asp_secret):zAnTcjmAezfdzrWGixyfwmb8cM0otrsmwJ8 + cNDs48Axh9hYgBtCJyeSE9tCvEBz


解决方案

由于您对解密使用Java加密的加密字符串感兴趣,因此 encryptEK -方法,解密应该使用PHP decrypt -method完成(反之亦然),我忽略了 main 方法(我不太清楚),我专注于将两个Java方法 encryptEK decrypt 移植到PHP方法。



Java encryptEK 方法采用纯文本和密钥作为字节数组,使用AES加密纯文本(256-ECB)并使用Base64编码对加密的文本进行编码。可能的PHP对应对象为:

 公共函数crypto($ data ='',$ key = NULL){
if($ key!= NULL&& $ data!=){
$ method = AES-256-ECB;
$ encrypted = openssl_encrypt($ data,$ method,$ key,OPENSSL_RAW_DATA);
$ result = base64_encode($ encrypted);
返回$ result;
} else {
return要加密的字符串,需要密钥。;
}
}

注意:ECB模式不使用IV。



Java 解密方法采用base64编码的字符串,将其解码然后解密。可能的PHP对应对象是

 公共函数delete($ data =,$ key = NULL){
if($ key!= NULL&& $ data!=){
$ method = AES-256-ECB;
$ dataDecoded = base64_decode($ data);
$ decrypted = openssl_decrypt($ dataDecoded,$ method,$ key,OPENSSL_RAW_DATA);
返回$ decrypted;
} else {
return要解密的加密字符串,需要密钥。;
}
}

两种Java方法 java.util.Base64 类的> encodeBase64String 和 decodeBase64StringTOByte 不是由Java方法 encryptEK 解密使用。取而代之的是 org.apache.commons.codec.binary.Base64 -class的相应方法(例如 https://commons.apache.org/proper/commons-codec/download_codec.cgi )被消耗。因此,我不再赘述这两种方法。



在Java参考代码中,不会生成256bit-AES密钥,但是通常会生成一个随机密钥生成方式如下:

  KEYGEN.init(256); 
SecretKey secretKey = KEYGEN.generateKey();
byte [] key = secretKey.getEncoded();

在PHP中,这是通过



<$ p完成的$ p> $ key = random_bytes(32);

对于双方的混合加密/解密测试(例如Java / PHP),要使用的。例如,此密钥以Java提供:

  byte [] key =这是一个256位= 32字节的密钥。 getBytes(Charsets.UTF_8); 

以及在PHP中:

  $ key = mb_convert_encoding(这是256位= 32字节密钥, UTF-8); 

测试1:使用Java加密/解密(使用随机生成的密钥)

 纯文本:快速的棕色狐狸跳过懒狗
随机生成的密钥(十六进制):20e9c191374b688e74e68ab6c969109e84c5c8e059d84f16f2beb07a7545cbc8
加密文本(以base64编码):ZWOnSYErRxRRtqoVFTLVQMT329pOFHzN1gPDMuiZt0zFpt4n2TF / L54RB21zhVUa
解密文本:快速的棕色狐狸跳过了懒狗

测试2:使用PHP加密/解密(使用随机生成的密钥)

 纯文本:敏捷的棕色狐狸跳过懒狗
随机产生的密钥(十六进制):eecd40c21e2a395f3aa3baeac19bfc8dcee04ea6e07f02dca7069397a487824f
加密文本(Base64编码):8wjusOED9TTXHjyEqvmGExLATVlvhg3hXEBHQ6Ku3Fos2OrYKbF + 4XdO6cD9JJA5
解密文本:该快速的棕色狐狸跳过了懒狗

可能的加密和解密n部分:

  $ key = random_bytes(32); 
echo bin2hex($ key);
$ atomAES =新的AtomAES();
$ encrypt = $ atomAES-> encrypt(快速的棕色狐狸跳过懒狗,$ key);
echo $ encrypt;
$ decrypt = $ atomAES-> decrypt($ encrypt,$ key);
echo $ decrypt;

测试3:使用Java加密/使用PHP解密(使用上面的具体密钥)

 纯文本:快速的棕色狐狸跳过了懒狗
加密文本(以base64编码) Java:/ XjXJc5dNk6p / h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG / PXZ0AzsIIMV1YmvMJho
PHP解密后的文字:快速的棕色狐狸跳过了懒狗

可能的解密部分:

  $ key = mb_convert_encoding(这是256位= 32字节密钥,  UTF-8); 
$ atomAES =新的AtomAES();
$ decrypt = $ atomAES-> decrypt( / XjXJc5dNk6p / h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG / PXZ0AzsIIMV1YmvMJho,$ key);
echo $ decrypt;

测试4:使用PHP加密/使用Java解密(使用上面的具体密钥)

 纯文本:快速的棕色狐狸跳过了懒狗
加密文本(以base64编码) PHP:/ XjXJc5dNk6p / h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG / PXZ0AzsIIMV1YmvMJho
用Java解密的文本:快速的棕色狐狸跳过了懒狗

可能的加密部分:

  $ key = mb_convert_encoding(这是256位= 32字节密钥,  UTF-8); 
$ atomAES =新的AtomAES();
$ encrypt = $ atomAES-> encrypt(快速的棕色狐狸跳过懒狗,$ key);
echo $ encrypt;

编辑:



与主方法中的代码相对应的是(与示例结合):

  $ encKey = mb_convert_encoding ( VEMwcCYfFpsrXQVIFTDrA / 2zP / 5PYOY6JC1XEkEcLGSk / klt + HqHzGSr781Yznku, UTF-8); 
$ asp_secret = mb_convert_encoding( DTosv9G179D0cY1985Uh2eF6ND80C95L, UTF-8);

atomAES =新的AtomAES();
$ enc_key = $ atomAES-> decrypt($ encKey,$ asp_secret);
$ enc_asp_secret = $ atomAES-> encrypt($ asp_secret,base64_decode(base64_encode($ enc_key)));
// $ enc_asp_secret = $ atomAES-> encrypt($ asp_secret,$ enc_key);

回显 asp秘密加密:\n。mb_convert_encoding($ enc_asp_secret, UTF-8)。 \n;

注意:PHP表达式 base64_decode(base64_encode($ enc_key))等效于 $ enc_key ,因此您也可以将其替换为当前注释掉的行。我编码的唯一原因是因为它也在Java代码中编码。在这里, decodeBase64StringTOByte(encodeBase64String(enc_key)相当于
enc_key 。这是因为一种方法是相反的



如果运行上面的代码,输出为

  asp秘密加密:
zAnTcjmAezfdzrWGixyfwmb8cM0otrsmwJ8 + cNDs48Axh9hYgBtCJyeSE9tCvEBz

您也可以定义第三种方法 AtomAES -class的类型:

 公共函数main(){
$ encKey = mb_convert_encoding( VEMwcCYfFpsrXQVIFTDrA / 2zP / 5PYOY6JC1XEkEcLGSk / KLT + HqHzGSr781Yznku, UTF-8);
$ asp_secret = mb_convert_encoding( DTosv9G179D0cY1985Uh2eF6ND80C95L, UTF-8);

$ enc_key = $ this-> decrypt($ encKey,$ asp_secret);
$ enc_asp_secret = $ this-> encrypt($ asp_secret,base64_decode(base64_encode($ enc_key)));
// $ enc_asp_secret = $ this-> encrypt($ asp_secret,$ enc_key);

echo asp secret en加密:\n .mb_convert_encoding($ enc_asp_secret, UTF-8)。 \n;
}

可以用


$ b $调用b

  $ atomAES = new AtomAES(); 
$ atomAES-> main();


I have the following Java code

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESEncryption 
{
    public static final String AES_TRANSFORMATION = "AES/ECB/PKCS5Padding";
    public static final String AES_ALGORITHM = "AES";
    public static final int ENC_BITS = 256;
    public static final String CHARACTER_ENCODING = "UTF-8";

    private static Cipher ENCRYPT_CIPHER;
    private static Cipher DECRYPT_CIPHER;
    private static KeyGenerator KEYGEN; 

    static
    {
        try
        {
            ENCRYPT_CIPHER = Cipher.getInstance(AES_TRANSFORMATION);
            DECRYPT_CIPHER = Cipher.getInstance(AES_TRANSFORMATION);
            KEYGEN = KeyGenerator.getInstance(AES_ALGORITHM);
            KEYGEN.init(ENC_BITS);
        }
        catch(NoSuchAlgorithmException | NoSuchPaddingException e) 
        {
            e.printStackTrace();
        }
    }

    /**
     * This method is used to encode bytes[] to base64 string.
     * 
     * @param bytes
     *            : Bytes to encode
     * @return : Encoded Base64 String
     */

    private static String encodeBase64String(byte[] bytes) 
    {
         return new String(java.util.Base64.getEncoder().encode(bytes));
    }

    /**
    * This method is used to decode the base64 encoded string to byte[]
    * 
    * @param stringData
    *            : String to decode
    * @return : decoded String
    * @throws UnsupportedEncodingException
    */

    private static byte[] decodeBase64StringTOByte(String stringData) throws Exception 
    {
        return java.util.Base64.getDecoder().decode(stringData.getBytes(CHARACTER_ENCODING));
    }

    /**
    * This method is used to encrypt the string which is passed to it as byte[] and return base64 encoded
    * encrypted String
    * @param plainText
    *            : byte[]
    * @param secret
    *            : Key using for encrypt
    * @return : base64 encoded of encrypted string.
    * 
    */

    private static String encryptEK(byte[] plainText, byte[] secret)
    {
        try
        {
            SecretKeySpec sk = new SecretKeySpec(secret, AES_ALGORITHM);
            ENCRYPT_CIPHER.init(Cipher.ENCRYPT_MODE, sk);
            return Base64.encodeBase64String(ENCRYPT_CIPHER.doFinal(plainText));    
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return "";
        }
    }

    /**
    * This method is used to decrypt base64 encoded string using an AES 256 bit key.
    * 
    * @param plainText
    *            : plain text to decrypt
    * @param secret
    *            : key to decrypt
    * @return : Decrypted String
    * @throws IOException
    * @throws InvalidKeyException
    * @throws BadPaddingException
    * @throws IllegalBlockSizeException
    */
    public static byte[] decrypt(String plainText, byte[] secret)
                throws InvalidKeyException, IOException, IllegalBlockSizeException,
                BadPaddingException,Exception 
    {
        SecretKeySpec sk = new SecretKeySpec(secret, AES_ALGORITHM);
        DECRYPT_CIPHER.init(Cipher.DECRYPT_MODE, sk);       
        return DECRYPT_CIPHER.doFinal(Base64.decodeBase64(plainText));
    }

    public static void main(String args[])throws Exception
    {
        String encKey = ""; 

        //client asp_secret
        String asp_secret="";   


        byte[] enc_key = decrypt(encKey, asp_secret.getBytes());

        String enc_asp_secret=encryptEK(asp_secret.getBytes(), decodeBase64StringTOByte(encodeBase64String(enc_key)));

        System.out.println("asp secret encrypted:");
        System.out.println(enc_asp_secret);     
    }
}

I happened to see a very similar post in StackOverflow with no answers

Cannot replicate an AES 256 encryption code from Java to PHP [duplicate]

which is marked duplicate to another question which is different.

I have tried a couple of PHP codes but it didn't work out.

I will add up bounty for this as im trying this for ages.

Disclaimer : Used the same code snippet from the above question as this one is more clear.

Adding the PHP code I tried

class AtomAES {

public function encrypt($data = '', $key = NULL, $salt = "") {
    if($key != NULL && $data != "" && $salt != ""){

        $method = "AES-256-CBC";

        //Converting Array to bytes
        $iv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        $chars = array_map("chr", $iv);
        $IVbytes = join($chars);


        $salt1 = mb_convert_encoding($salt, "UTF-8"); //Encoding to UTF-8
        $key1 = mb_convert_encoding($key, "UTF-8"); //Encoding to UTF-8

        //SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
        $hash = openssl_pbkdf2($key1,$salt1,'256','65536', 'sha1'); 

        $encrypted = openssl_encrypt($data, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);

        return bin2hex($encrypted);
    }else{
        return "String to encrypt, Salt and Key is required.";
    }
}

public function decrypt($data="", $key = NULL, $salt = "") {
    if($key != NULL && $data != "" && $salt != ""){
        $dataEncypted = hex2bin($data);
        $method = "AES-256-CBC";

        //Converting Array to bytes
        $iv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        $chars = array_map("chr", $iv);
        $IVbytes = join($chars);

        $salt1 = mb_convert_encoding($salt, "UTF-8");//Encoding to UTF-8
        $key1 = mb_convert_encoding($key, "UTF-8");//Encoding to UTF-8

        //SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
        $hash = openssl_pbkdf2($key1,$salt1,'256','65536', 'sha1'); 

        $decrypted = openssl_decrypt($dataEncypted, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
        return $decrypted;
    }else{

        return "Encrypted String to decrypt, Salt and Key is required.";

    }
}

}

I am not able to decrypt a string generated using java using this PHP

Update

here is the text and key that i tried for encryption using the above java code

Random generated text (asp_secret)  : DTosv9G179D0cY1985Uh2eF6ND80C95L
Random generated Key used (encKey): VEMwcCYfFpsrXQVIFTDrA/2zP/5PYOY6JC1XEkEcLGSk/klt+HqHzGSr781Yznku
Encrypted string using above java code (enc_asp_secret): zAnTcjmAezfdzrWGixyfwmb8cM0otrsmwJ8+cNDs48Axh9hYgBtCJyeSE9tCvEBz

解决方案

Since you are interested in the decryption of an encrypted string in which the encryption was done with the Java encryptEK-method and the decryption should be done with the PHP decrypt-method (or vice versa) I ignore the code of the main-method (which isn't very clear to me) and I focus on the porting of the both Java-methods, encryptEK and decrypt, to PHP-methods.

The Java encryptEK-method takes a plain text and a key as byte array, encrypts the plain text using AES (256-ECB) and encodes the encrypted text using Base64 encoding. A possible PHP-counterpart is:

public function encrypt($data = '', $key = NULL) {
    if($key != NULL && $data != ""){
        $method = "AES-256-ECB";
        $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA);
        $result = base64_encode($encrypted);
        return $result;
    }else{
        return "String to encrypt, Key is required.";
    }
}

Note: The ECB-mode doesn't use an IV.

The Java decrypt-method takes a base64 encoded string, decodes it and then decrypts it. A possible PHP-counterpart is

public function decrypt($data="", $key = NULL) {
    if($key != NULL && $data != ""){
        $method = "AES-256-ECB";
        $dataDecoded = base64_decode($data);
        $decrypted = openssl_decrypt($dataDecoded, $method, $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }else{
        return "Encrypted String to decrypt, Key is required.";
    }
}

The both Java-methods, encodeBase64String and decodeBase64StringTOByte, which use the java.util.Base64-class are not consumed by the Java-methods encryptEK and decrypt. Instead of that, the corresponding methods of the org.apache.commons.codec.binary.Base64-class (e.g. https://commons.apache.org/proper/commons-codec/download_codec.cgi) are consumed. For this reason, I do not take any further notice of both methods.

In the Java reference code no 256bit-AES key is examplarily generated, but a random key is typically generated in the following way:

KEYGEN.init(256);
SecretKey secretKey = KEYGEN.generateKey();
byte[] key = secretKey.getEncoded();

In PHP this is done with

$key = random_bytes(32);

For a mixed encryption/decryption-testing (e.g. Java/PHP) on both sides the same key has to be used. E.g., this key is provided in Java:

byte[] key = "This is a 256 bits = 32 byte key".getBytes(Charsets.UTF_8);

and in PHP:

$key = mb_convert_encoding("This is a 256 bits = 32 byte key", "UTF-8");

Test 1: Encrypt/Decrypt with Java (using a random generated key)

Plain text: The quick brown fox jumps over the lazy dog
Randomly generated key (hex): 20e9c191374b688e74e68ab6c969109e84c5c8e059d84f16f2beb07a7545cbc8
Encrypted text (base64 encoded): ZWOnSYErRxRRtqoVFTLVQMT329pOFHzN1gPDMuiZt0zFpt4n2TF/L54RB21zhVUa
Decrypted text: The quick brown fox jumps over the lazy dog

Test 2: Encrypt/Decrypt with PHP (using a random generated key)

Plain text: The quick brown fox jumps over the lazy dog
Randomly generated key (hex): eecd40c21e2a395f3aa3baeac19bfc8dcee04ea6e07f02dca7069397a487824f
Encrypted text (base64 encoded): 8wjusOED9TTXHjyEqvmGExLATVlvhg3hXEBHQ6Ku3Fos2OrYKbF+4XdO6cD9JJA5
Decrypted text: The quick brown fox jumps over the lazy dog

Possible encryption and decryption portion:

$key = random_bytes(32);
echo bin2hex($key);
$atomAES = new AtomAES();
$encrypt = $atomAES->encrypt("The quick brown fox jumps over the lazy dog", $key);
echo $encrypt; 
$decrypt = $atomAES->decrypt($encrypt, $key);
echo $decrypt;

Test 3: Encrypt with Java/Decrypt with PHP (using the concrete key above)

Plain text: The quick brown fox jumps over the lazy dog
Encrypted text (base64 encoded) with Java: /XjXJc5dNk6p/h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG/PXZ0AzsIIMV1YmvMJho
Decrypted text with PHP: The quick brown fox jumps over the lazy dog

Possible decryption portion:

$key = mb_convert_encoding("This is a 256 bits = 32 byte key", "UTF-8");
$atomAES = new AtomAES();
$decrypt = $atomAES->decrypt("/XjXJc5dNk6p/h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG/PXZ0AzsIIMV1YmvMJho", $key);
echo $decrypt;

Test 4: Encrypt with PHP/Decrypt with Java (using the concrete key above)

Plain text: The quick brown fox jumps over the lazy dog
Encrypted text (base64 encoded) with PHP:  /XjXJc5dNk6p/h2HL8MVmmWG8Vd0Ud2x1QQWwmIQr9OG/PXZ0AzsIIMV1YmvMJho
Decrypted text with Java: The quick brown fox jumps over the lazy dog

Possible encryption portion:

$key = mb_convert_encoding("This is a 256 bits = 32 byte key", "UTF-8");
$atomAES = new AtomAES();
$encrypt = $atomAES->encrypt("The quick brown fox jumps over the lazy dog", $key);
echo $encrypt; 

EDIT:

The counterpart to the code in the main-method is (in combination with your sample):

$encKey = mb_convert_encoding("VEMwcCYfFpsrXQVIFTDrA/2zP/5PYOY6JC1XEkEcLGSk/klt+HqHzGSr781Yznku", "UTF-8");
$asp_secret = mb_convert_encoding("DTosv9G179D0cY1985Uh2eF6ND80C95L", "UTF-8");

atomAES = new AtomAES();
$enc_key = $atomAES->decrypt($encKey, $asp_secret);
$enc_asp_secret = $atomAES->encrypt($asp_secret, base64_decode(base64_encode($enc_key)));
//$enc_asp_secret = $atomAES->encrypt($asp_secret, $enc_key);

echo "asp secret encrypted:\n".mb_convert_encoding($enc_asp_secret, "UTF-8")."\n"; 

Note: The PHP expression base64_decode(base64_encode($enc_key)) is equivalent to $enc_key, thus you can also replace it with the line currently commented out. The only reason I coded it is because it is also coded in the Java code. Here decodeBase64StringTOByte(encodeBase64String(enc_key) is equivalent to enc_key. That's because the one method is the inverse of the other method.

If you run the above code the output is

asp secret encrypted:
zAnTcjmAezfdzrWGixyfwmb8cM0otrsmwJ8+cNDs48Axh9hYgBtCJyeSE9tCvEBz

You can alternatively define a third method of the AtomAES-class:

public function main(){
    $encKey = mb_convert_encoding("VEMwcCYfFpsrXQVIFTDrA/2zP/5PYOY6JC1XEkEcLGSk/klt+HqHzGSr781Yznku", "UTF-8");
    $asp_secret = mb_convert_encoding("DTosv9G179D0cY1985Uh2eF6ND80C95L", "UTF-8");

    $enc_key = $this->decrypt($encKey, $asp_secret);
    $enc_asp_secret = $this->encrypt($asp_secret, base64_decode(base64_encode($enc_key)));
    //$enc_asp_secret = $this->encrypt($asp_secret, $enc_key);

    echo "asp secret encrypted:\n".mb_convert_encoding($enc_asp_secret, "UTF-8")."\n"; 
}

which can be called with

$atomAES = new AtomAES();
$atomAES->main();

这篇关于无法使用AES / ECB / PKCS5Padding将加密方法从Java复制到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆