我有模数和私有指数.如何构建RSA私钥并签名消息?

Max*_*xim 7 python cryptography rsa pycrypto

我是密码学和pycrypto的新手.

我有模数n和私有指数d.根据我在阅读一些文档后的理解,私钥n和组成d.

我需要签署一条消息,我无法弄清楚如何使用它pycrypto.RSA.construct()方法接受元组.但我必须另外为e这种方法提供公共指数(我没有).

所以这是我的问题.我是否必须以e某种方式进行计算才能签署消息?

似乎我应该能够通过使用nd(构成私钥)来签署消息.我对么?我可以这样做pycrypto吗?

提前致谢.

mat*_*ata 4

实际上,为了解密用公钥加密的消息,拥有私有指数就足够了。

这也意味着您可以对消息进行签名,因为签名基本上只是用私钥*解密*加密明文,当使用公钥*加密*加密时将再次给出明文。通常,您之前会对明文使用哈希摘要并签名......

无法仅使用ndwith解密消息的原因pyrcypto是,它在消息解密过程中执行了致盲步骤,其中涉及公共指数,但解密实际上并不需要。

但通过使用一些对私有 API 的调用,可以绕过此步骤。

因此这应该有效:

from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long, long_to_bytes

full = RSA.generate(2048)

# construct key using only n and d
try:
    # pycrypto >=2.5, only tested with _slowmath
    impl = RSA.RSAImplementation(use_fast_math=False)
    partial = impl.construct((full.n, 0L))
    partial.key.d = full.d
except TypeError:
    # pycrypto <=2.4.1
    partial = RSA.construct((full.n, 0L, full.d))   



pub = full.publickey()

# create message with padding
# http://en.wikipedia.org/wiki/RSA_%28algorithm%29#Padding_schemes
cleartext = ...

signature = partial.sign(cleartext, None)

print "validating message: ", pub.verify(cleartext, signature)


message = pub.encrypt(cleartext, None)

# bypassing the blinding step on decrypt
enc_msg=map(bytes_to_long, message)
dec_msg = map(partial.key._decrypt, enc_msg)

print "decrypting: "
for m in dec_msg:
    print long_to_bytes(m)
Run Code Online (Sandbox Code Playgroud)

  • 任何在没有填充的情况下完成 RSA 签名的代码(如这段代码)都是“死的”“错误的”,无论它是否有效。 (4认同)
  • @mike-pennington 是的,这个例子是完全错误的。首先,使用 RSA 而不进行填充(您应该自己创建它或使用 [PKCS#1 模块](https://www.dlitz.net/software/pycrypto/api/current/Crypto.Signature.PKCS1_v1_5-module。 html))。其次,对于 DSA 和 ElGamal,K 选择不正确。 (2认同)