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参数是使用opensslEVP_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

相关推荐
chao1898447 小时前
基于字典缩放的属性散射中心参数提取算法与MATLAB实现
开发语言·算法·matlab
小尧嵌入式7 小时前
【Linux开发四】Linux中概念|MobaXterm和Filezilla软件使用|线程|互斥锁|读写锁
linux·运维·服务器·开发语言·数据结构
a努力。7 小时前
Spring Boot 4 全面拥抱 Jackson 3
java·运维·开发语言·spring boot·后端·spring·jenkins
晚霞的不甘8 小时前
Flutter for OpenHarmony 布局探秘:从理论到实战构建交互式组件讲解应用
开发语言·前端·flutter·正则表达式·前端框架·firefox·鸿蒙
爱吃大芒果8 小时前
Flutter for OpenHarmony核心组件学习: MaterialApp、Scaffold 两大基础组件以及有无状态组件
开发语言·学习·flutter
运筹vivo@8 小时前
BUUCTF: [极客大挑战 2019]BabySQL
前端·web安全·php·ctf
做科研的周师兄8 小时前
【MATLAB 实战】栅格数据一元线性回归计算(NDVI 趋势分析)| 附完整可运行代码
开发语言·matlab·线性回归
fengfuyao9858 小时前
基于MATLAB的量子图像加密实现
开发语言·matlab·量子计算
Rabbit_QL16 小时前
【水印添加工具】从零设计一个工程级 Python 图片水印工具:WaterMask 架构与实现
开发语言·python
天“码”行空16 小时前
简化Lambda——方法引用
java·开发语言