加密 – 解密AES PHP

我想用AES CCM加密和解密一些数据!

我设法在同一个PHP文件中执行此操作.但我希望能够将加密数据发送到另一个页面进行解密.但不可能……但我发送了iv,标签和加密数据.
你有解决方案吗?

我有这些错误

Warning: openssl_decrypt(): Setting tag for AEAD cipher decryption Failed in adddata1.PHP on line 18

Fatal error: Uncaught Exception: OpenSSL error: error:0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length in adddata1.PHP:21 Stack trace: #0 {main} thrown in dddata1.PHP on line 21

第一档:
    

$algo  = 'aes-128-ccm';
$iv    = random_bytes(openssl_cipher_iv_length($algo));
$key   = "cd9344040aa9f9217871d46ee871c59c"; 
$data = '00000000010-3b57af';
$ciphertext = openssl_encrypt(
    $data,
    $algo,
    $key,
    OPENSSL_RAW_DATA,
    $iv,
    $tag
);

echo'<a href="adddata1?data='.$ciphertext.'&tag='.$tag.'&iv='.$iv.'">"decrypte"</a>';
?>

第二档:
    

$algo  = 'aes-128-ccm';
$key   = "cd9344040aa9f9217871d46ee871c59c"; 

$ciphertext = $_GET['data'];
$iv = $_GET['iv'];
$tag = $_GET['tag'];
// Change 1 bit in additional authenticated data
// $i = rand(0, mb_strlen($aad, '8bit') - 1);
// $aad[$i] = $aad[$i] ^ chr(1);
$decrypt = openssl_decrypt(
    $ciphertext,
    $algo,
    $key,
    OPENSSL_RAW_DATA,
    $iv,
    $tag
);
if (false === $decrypt) {
    throw new Exception(sprintf(
        "OpenSSL error: %s", openssl_error_string()
    ));
}


printf ("Decryption %s\n", $data === $decrypt ? 'Ok' : 'Failed');
printf("<br/>");
printf(base64_encode($tag));
printf("<br/>");
printf(base64_encode($iv));
printf("<br/>");
printf(base64_encode($ciphertext));
printf("<br/>");
printf($data);
?>

一个文件中:

<?PHP

$algo  = 'aes-128-ccm';
$iv    = random_bytes(openssl_cipher_iv_length($algo));
$key   = "cd9344040aa9f9217871d46ee871c59c"; 
$data = '00000000010-3b57af';
$ciphertext = openssl_encrypt(
    $data,
    $algo,
    $key,
    OPENSSL_RAW_DATA,
    $iv,
    $tag
);

// Change 1 bit in additional authenticated data
// $i = rand(0, mb_strlen($aad, '8bit') - 1);
// $aad[$i] = $aad[$i] ^ chr(1);
$decrypt = openssl_decrypt(
    $ciphertext,
    $algo,
    $key,
    OPENSSL_RAW_DATA,
    $iv,
    $tag
);
if (false === $decrypt) {
    throw new Exception(sprintf(
        "OpenSSL error: %s", openssl_error_string()
    ));
}


printf ("Decryption %s\n", $data === $decrypt ? 'Ok' : 'Failed');
printf("<br/>");
printf(base64_encode($tag));
printf("<br/>");
printf(base64_encode($iv));
printf("<br/>");
printf(base64_encode($ciphertext));
printf("<br/>");
printf($data);
?>

谢谢

解决方法:

问题可能是iv.您正在生成随机字节并将其作为请求参数添加到URL中,其中字符串编码很重要.将字节转换为URL中有效的字符. bin2hex一个简单的方法

echo '<a href="adddata1?data='.$ciphertext.'&iv='.bin2hex($iv)...

并在接收端将其转换回来:

$iv = hex2bin($_GET['iv']);

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...