如何使用 OpenSSL 解密使用 ASCII 密钥的 Mcrypt 生成的值? [英] How to use OpenSSL to decrypt a value generated with Mcrypt that has used an ASCII key?

查看:126
本文介绍了如何使用 OpenSSL 解密使用 ASCII 密钥的 Mcrypt 生成的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够使用 OpenSSL 解密在 PHP 下使用 Mcrypt 生成的值.

I need to be able to decrypt values using OpenSSL that were generated using Mcrypt under PHP.

我有这个工作,除了用于加密它们的密钥是 ascii.

I have this working, with the exception that the key used to encrypt them was ascii.

以下是我的代码,它演示了一个工作案例,当密钥是 MD5 时,OpenSSL 可以解密使用 Mcrypt 加密的值.

The following is my code that demonstrates a working case where OpenSSL can decrypt the value encrypted with Mcrypt, when the key is an MD5.

<?php
$message = 'test';
$key = md5('Quigibo');

$iv = openssl_random_pseudo_bytes(0);

$encrypted = mcrypt_encrypt(
    MCRYPT_BLOWFISH,
    $key,
    $message,
    MCRYPT_MODE_ECB,
    $iv
);

$decrypted = openssl_decrypt(
    $encrypted,
    'bf-ecb',
    $key,
    OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,
    $iv
);

$trimDecrypted = rtrim($decrypted);

var_export(
    [
        'Original message' => $message,
        'Encrypted' => bin2hex($encrypted),
        'Decrypted' => $decrypted,
        'Trim decrypted' => $trimDecrypted,
        'Message length' => mb_strlen($message, '8bit'),
        'Decrypted length' => mb_strlen($decrypted, '8bit'),
        'Message == decrypted' => $message === $trimDecrypted
    ]
);

但是,如果您将 $key 更改为值Quigibo"(而不是该值的 MD5 哈希),则无法使用 OpenSSL 解码加密值.

However, if you change $key to be the value "Quigibo" (as opposed to an MD5 hash of that value) the encrypted value cannot be decoded with OpenSSL.

在与 OpenSSL 一起使用之前,是否可以将一种编码形式应用于 ASCII 密钥,以便正确解密该值?

Is there a form of encoding I can apply to the ASCII key prior to use with OpenSSL such that it will correctly decrypt the value?

推荐答案

修改后的答案:

OpenSSL 中存在一个错误,它将 Blowfish 的密钥空填充为 16 个字节,这是不正确的,因为密码支持可变长度的密钥.他们最近添加了一个标志来解决这个问题 - OPENSSL_DONT_ZERO_PAD_KEY - 但它只在一个多星期前发布的 php 7.1.8 中可用......相关错误:https://bugs.php.net/bug.php?id=72362

There is a bug in OpenSSL which null pads the key to 16 bytes for Blowfish, which is incorrect because the cipher supports a variable length key. They have very recently added a flag to fix this - OPENSSL_DONT_ZERO_PAD_KEY - but it is only available in php 7.1.8 which was released a little over a week ago... Relevant bug: https://bugs.php.net/bug.php?id=72362

一种解决方法是手动循环密钥并将其提供给 OpenSSL:

A workaround is to manually cycle the key and feed that into OpenSSL:

$keylen = (floor(mb_strlen($key, '8bit')/8)+1)*56;
$key_cycled = substr(str_repeat($key,ceil($keylen/strlen($key))),0,$keylen);

$decrypted = openssl_decrypt(
$encrypted,
'bf-ecb',
$key_cycled,
OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,
$iv
);

这篇关于如何使用 OpenSSL 解密使用 ASCII 密钥的 Mcrypt 生成的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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