OpenSSL加密/解密php [英] OpenSSL Encryption / Decryption php

查看:59
本文介绍了OpenSSL加密/解密php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行加密,效果很好,但是使用相同的方法进行解密,但是我得到的是空白字符串而不是解密字符串.我正在使用方法 AES-256-ECB ,并且密钥是十六进制的,所以我通过了

I am doing encryption which is working good but with same method I am doing decryption I am getting blank string not getting decryption string. I am using method AES-256-ECB and key is hexadecimal so I pass as

$ key = pack('H *','xxxxxxxxxxxx');

$key = pack('H*','xxxxxxxxxxxx');

加密正确,但是解密不起作用.请帮助我我做错了.

Encryption is going correct but decryption is not working. Please help me what I am doing wrong.

function encrypt(string $data, string $key, string $method): string
{
    $ivSize = openssl_cipher_iv_length($method);
        $iv = openssl_random_pseudo_bytes($ivSize);
        $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
    $encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
    return $encrypted;
}

function decrypt(string $data, string $key, string $method): string
{

    $data = pack('H*', $data);
    $ivSize = openssl_cipher_iv_length($method);  
        $iv = $iv = openssl_random_pseudo_bytes($ivSize);
    $decrypted = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv); 
    return trim($decrypted);
}

推荐答案

使用以下代码,您的函数对我而言非常完美:

Your functions are working perfectly for me with the following code:

$key = pack('H*','aaaaaaaaaaaaa');
$method = 'aes-256-ecb';
$encrypted = encrypt('test string', $key, $method);
$decrypted = decrypt($encrypted, $key.'a', $method);

echo $decrypted; // Output: 'test string'

由于要解密的字符串是空的,这意味着解密时您得到的密钥或密文都不正确.确保用于解密的密钥与用于加密的密钥完全相同,包括对其进行的任何操作,例如您在此处执行的 pack()函数.即使只有一个字节的差异,您也将无法解密.

Since you're getting an empty string for decryption, this means that you've either got the wrong key or cipher text when decrypting. Make sure the key you are using for decryption is exactly the same as the key you're using for encryption, including any manipulations done on it, such as the pack() function you've done here. Even one byte difference and you're not going to be able to decrypt.

还要确保密钥和密文在存储时都没有被截断.如果使用数据库并且列类型对于要存储的内容而言太小,则会截断值.

Also make sure neither the key nor the cipher text are being truncated when they are stored. If using a database and the column type is too small for what you are trying to store, it will truncate the values.

这篇关于OpenSSL加密/解密php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆