PHP实现OPENSSL的EVP_BytesToKey

使用PHP和nodejs进行通讯时候遇到双方加解密结果不一致的问题。

注意到crypto.createCipher(algorithm, password[, options])方法有如下的提示。

text 复制代码
The implementation of crypto.createCipher() derives keys using the OpenSSL 
function EVP_BytesToKey with the digest algorithm set to MD5, one iteration, and no salt. 

createCipher方法只接受key,不接受iv参数,iv参数是使用openssl的EVP_BytesToKey方法对key进行扩展得来的,salt为空,hash算法为MD5。

可以使用新的createCipheriv方法代替,但原来的NodeJs代码不能修改,只能从php方面入手修改。

简易实现-使用php对key进行扩展,再进行加解密。

php 复制代码
function EVP_BytesToKey($salt, $password) {

    $bytes = '';

    $last = '';

    while(strlen($bytes) < 48) {

        $last = hash('md5', $last . $password . $salt, true);

        $bytes.= $last;

    }

    return $bytes;

}
//从扩展结果中分离真正用于通讯的key和iv
$key = '12345678901234561234567890123456';
$devd = EVP_BytesToKey('', $key);
$key = substr($devd, 0, 32);
$iv = substr($devd, 32, 16);

@openssl_encrypt('test-data', "aes-256-cbc", $key,  1, $iv);

nodejs直接使用key进行加解密

js 复制代码
const key = '12345678901234561234567890123456';
crypto.createCipher("aes-256-cbc", key)

EVP_BytesToKey的完整实现

php 复制代码
/**
 * @param string $password
 * @param int $nkey 需要生成的密钥长度
 * @param int $niv 需要生成的iv长度
 * @param string $hash HASH算法,默认MD5
 * @param string $salt salt。默认为空
 * @param int $round HASH运行轮数
 * @return array
 */
function EVP_BytesToKey(string $password, int $nkey = 32, int $niv = 16, string $hash = 'md5', string $salt = '', int $round = 1): array
{
    $bytes = '';
    $last = '';
    $total = $nkey + $niv;

    while (strlen($bytes) < $total) {
        $last = hash($hash, $last . $password . $salt, true);

        for ($i = 1; $i < $round; $i++) {
            $last = hash($hash, $last, true);
        }
        $bytes .= $last;
    }

    return [
        'key' => substr($bytes, 0, $nkey),
        'iv' => substr($bytes, $nkey, $niv),
    ];

}

更多语言实现

https://github.com/sometiny/evp_bytestokey

相关推荐
潼心1412o4 分钟前
C++初阶(长期更新)第9讲:string(上)
开发语言·c++
朝朝辞暮i16 分钟前
C++ 第 39 章: 阶段性总复习——类、对象、构造、继承、this、指针与智能指针
开发语言·c++·算法·ros2
掉进电商坑三年没爬出来的东叔1 小时前
青龙面板进阶:一个面板聚合多平台签到,所有积分自动领
java·开发语言
iCxhust1 小时前
51单片机电力载波应用开发(七)广播通讯
c语言·开发语言·单片机·嵌入式硬件·51单片机
Lsetea1 小时前
OpenSSL verify报CA certificate key too weak:auth_level与弱密钥链排查
运维·https·ssl证书·openssl·证书链
殷色玫瑰2 小时前
C++ STL:stack、queue、priority_queue 与容器适配器详解
java·开发语言·数据结构·c++·算法·visualstudio
IT方大同2 小时前
java输入输出+方法
java·开发语言·python
滕州市燕猫虎计算机科技工作室个体工商户2 小时前
《Rust程序设计》学习笔记一
开发语言·rust·学习笔记·rust程序设计
Wang's Blog2 小时前
Java框架 SpringCloud 快速入门: 服务拆分之服务远程调用
java·开发语言·spring cloud
努力努力再努力wz2 小时前
【CUDA入门系列】CUDA编程实战:设备选择、显存管理、Kernel、Stream 与 Event 全流程梳理
开发语言·c++