JSEncrypt 每次为相同的消息和公钥生成不同的输出 [英] JSEncrypt producing different output for identical message and public key each time
问题描述
我有这么简单的 JavaScript 代码:
I've got this simple bit of JavaScript:
<html>
<script type="text/javascript" src="http://cdn.rawgit.com/travist/jsencrypt/v2.1.0/bin/jsencrypt.js"></script>
<script type="text/javascript">
var message = "This is my message"
// we create a new JSEncrypt object for rsa encryption
var rsaEncrypt = new JSEncrypt();
var publicKey = "-----BEGIN PUBLIC KEY-----" +
"\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQK" +
"BgQCQDxDFOYJpkCaqeX4CBVNCtBjX\nMZgGMo" +
"lSs2wYrVu1ixr36KpeJcRcYhz+AnyhnUpYkgk" +
"+hEqJtDSNirU5Dk5oVYYi\ngf2uLogV5Tp/ka" +
"K49r9vtxldcHraZIgNQjcdeQUd/viKd/3DvM8" +
"naWR/mTG0nCBE\nrEQkATW/xXynJh/COQIDAQ" +
"AB\n-----END PUBLIC KEY-----"
rsaEncrypt.setPublicKey(publicKey);
var encryptedMessage = rsaEncrypt.encrypt(message);
console.log(encryptedMessage)
</script>
</html>
我觉得每次运行时都应该在控制台中产生相同的输出,但事实并非如此.
That I feel should be producing the same output in the console each time it runs, but it doesn't.
示例输出:
abqE+YkCMKFWgsazbZpfGvoXLci9FL/wZLYUMR6ZFkolsvJC5MdJgq5yn+AXXy8xlKHDOry6czAaOQOTl2HXdKSfsypc8nqDU8Sx5PuEgMYjvJ/dEyfU6jVuxfH1Qmuk6aOGVHePNfDlC4kSjgp1RXToSP5NqAEi24EuMx3uulI=
OzZM03Pki3o631KOuZ5nyQKu1xXRbLHhrR0WnjE5Ns5SssoiCEwlrS+svtP0cbZaYWZJc+FlZQNFUam4iC233BKnY5Nrr5Ppj14eaBvJ4x3FR8FiLwtyEW7nTzisAS7Ys2RKPjUzmkiOCZHwIpXnUO10KVo8763+JIuDB0cDPS4=
谁能解释这种行为?
推荐答案
这是意料之中的.
RSA 密码系统以组模某个素数的形式工作.为确保所有可能的明文都以相同的安全性进行加密,对明文进行填充以产生略小于模数的填充明文.由于在加密之前应用了填充,因此密文看起来完全不同.
The RSA cryptosystem works in group modulo some prime number. To ensure that all possible plaintexts are encrypted with the same security, the plaintexts are padded to produce a padded plaintext that is slightly smaller than the modulus. Since the padding is applied before encryption, the ciphertext looks completely different.
JSEncrypt 基于 JSBN,而 JSBN 仅实现 PKCS#1 v1.5 填充类型 2(RFC 2313).这种填充的第二种类型引入了由于标记字节而在解密后被删除的随机字节.填充至少需要 11 个字节.
JSEncrypt is based on JSBN which in turn implements only PKCS#1 v1.5 padding type 2 (RFC 2313). The second type of this padding introduces random bytes that are removed after decryption because of marker bytes. At least 11 bytes are needed for the padding.
如果你想检查与其他实现的互操作性,你需要做一个完整的加密-解密循环,并确保你得到相同的明文.
If you want to check the interoperability with other implementations, you need to do a full encryption-decryption cycle and make sure that you get the same plaintext back.
请注意,现在不应再使用 PKCS#1 v1.5 填充,而首选 PKCS#1 v.2 OAEP,它也是随机的.
Note that nowadays, PKCS#1 v1.5 padding shouldn't be used anymore and PKCS#1 v.2 OAEP is preferred which is also randomized.
这篇关于JSEncrypt 每次为相同的消息和公钥生成不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!