Поскольку код Java является справочным, методы PHP должны быть адаптированы к 65556 (значение из методов Java), то есть в методе шифрования и дешифрования PHP в $ hash = openssl_pbkdf2 ($ key1, $ salt1, '256 ',' 65536 ',' sha1 ') значение' 65536 'должно быть изменено на' 65556 '. Я уже обновил свой ответ (методы, а также тестовые случаи). Если вы попытаетесь расшифровать ваш пример после этого изменения с помощью PHP-метода decrypt, он будет работать.

я есть следующий код Java, который был предоставлен одним из партнеров по интеграции для их шифрования API

    import java.nio.ByteBuffer;
    import java.security.AlgorithmParameters;
    import java.security.SecureRandom;
    import java.security.spec.KeySpec;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;

public class AES256 {

    /**
     *
     * @param word
     * @param keyString
     * @return
     * @throws Exception
     */
    public static String encrypt(String word, String keyString) throws Exception {
        byte[] ivBytes;
        //String password = "zohokeyoct2017";
        /*you can give whatever you want for password. This is for testing purpose*/
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        byte[] saltBytes = bytes;
        System.out.println("salt enc:"+saltBytes.toString());
        // Derive the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(keyString.toCharArray(), saltBytes, 65556, 256);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        //encrypting the word
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8"));
        //prepend salt and vi
        byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
        System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
        System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
        System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
        return new Base64().encodeToString(buffer);
    }

    /**
     *
     * @param encryptedText
     * @param keyString
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText, String keyString) throws Exception {
        //String password = "zohokeyoct2017";
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //strip off the salt and iv
        ByteBuffer buffer = ByteBuffer.wrap(new Base64().decode(encryptedText));
        byte[] saltBytes = new byte[20];
        buffer.get(saltBytes, 0, saltBytes.length);
        byte[] ivBytes1 = new byte[16];

        buffer.get(ivBytes1, 0, ivBytes1.length);
        byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];

        buffer.get(encryptedTextBytes);
        // Deriving the key
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(keyString.toCharArray(), saltBytes, 65556, 256);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            System.out.println("Exception"+e);
        }

        return new String(decryptedTextBytes);
    }

    public static void main (String []args) throws Exception{
        String encryptedText;
        encryptedText = AES256.encrypt("106_2002005_9000000106","3264324");
        System.out.println("Encrypted Text:"+encryptedText);
        System.out.println("Decrypted Text:"+AES256.decrypt(encryptedText,"3264324"));

    }
}

И я попробовал пару кодов PHP, которые я получил от stackoverflow или Google. Не могу заставить любого из них работать.

Код, который я пробовал в последнее время на PHP ниже

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.";

        }
    }

}

Это код PHP, который я хотел попробовать, но он не работает так, как ожидалось, в соответствии с кодом Java.

Encrypted Text:1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=
Decrypted Text:This is a sample text
KEY: NEWENCTEST

Попробуйте расшифровать вышеприведенный зашифрованный текст Java с помощью кода PHP и ключа, если он работает, то отлично.

Если кто-то может помочь мне с этим, это очень поможет!

ТИА!

Ответы на вопрос(1)

Ваш ответ на вопрос