如何使openssl_encrypt将输入填充到所需的块大小? [英] How do I make openssl_encrypt pad the input to the required block size?

查看:139
本文介绍了如何使openssl_encrypt将输入填充到所需的块大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我手动将字符串填充到32的长度,我的代码将起作用.
我的问题是:有没有办法使openSSL填充数据,还是我总是必须为此做?

My code works if I manually pad my string to the length of 32.
My question is: Is there a way to make the openSSL pad the data, or do I always have to do it for it?

工作:

 openssl_encrypt ("my baba is over the ocean1111111", 'AES-256-CBC', $MY_SECRET_KEY,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$MY_IV);

不起作用:

openssl_encrypt ("my baba is over the ocean", 'AES-256-CBC', $MY_SECRET_KEY,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$MY_IV);

我目前通过自我填充解决了这个问题:

I solve this currently by self padding:

$pad = 32 - (strlen("my baba is over the ocean") % 32);
$clear = "my baba is over the ocean" . str_repeat(chr($pad), $pad); //encrypt this string

推荐答案

正如卢克·帕克(Luke Park)所说,与其明确告诉openssl_encrypt使用OPENSSL_ZERO_PADDING,不如从参数中删除该选项,它将默认为 PKCS#7填充方案(用0x0n填充块的其余部分,其中 n 是必需的字节数;如果该块已经完成,则为+ 16 0x00. 注意:在这种情况下,Luke和PKCS#7引用的PKCS#5实际上是相同的.

As Luke Park said, instead of explicitly telling openssl_encrypt to use OPENSSL_ZERO_PADDING, simply remove that option from the parameter and it will default to the PKCS #7 padding scheme (fills the rest of the block with 0x0n where n is the number of bytes necessary; + 16 0x00 if the block is already complete). Note: PKCS #5 as referenced by Luke and PKCS #7 are effectively identical in this scenario.

来自 PHP文档:

不使用OPENSSL_ZERO_PADDING,您将自动获得PKCS#7填充.

Without using OPENSSL_ZERO_PADDING, you will automatically get PKCS#7 padding.

所以您应该打电话给

openssl_encrypt("my baba is over the ocean", 'AES-256-CBC', $MY_SECRET_KEY, OPENSSL_RAW_DATA, $MY_IV);

这篇关于如何使openssl_encrypt将输入填充到所需的块大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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