使用 phpseclib AES 加密字符串

Using phpseclib AES to encrypt string

好的,下面是页面 http://phpseclib.sourceforge.net/crypt/examples.html

中的示例代码
<?php
include('Crypt/AES.php');
include('Crypt/Random.php');

$cipher = new Crypt_AES(); // could use CRYPT_AES_MODE_CBC
// keys are null-padded to the closest valid size
// longer than the longest key and it's truncated
//$cipher->setKeyLength(128);
$cipher->setKey('abcdefghijklmnop');
// the IV defaults to all-NULLs if not explicitly defined
$cipher->setIV(crypt_random_string($cipher->getBlockLength() >> 3));

$size = 10 * 1024;
$plaintext = str_repeat('a', $size);

echo $cipher->decrypt($cipher->encrypt($plaintext));
?>

首先,为什么 //$cipher->setKeyLength(128); 行被注释掉了?

如果我想将密钥设置为“1234568790”,有什么我应该做的吗?因为它比上面示例中的密钥长度 (abcdefghijklmnop) 短得多。

最后,如果我要加密的明文很短,比如“我的名字是詹姆斯·邦德”,还有什么我应该做的吗?因为从上面的代码来看,明文的长度似乎应该是10 x 1024。(为什么?)

Before anything, why is the line //$cipher->setKeyLength(128); is being commented out?

假设您通过 setKey 将一个 17 字节的密钥传递给 phpseclib。你认为应该发生什么?在 1.0 和 2.0 版本中,如果 setKeyLength 未被调用,则密钥被空填充为 24 字节(例如 192 位)。但是如果调用 setKeyLength 它将被截断为 16 个字节。在 master 分支(据我了解,它最终将成为 3.0 分支)中,如果密钥长度无效,则会抛出异常。在该版本中,可能仍然需要调用 setKeyLength,例如,如果您想在代码的一部分中将密钥长度设置为 128 位,然后在代码的另一部分中实际设置密钥代码。 IE。你可以做长度检查或者 phpseclib 可以做长度检查。

And if I want to set my key to '1234568790', is there anything I should do? Because it's much shorter than they length of the key in the example above (abcdefghijklmnop).

1234568790 在技术上不够长,不能成为有效密钥。它有 80 个字节长。 AES 支持的最小密钥是 128 位。也许你应该考虑做类似 setPassword('1234568790') 而不是 setKey('1234568790') 的事情。 setPassword 将使用密钥派生函数从密码生成密钥。

在 phpseclib 1.0 和 2.0 中 setKey 将 none-the-less 接受它作为密钥。它只会空填充键。主分支 otoh 将抛出异常,因为密钥实际上不够长。

And finally if the plaintext that I want to encrypt is short, something like "my name is james bond", is there anything extra that I should do? Because from the code above, it seems the plaintext's length should be 10 x 1024. (Why is that?)

10 * 1024 只是一个例子。默认情况下,phpseclib 将使用 PKCS7 填充来使字符串足够长。例如。你的字符串有 21 个字节长(如果我没数错的话)。因此,如果您调用 $cipher->encrypt('my name is james bond'),那么 chr(11) 将通过 phpseclib 附加到明文 11 次,然后字符串将被加密。这是因为块算法需要明文是块长度的倍数。所以密文将是 32 字节长。当您随后调用 $cipher->decrypt('...') 时,您将获得原始的 21 字节字符串。我可以进一步详细说明 PKCS7 填充,但我想我已经回答了您的直接问题。