繁体   English   中英

如何使用PKCS5填充将Java AES ‐ CBC更改为PHP

[英]How to change Java AES ‐ CBC with PKCS5 Padding to PHP

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

加密密钥的大小为128位。

初始化向量(IV):

-每个请求中都会使用新的Random IV。 -在单个Web服务请求中,对所有加密字段进行加密时将使用相同的IV。 -此IV将在SOAP Header中传递,名称为“ IV”。 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
*/
public static String encrypt(String encKey, String plainVal, String currentIV) throws Exception {

String encryptedText = null ; Key key = generateKey(encKey);
if (key!=null && currentIV!=null && plainVal!=null){
 Cipher c = Cipher.getInstance(ALGORITHM_AES_CBC);
 c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new BASE64Decoder().decodeBuffer(currentIV)));
byte[] encValue = c.doFinal(plainVal.getBytes()); encryptedText= new BASE64Encoder().encode(encValue);
}else{
System.out.println("Invalid input passed to encrypt !! keyValue="+encKey+", IV="+currentIV+", valueToEnc="+plainVal);
}
return encryptedText; }
}

我设法找到了工作

<?php
$string = "online1234";
$key = "haskingvista127$";

$iv  = 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));

?>

希望这可以帮助其他人

暂无
暂无

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

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