正确的 PHP mcrypt 加密方法?
好吧,我尝试使用 PHP mcrypt
创建自己的加密/解密方法,当我不久前发布它们时,有些人称它们为“垃圾”。他们提到了“初始化向量”之类的事情。基本上,我怎样才能使这些加密方法变得更好:
function encrypt($key, $data){
$encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $data, MCRYPT_ENCRYPT);
return base64_encode($encrypted_data);
}
function decrypt($key, $encryptedData){
$dec = base64_decode($encryptedData);
$decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $dec, MCRYPT_DECRYPT);
return trim($decrypt);
}
我希望这些方法能发挥最大作用,除非我在 mcrypt
方面处于一个全新的世界,欢迎任何建议,谢谢!
Ok, I have tried to create my own encryption/decryption methods using PHP mcrypt
, and when I posted them a while back some called them "trash". They were mentioning things about "Initialization Vectors" and such. Basically, how can I make these cryptography methods better:
function encrypt($key, $data){
$encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $data, MCRYPT_ENCRYPT);
return base64_encode($encrypted_data);
}
function decrypt($key, $encryptedData){
$dec = base64_decode($encryptedData);
$decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $dec, MCRYPT_DECRYPT);
return trim($decrypt);
}
I want these to work the best they can except I am a duck in a brand new world when it comes to mcrypt
, any suggestions are welcome, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我使用的 mcrypt 函数的片段。它们使用
mcrypt_generic
和mdecrypt_generic
,应根据 PHP 手册。我对
mcrypt
也不太了解,所以我只是将它们组合在一起。我对密钥进行 md5 处理,使其始终为 32 个字符(最大密钥长度),然后随机计算“初始化向量”。使用 PKCS7 填充 更好,因为您可以使用以空格结尾的字符串(因为
trim
会删除它),当字符串达到一定长度时,加密也会更有效。我在这里使用 AES 256 (MCRYPT_RIJNDAEL_256),但 AES 192 (MCRYPT_RIJNDAEL_192) 也可以。
演示:http://ideone.com/WA5Tk
Here is a snippet of the mcrypt functions I use. They use
mcrypt_generic
andmdecrypt_generic
, which should be used according to the PHP manual.I don't know much about
mcrypt
either, so I just kinda hacked these together. Imd5
the key so it's always 32 characters (the max key length), and I randomly calculate an "Initialization Vector".Using PKCS7 Padding is better because you can have strings that end in white space (as
trim
would remove that), also the encryption is more efficient when the string is a certain length.I'm using AES 256 (MCRYPT_RIJNDAEL_256) here, but AES 192 (MCRYPT_RIJNDAEL_192) would work too.
Demo: http://ideone.com/WA5Tk
您可以使用
mcrypt_create_iv()
创建一个 iv,并使用适合您的加密模式的大小。然后将其作为可选的第 5 个参数传递给
mcrypt_cbc()
。我对原始函数所做的唯一更改是传入$iv
:You can create an iv with
mcrypt_create_iv()
, using the appropriate size for your encryption mode.Then pass it to
mcrypt_cbc()
as the optional 5th parameter. The only changes I've made here to your original functions are to pass in$iv
: