gpt4 book ai didi

java - PHP 中等效的 AES 128 位

转载 作者:行者123 更新时间:2023-12-03 18:41:51 24 4
gpt4 key购买 nike

我有这段 Java 代码,它使用 AES 128 位将源字符串加密为 Base64 加密值。但是我没能找到产生相同结果的类似 PHP 函数。任何帮助将不胜感激

    String key = "1234567890123456";
String source = "The quick brown fox jumped over the lazy dog";

byte[] raw = key.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal(source.getBytes());
System.out.println(new String(Base64.encodeBase64(encrypted)));

最佳答案

这就是答案。感谢@owlstead 和他提到的线程中原始答案的所有者

<?php
function encrypt($str, $key){
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB));
}

function decrypt($str, $key){
$str = base64_decode($str);
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
$pad = ord($str[($len = strlen($str)) - 1]);
$len = strlen($str);
$pad = ord($str[$len-1]);
return substr($str, 0, strlen($str) - $pad);
}
?>

关于java - PHP 中等效的 AES 128 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9462380/

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