首页 > 解决方案 > 使用 postegresql 数据在 Laravel 中加密和解密

问题描述

当我给出像“你好”这样的数据时。功能是加密和解密没有问题。但是当我从数据库中获取数据时,解密函数给出有效载荷无效错误。

$listed_policy = DB::table('table_name')
    ->join('table_name_second', 'be_product.id', '=', 'table_name.product_id')
    ->pluck('identity_no');
        
 
$private_secret_key[] =array('1','2','3','4','5');
$encrypted = encrypt($original_string, $private_secret_key);
$original_string = $listed_policy[0];
$encrypted = decrypt($original_string,$private_secret_key);   

/* DATA İS THAT eyJpdiI6Ino4YjNaNEFOUXlxZm0xeHdZaEx0YVE9PSIsInZhbHVlIjoidmFaRlVCUEF0SzZvRzNraHBjalo4Zz09IiwibWFjIjoiMzJhODYwOWFmYjk1NzU3YjliOGE4Y2I1N2JjN2I0NTMwMTM0ZTViYWU4Y2JiYWQ4YWNlMDA3ODc4M2Q4ZDdmZSJ9
*/

$private_secret_key[] =array('x', 'x', 'x', 'x', 'x', '.', 'x', 'x', 'x', '!', 'z', 'z', 'z', 'z', 'z', 'z');
$encrypted = decrypt($original_string,$private_secret_key);
dd($encrypted);
die();
function encrypt($message, $encryption_key)
{
    $key = hex2bin($encryption_key);
    $nonceSize = openssl_cipher_iv_length('aes-256-ctr');
    $nonce = openssl_random_pseudo_bytes($nonceSize);
    $ciphertext = openssl_encrypt(
        $message, 
        'aes-256-ctr', 
        $key,
        OPENSSL_RAW_DATA,
        $nonce
    );
    
    return base64_encode($nonce.$ciphertext);
}

function decrypt($message,$encryption_key) {
    $key = hex2bin($encryption_key);
    $message = base64_decode($message);
    $nonceSize = openssl_cipher_iv_length('aes-256-ctr');
    $nonce = mb_substr($message, 0, $nonceSize, '8bit');
    $ciphertext = mb_substr($message, $nonceSize, null, '8bit');
    $plaintext= openssl_decrypt(
        $ciphertext, 
        'aes-256-ctr', 
        $key,
        OPENSSL_RAW_DATA,
        $nonce
    );

    return $plaintext;
}

我怎么解决这个问题 ?

标签: phplaravelencryptioncryptographylaravel-8

解决方案


推荐阅读