PHP mcrypt_decrypt-我可以确定是否使用正确的密钥解密数据吗? [英] PHP mcrypt_decrypt - can I determine if data is decrypted with the right key?

查看:83
本文介绍了PHP mcrypt_decrypt-我可以确定是否使用正确的密钥解密数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用php脚本,正在使用mcrypt加密/解密任意数据.

I'm working on a php script and are using mcrypt to encrypt/decrypt arbitrary data.

当我使用另一个密钥(例如,我输入了错误的密码)解密加密的数据时,输出当然不会被正确解密.

When I decrypt encrypted data, using another key (e.g. I typed in the wrong password), the output won't be correctly decrypted of course.

如果使用了错误的密钥,我想显示一条错误消息,但是我认为很难将输出字符串验证为正确的纯文本"(因为编码数据中的字符也可以作为输入有效)数据).

If the wrong key has been used I would like to display an error message, but I'm thinking it's quite hard to validate the output string as correct "plaintext" (since the chars in the encoded data are also valid as input data).

有什么办法可以解决这个问题?

Is there any way to get around this?

在我写这个问题时,我有了一个主意:)

As I was writing this question, I got an idea :)

我可以在输入数据前添加静态控制"字符串作为前缀,并在解密时使用此字符串进行验证吗?

Could I possibly prefix the input data with a static "control" string and use this for validation when I decrypt?

推荐答案

我通常这样做:

  • 散列输入数据(文件或消息或其他内容).
  • 加密数据.
  • 在加密的数据前加上IV和数据的哈希值.
  • 发送或存储IV +哈希+密文.

由于IV和哈希值的长度始终相同,因此无需添加填充或控制字符.

As the IV and hash are always the same length, there is no need to add padding or control characters.

在接收或读取方面:

  • 提取IV.
  • 提取哈希值.
  • 提取并解密加密的文本.
  • 对解密的数据进行哈希处理,并检查其是否与提取的哈希匹配.

因此,您存储的是源数据的哈希,而不是密钥的哈希.正如上面的评论者所述,泄露密钥的哈希值是一个漏洞,因为攻击者现在只需要在彩虹表中搜索它(这将在几秒钟内破坏您的数据).

So, you store the hash of the source data, NOT the hash of the key. As a commenter posted above, giving away the hash of your key is a vulnerability, as the attacker now needs only to search it in a rainbow table (it would compromise your data in a matter of seconds).

您存储控制字符串的想法也不错(肯定更快),但仅使用了正确的密钥,就无法确认消息或数据确实未损坏.

You idea of storing a control string is good too (certainly is faster) but it cannot allow you to confirm the message or data is indeed uncorrupted, only that the correct key was used.

这篇关于PHP mcrypt_decrypt-我可以确定是否使用正确的密钥解密数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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