gpt4 book ai didi

java - AES-256 CBC 在 php 中加密并在 Java 中解密,反之亦然

转载 作者:行者123 更新时间:2023-12-02 03:00:49 28 4
gpt4 key购买 nike

JAVA

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

class AES256JavaPhp{
public static void main(String[] args) throws Exception {
Base64 base64 = new Base64();
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new
SecretKeySpec("PasswordPassword".getBytes("UTF-8"),"AES");
IvParameterSpec iv = new IvParameterSpec
("dynamic@dynamic@".getBytes("UTF-8"),0,ciper.getBlockSize());
//Encrypt
ciper.init(Cipher.ENCRYPT_MODE, key,iv);
byte[] encryptedCiperBytes = base64.encode
((ciper.doFinal("Hello".getBytes())));
System.out.println("Ciper : "+new String(encryptedCiperBytes));
//Decrypt
ciper.init(Cipher.DECRYPT_MODE, key,iv);
byte[] text = ciper.doFinal(base64.decode(encryptedCiperBytes));
System.out.println("Decrypt text : "+new String(text));
}
}

Java 输出:

Ciper : KpgzpzCRU7mTKZePpPlEvA==
Decrypt text : Hello

PHP

<?php>    
$cipherText = encrypt("Hello", 'aes-256-cbc');
exit();

function encrypt($data, $algo)
{
$key = 'PasswordPassword';
//$iv = random_bytes(openssl_cipher_iv_length($algo));
$iv = 'dynamic@dynamic@';
$cipherText = openssl_encrypt(
$data,
$algo,
$key,
OPENSSL_RAW_DATA,
$iv
);
$cipherText = base64_encode($cipherText);
printData("Ciper Text : $cipherText");

$cipherText = base64_decode($cipherText);
$plaintext = openssl_decrypt(
$cipherText,
$algo,
$key,
OPENSSL_RAW_DATA,
$iv
);
printData("Plain Text after decryption : $plaintext");
}

function printData($obj)
{
print_r($obj);
}
?>

PHP 输出:

Ciper Text : ef/ENVlBn9QBFlkvoN7P2Q==
Plain Text after decryption : Hello

即使使用相同的 key 和 IV,生成的密码也是不同的。这怎么可能?

最佳答案

显然,您必须使用相同的 AES key 和 IV 来实现安全 session 。并且必须在客户之间正确、安全地传达这些信息。客户端用什么语言编写根本不重要。您的问题是不了解 key 协商和 session 建立的协议(protocol)。

初始化 vector 不是 protected 值;即,在客户端之间通信时,您没有对其进行加密。它必须使用加密的 AES key (从某些 key 协商协议(protocol)派生)以明文形式打包。

CMS使用 KeyTransRecipientInfo来传递此信息。 TLS还定义 IV establishment关注其 handshake 。我强烈建议遵循 CMS 实现,而不是人为的、几乎肯定会包含安全错误的东西。

<小时/>

更新

现在很明显,您很困惑为什么生成的密文不是确定性的。这是因为 Java 实现默认采用 128 位加密,并已提供 128 位 key ,但是 PHP 代码请求 256 位强度加密,并且仅提供相同的 128 位 key 。因此,PHP 必须填充该键。

<小时/>

更新2

根据您的以下评论,以下是使用 Java 生成 256 位 key 的示例:

KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256); // The AES key size in number of bits
SecretKey secKey = generator.generateKey();

关于java - AES-256 CBC 在 php 中加密并在 Java 中解密,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396690/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com