将 Java 中的 AES256 加密算法转换为 PHP



大家好,我在尝试将使用 AES256 加密的 API 从 Java 示例集成到 PHP 时遇到了一个主要障碍,这是文档中存在的 Java 版本。

package com.partner.carrier.library;
import java.io.UnsupportedEncodingException;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;
import com.partner.config.ConfigData;
public class AES {
    private static byte[] _sessionKey = "YOUR-KEY".getBytes(); 
    private static byte[] _initialVector = "INITVECTOREXAMPLE".getBytes();
        private static int _keySize = 256;
        private static int _blockSize = 128;    
    public static String Encrypt(String txt)
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RijndaelEngine(_blockSize)), new ZeroBytePadding());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(_sessionKey, 0, (_keySize / 8)), _initialVector, 0, (_blockSize / 8));
        cipher.init(true, ivAndKey);
        try {
            byte[] decoded = txt.trim().getBytes("UTF-8");
            byte[] encoded  = new byte[cipher.getOutputSize(decoded.length)];
            int len = cipher.processBytes(decoded, 0, decoded.length, encoded, 0);
            cipher.doFinal(encoded, len);
            return new String(Base64.encode(encoded));
        } 
        catch (DataLengthException | IllegalStateException | InvalidCipherTextException | UnsupportedEncodingException e) {
            return null;
        }
    }

}

从这里我可以收集到我应该在 PHP 中运行这样的东西

openssl_encrypt($data, "aes-256-cbc", “YOURKEY”, null, "INITVECTOREXAMPLE");

然后我应该将其结果转换为 Base64 并返回它?这是对的吗?ZeroBytePadding(( 调用和所有这些对我来说真的很困惑。

提前感谢您的帮助! :)

使用这个优秀的类解决了这个问题

http://aesencryption.net/#PHP-aes-encryption-example

只是稍微调整了一下,我就去了,现在它工作正常。

$encoder = new AES($data, "PRIVATEKEYHERE", 128, "cbc", "INITIALVECTORIFANY");
$_SESSION['ENCRYPTED_DATA'] = $encoder->encrypt();

希望这对以后的人有所帮助:)谢谢!

最新更新