使用PKCS1-V1_5(JavaScript)加密RSA



我想使用PKCS1-1.5填充的RSA格式使用公共密钥对密码进行加密。目前,我尝试从https://github.com/digitalbazaar/forge使用forge库。解决方案的一部分使用Tom Wu的BigInteger()

modulus = new forge.jsbn.BigInteger(modulus,16);
exponent =  new forge.jsbn.BigInteger(exponent, 16);
var text = "Password";
var rsa = forge.pki.rsa;
var publicKey = rsa.setPublicKey(modulus, exponent);
var encryptedData = publicKey.encrypt(text, 'RSAES-PKCS1-V1_5');

提供的指数-10001似乎在BigInteger()中正确解析了单个项目数组-65537。

我得到了奇怪的 BigInteger()结果:模量屏幕截图

因此,在代码稍后创建的RSA Keypair是错误的。谁能将我指向正确的方向?更令人沮丧的是,我有工作。(我知道JS密码加密的问题/风险)。

update

这是工作python脚本:

import binascii
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
def assymmetric_encrypt(val, public_key):
     modulusDecoded = long(public_key["n"], 16)
     exponentDecoded = long(public_key["e"], 16)
     keyPub = RSA.construct((modulusDecoded, exponentDecoded))
     print(keyPub)
     # Generate a cypher using the PKCS1.5 standard
     cipher = PKCS1_v1_5.new(keyPub)
     return cipher.encrypt(val)
# Encrypt the password used to login
encryptedPassword = assymmetric_encrypt(password_input,public_key)

看来JS应该执行相同的操作,但是在两个脚本中提供相同的模量指数时,加密密码是不同的(看起来相似但不相等)

更新:有趣的是,如果我运行带有硬编码的N,E和密码的JS脚本,我每次都会获得相同的加密数据。当我对Python脚本做同样的事情时,我总是会得到不同的结果。.

更新2:问题位于完全不同的地方。多亏了Maarten Bodewes的评论,事实证明,填充库被打破了(每次都没有生成新的字符串)。我将Forger lib更改为JSencrypt,它效果很好。浏览PEM文件,但这可能在将来改变以获得更好的性能:

var encrypt = new JSEncrypt();
encrypt.setPublicKey(pem);
var encrypted_jeencrypt= encrypt.encrypt(password);
var encrypted_jeencrypt_hex = base64toHEX(encrypted_jeencrypt);

我相信您的构建方式是正确的。问题可能是由于您使用字符串来加密,而Forge需要缓冲区。尝试以下操作:

var buf = forge.util.createBuffer(text, 'utf8');
var encryptedData = publicKey.encrypt(buf, 'RSAES-PKCS1-V1_5');

如果您要使用RSA加密来发送密码,我建议您通过SSL/TLS频道使用更安全的RSA-OAEPRSA_PKCS1-V1_5RSA-OAEP是非确定性的,每次都会生成不同的密文。正确比较消息是否正确的方法是解密

最新更新