简体   繁体   中英

AES - Encryption in Java and decryption in PHP

Why PHP decryption method can't decrypt data encrypted in Java?

When I encrypt and decrypt data using only Java or only in PHP, everything works fine.

I have Java class to encrypt/decrypt data using AES/ECB algorithm. Encryption key is always 2a925de8ca0248d7

package com.example.test.helpers;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Encryptor {

    /**
    * @param strToEncrypt - data to encrypt
    * @param secret - 16 bytes secret
    */
    public static String encrypt(String strToEncrypt, String secret) // secret is always 2a925de8ca0248d7
    {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret.getBytes(), "AES"));
            return Base64.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT);
        }
        catch (Exception e)
        {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

     /**
     * @param strToDecrypt - base64 encoded string to decrypt
     * @param secret - 16 bytes secret
     */
     public static String decrypt(String strToDecrypt, String secret) // secret is always 2a925de8ca0248d7
     {
         try {
             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret.getBytes(), "AES"));
             return new String(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT)));
        }
        catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
}

Encrypted data is sent to server where I try to decrypt it with PHP openssl_decrypt

openssl_decrypt($receivedEncryptedBase64Data, 'AES-256-ECB', '2a925de8ca0248d7');

Unfortunately openssl_decrypt returns an empty string.

Ok, now I see. I should use AES-128-ECB in PHP insetad of AES-256-ECB or extend secret key to 256 bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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