java aes 256 cbc_AES-256 CBC在php中加密并在Java中解密,反之亦...

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

$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

得到的密码是不同的,即使它们使用相同的密钥和IV.这怎么可能?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值