如何将 Java AES - CBC 与 PKCS5 填充更改为 PHP

我正在尝试将 JAVA 加密更改为 PHP 并产生完全相同的结果。我有以下准则。AES - CBC 与 PKCS5 填充对称加密方案:


加密密钥大小为 128 位大小。


初始化向量(IV):


-新的随机 IV 将在每个请求中使用。-在单个 Web 服务请求中,在加密所有加密字段时将使用相同的 IV。-此 IV 将在名称为“IV”的 SOAP Header 中传递。IV 值将采用 Base64 编码。


我试过这个https://gist.github.com/thomasdarimont/fae409eaae2abcf83bd6633b961e7f00


public class AESEncryptionUtil {

public static final String CLASS_NAME = AESEncryptionUtil.class.getName(); private static final int KEY_SIZE = 16;

private static final String ALGORITHM_AES = "AES";

public final static String ALGORITHM_AES_CBC = "AES/CBC/PKCS5Padding";


private static Key generateKey(String keyValue) throws Exception { Key key = null ;

if (keyValue!=null && keyValue.length()==KEY_SIZE){

byte[] byteKey = keyValue.substring(0, KEY_SIZE).getBytes("UTF-8");  

key = new SecretKeySpec(byteKey, ALGORITHM_AES);

}else{

System.out.println("Not generating the Key!! "+keyValue); }

return key; 

}

/**

* Return Base64 Encoded value of IV *

* @param keyValue * @return

* @throws Exception */

public static String generateIV(String keyValue) throws Exception { String iv = null ;

Key key = generateKey(keyValue); if (key!=null){

Cipher cipher = Cipher.getInstance(ALGORITHM_AES_CBC); cipher.init(Cipher.ENCRYPT_MODE, key); AlgorithmParameters params =     cipher.getParameters();

iv = new BASE64Encoder().encode(params.getParameterSpec(IvParameterSpec.class).getIV()); 

 }else{

System.out.println("No IV generated ...");

}

return iv; }


/**

* Method to perform encryption of given data with AES Algorithm / Key and IV. * @param encKey -

*Encryption Key value * @param plainVal -

*Value to be encrypted * @return - encrypted String Value * @throws   Exception

*/



蝴蝶刀刀
浏览 154回答 1
1回答

扬帆大鱼

我设法得到一些工作<?php$string = "online1234";$key = "haskingvista127$";$iv&nbsp; = base64_encode(openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-128-cbc')));$encodedEncryptedData = base64_encode(openssl_encrypt($string, "AES-128-CBC", $key, OPENSSL_RAW_DATA, base64_decode($iv)));$decryptedData = openssl_decrypt(base64_decode($encodedEncryptedData), "AES-128-CBC", $key, OPENSSL_RAW_DATA, base64_decode($iv));?>希望这可以帮助别人
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java