Pycrypto:如何查看原始RSA签名数据? [英] Pycrypto: How to view raw RSA signature data?

查看:44
本文介绍了Pycrypto:如何查看原始RSA签名数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用使用带有私钥的原始RSA签署有效负载的服务.可以使用以下方法有效地生成数据:

I'm working with a service that uses raw RSA with a private key to sign a payload. The data is effectively produced using:

openssl rsautl -inkey private_key.pem -raw -sign

(也是用私钥加密的结果)

(Also, the result of encrypting with the private key)

不幸的是,在Pycrypto中,相应的 .verify()方法仅采用一个参数来验证数据是否返回true或false.

Unfortunately, in Pycrypto the corresponding .verify() method only takes an argument to verify the data against to return true or false.

在openssl中,可以使用以下任一方法来实现:

In openssl, this could be achieved with one of the following:

# Private key based
openssl rsautl -inkey private_key.pem -raw -verify
# Public key based
openssl rsautl -inkey public_key.pem -pubin -raw -verify

如何在Pycrypto中实现相同的功能?

How can I achieve the same functionality in Pycrypto?

(我了解原始RSA的风险.已实施了自定义填充机制来减轻其中的某些风险.不幸的是,无法更改当前的实现)

(I understand the risks of raw RSA. A custom padding mechanism has been implemented to mitigate some of those risks. Unfortunately, it's not possible to change the current implementation)

推荐答案

深入研究 .verify()方法,可以在将Pycrypto与给定的所需签名进行比较之前找到Pycrypto如何构建验证签名.

Delving into the .verify() method, one can find how Pycrypto builds the verification signature before comparing it to the given required signature.

它本质上使用Python的 pow()方法以及密钥的公用( e )和密钥的模数( n ).您首先需要将秘密消息打包为一个(长)整数,然后将结果转换回字节.幸运的是,Pycrypto提供了您所需的一切.

It essentially uses Python's pow() method with the key's public (e) and the key's modulus (n). You will first need to pack the secret message into a (long) integer and then convert the result back to bytes. Fortunately, Pycrypto provides everything you need.

from Crypto.PublicKey import RSA
from Crypto.Util import number

key = RSA.importKey(private_key_str, key_password_str)

# The message must be packed as a long first.
secret_message_long = number.bytes_to_long(secret_message_bytes)
# The magic!        
verify_long = pow(encrypted_session_key_long, key.e, key.n)
# and back to bytes
verify_bytes = number.long_to_bytes(result_long)

# Convert message back to a str (Unicode str in Py2).
# Replace 'utf-8' with the correct encoding for *your* message!!!!!
verify_str = verify_bytes.decode('utf-8')

这篇关于Pycrypto:如何查看原始RSA签名数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆