mcrypt加密了一串'%00'到字符串的结尾 [英] mcrypt encrypt adding s bunch of '%00' to end of string
问题描述
使用OAuth并使用我们称为foo的字符串(实际上是OAuth令牌)使用以下功能加密密钥。
public function encrypt($ text)
{
//添加文本分隔符的结尾
$ data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$ this-> key,$ text,MCRYPT_MODE_ECB ,$ this-> iv);
返回base64_encode($ data);
}
当我使用反函数解密时,我最终得到: p>
功能:
public function decrypt( $ text)
{
$ text = base64_decode($ text);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$ this-> key,$ text,MCRYPT_MODE_ECB,$ this-> iv);
}
结果:
foo%00%00%00%00%00%00%00%00%00%00%00%00%00%00
编辑:
再看一下,我意识到实际上是URL编码到%00,这意味着我的字符串以某种方式被空字符填充?所以我目前正在使用trim()来摆脱它们,但是我想了解为什么会发生这种情况。
Rijndael是块密码,这意味着它对特定长度的数据块进行操作(在这种情况下为128位) 。这意味着如果输入文本的长度不是块大小的倍数,则必须将其填充以适合。在这种情况下,填充为零;还有一些其他可能的填充方案可以使用,但如果您希望使用PHP的mcrypt你必须手动应用它们。
Working with OAuth and encrypting the keys with the following function with a string which we'll call 'foo' (actually an OAuth token)
public function encrypt( $text )
{
// add end of text delimiter
$data = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
return base64_encode( $data );
}
When I decrypt it using the inverse function, I end up with:
Function:
public function decrypt( $text )
{
$text = base64_decode( $text );
return mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
}
Result:
foo%00%00%00%00%00%00%00%00%00%00%00%00%00%00
Edit:
Looking at it a little more, I realized that it is actually URL encoding to %00, which means that my strings are somehow being padded by null characters? So I am currently using trim() to get rid of them, but I would like to understand why this is happening.
Rijndael is a block cypher, which means that it operates on chunks of data of a particular length (128 bits in this case). This means that if the length of the input text is not a multiple of the block size, it must be padded out to fit. In this case, the padding is zeros; there are a number of other possible padding schemes that could be used, but if you want them with PHP's mcrypt you'll have to apply them manually.
这篇关于mcrypt加密了一串'%00'到字符串的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!