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

相关推荐
xqlily2 小时前
Kotlin:现代编程语言的革新者
android·开发语言·kotlin
csbysj20202 小时前
XSLT Apply:深入解析XSLT在XML转换中的应用
开发语言
不会kao代码的小王2 小时前
突破机房围墙:openEuler设备的公网管理实战指南
开发语言·数据库·笔记
CodeCraft Studio2 小时前
CAD文件处理控件Aspose.CAD教程:在 Python 中将 SVG 转换为 PDF
开发语言·python·pdf·svg·cad·aspose·aspose.cad
消失的旧时光-19433 小时前
人脸跟随 ( Channel 实现(缓存5条数据 + 2度过滤 + 平滑移动))
android·java·开发语言·kotlin
默默coding的程序猿3 小时前
1.单例模式有哪几种常见的实现方式?
java·开发语言·spring boot·spring·单例模式·设计模式·idea
一人の梅雨3 小时前
京东商品详情深度解析:从接口调用到商业价值挖掘的技术实现
服务器·数据库·php
MOON404☾3 小时前
Rust程序语言设计(5-8)
开发语言·后端·rust
帅帅梓3 小时前
docker网络
网络·docker·php
Knight_AL5 小时前
浅拷贝与深拷贝详解:概念、代码示例与后端应用场景
android·java·开发语言