繁体   English   中英

加密/解密 java 到 PHP

[英]Encrypt/Decrypt java to PHP

我试图了解加密/解密的工作原理,所以我将此加密 JAVA function 转换为 PHP(也是解密方法):

// JAVA
public byte[] encrypt( String text, String salt, String key, ecrypt enc, eprovider provider, ebit bit ) {
    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    IvParameterSpec ivspec = new IvParameterSpec( iv );
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec( key.toCharArray(), salt.getBytes(), 65536, bit.getValue() );
    SecretKey tmp = factory.generateSecret( spec );
    SecretKeySpec secretkey = new SecretKeySpec( tmp.getEncoded(), enc.getValue() );
    Cipher cipher = Cipher.getInstance( provider.getValue() );
    cipher.init( Cipher.ENCRYPT_MODE, secretkey, ivspec );
    return cipher.doFinal( text.getBytes( "UTF-8" ) );
}

我写了这样的东西在 PHP 中解密(我想我收到了一个由上面的 JAVA 加密的 base64 字符串):

// PHP
$IvLength = 16;
$password = '<PASSWD>';
$salt = "<SALT>";
$keyLength = 65536;
$iterations = 256;
$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, $keyLength);
$ciphertext = base64_decode('<MY-BASE-64-CRYPT-STRING>');
$iv = substr($ciphertext, 0, $IvLength);
$ciphertext = substr($ciphertext, $IvLength);
$decryptedtext = openssl_decrypt($ciphertext, "aes-256-cbc", $hash, OPENSSL_RAW_DATA, $iv);

但我仍然遗漏了一些东西,因为“openssl_decrypt”返回 false。

我错过了什么?

当您尝试学习时,我提供了 Java 和 PHP 的完整解决方案,它们的工作原理相同且结果可交换,因此可以使用 Java 加密并使用 PHP 解密,反之亦然。 两个程序都使用 PBKDF2 从密码短语中派生出加密密钥,加密后将 salt、iv 和密文连接起来。 为了解密,完整的字符串被分成这些部分。

这是 output:

AES CBC 256 String encryption with PBKDF2 derived key
plaintext:  The quick brown fox jumps over the lazy dog
encryptionKey (Base64): sI5RagrofCpzDe1ucLI7cHb3GILAMsySr0A8CD04o0I=
* * * Encryption * * *
ciphertext (Base64): Vq5mhwLqgl2LoC/QNRKWA/5YpjrlZ1f3504NzpwEhUA=:QiEdP5gfXzNQwWcxNk4p1w==:Rwy3LC7SbeyDUREiitjjdtioQWkctU9H9OEvzv1ctWymzVh3A0SFQN4Ek/Ku4nVp
output is (Base64) salt : (Base64) iv : (Base64) ciphertext
* * * Decryption * * *
AES CBC 256 String decryption with PBKDF2 derived key
ciphertext (Base64): Vq5mhwLqgl2LoC/QNRKWA/5YpjrlZ1f3504NzpwEhUA=:QiEdP5gfXzNQwWcxNk4p1w==:Rwy3LC7SbeyDUREiitjjdtioQWkctU9H9OEvzv1ctWymzVh3A0SFQN4Ek/Ku4nVp
input is (Base64) salt : (Base64) iv : (Base64) ciphertext
plaintext:  The quick brown fox jumps over the lazy dog

安全警告:以下代码没有任何异常处理,仅用于教育目的。

Java:

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;

public class AesCbc256Pbkdf2StringEncryption_Full {
    public static void main(String[] args) throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeySpecException {
        System.out.println("AES CBC 256 String encryption with PBKDF2 derived key");

        String plaintext = "The quick brown fox jumps over the lazy dog";
        System.out.println("plaintext:  " + plaintext);
        char[] password = "secret password".toCharArray();

        // encryption
        System.out.println("\n* * * Encryption * * *");
        String ciphertextBase64 = aesCbcPbkdf2EncryptToBase64(password, plaintext);
        System.out.println("ciphertext (Base64): " + ciphertextBase64);
        System.out.println("output is (Base64) salt : (Base64) iv : (Base64) ciphertext");

        // decryption
        System.out.println("\n* * * Decryption * * *");
        System.out.println("AES CBC 256 String decryption with PBKDF2 derived key");
        String ciphertextDecryptionBase64 = ciphertextBase64;
        System.out.println("ciphertext (Base64): " + ciphertextDecryptionBase64);
        System.out.println("input is (Base64) salt : (Base64) iv : (Base64) ciphertext");
        String decryptedtext = aesCbcPbkdf2DecryptFromBase64(password, ciphertextDecryptionBase64);
        System.out.println("plaintext:  " + decryptedtext);
    }

    private static byte[] generateSalt32Byte() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] salt = new byte[32];
        secureRandom.nextBytes(salt);
        return salt;
    }

    private static byte[] generateRandomInitvector() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] iv = new byte[16];
        secureRandom.nextBytes(iv);
        return iv;
    }

    private static String aesCbcPbkdf2EncryptToBase64(char[] password, String data) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
        int PBKDF2_ITERATIONS = 15000;
        byte[] salt = generateSalt32Byte();
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec keySpec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, 32 * 8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "AES");
        byte[] iv = generateRandomInitvector();
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        String ciphertextBase64 = Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        String saltBase64 = Base64.getEncoder().encodeToString(salt);
        String ivBase64 = Base64.getEncoder().encodeToString(iv);
        return saltBase64 + ":" + ivBase64 + ":" + ciphertextBase64;
    }

    private static String aesCbcPbkdf2DecryptFromBase64(char[] password, String data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
        String[] parts = data.split(":", 0);
        byte[] salt = base64Decoding(parts[0]);
        byte[] iv = base64Decoding(parts[1]);
        byte[] encryptedData = base64Decoding(parts[2]);
        int PBKDF2_ITERATIONS = 15000;
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec keySpec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, 32 * 8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        return new String(cipher.doFinal(encryptedData));
    }

    private static String base64Encoding(byte[] input) {
        return Base64.getEncoder().encodeToString(input);
    }

    private static byte[] base64Decoding(String input) {
        return Base64.getDecoder().decode(input);
    }
}

PHP:

<?php
function aesCbcPbkdf2EncryptToBase64($password, $data)
{
    $PBKDF2_ITERATIONS = 15000;
    $salt = generateSalt32Byte();
    $key = hash_pbkdf2("sha256", $password, $salt, $PBKDF2_ITERATIONS, 32, $raw_output = true);
    $iv = generateRandomInitvector();
    $ciphertext = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($salt) . ':' . base64_encode($iv) . ':' . base64_encode($ciphertext);
}

function generateSalt32Byte()
{
    return openssl_random_pseudo_bytes(32, $crypto_strong);
}

function aesCbcPbkdf2DecryptFromBase64($password, $data)
{
    $PBKDF2_ITERATIONS = 15000;
    list($salt, $iv, $encryptedData) = explode(':', $data, 3);
    $key = hash_pbkdf2("sha256", $password, base64_decode($salt), $PBKDF2_ITERATIONS, 32, $raw_output = true);
    return openssl_decrypt(base64_decode($encryptedData), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, base64_decode($iv));
}

function generateRandomInitvector()
{
    return openssl_random_pseudo_bytes(16, $crypto_strong);
}

echo 'AES CBC 256 String encryption with PBKDF2 derived key' . PHP_EOL;

$plaintext = 'The quick brown fox jumps over the lazy dog';
echo 'plaintext: ' . $plaintext . PHP_EOL;
$password = "secret password";

// encryption
echo PHP_EOL . '* * * Encryption * * *' . PHP_EOL;
$ciphertextBase64 = aesCbcPbkdf2EncryptToBase64($password, $plaintext);
echo 'ciphertext: ' . $ciphertextBase64 . PHP_EOL;
echo 'output is (Base64) salt : (Base64) iv : (Base64) ciphertext' .PHP_EOL;

// decryption
echo PHP_EOL;
echo PHP_EOL . '* * * Decryption * * *' . PHP_EOL;
$ciphertextDecryptionBase64 = $ciphertextBase64;
echo 'ciphertextDecryption (Base64): ' . $ciphertextDecryptionBase64 . PHP_EOL;
echo 'input is (Base64) salt : (Base64) iv : (Base64) ciphertext' .PHP_EOL;
$decryptedtext = aesCbcPbkdf2DecryptFromBase64($password, $ciphertextDecryptionBase64);
echo 'plaintext: ' . $decryptedtext . PHP_EOL;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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