在python 3.6中使用pycryptodome或密码学。如何实现?

问题描述 投票:0回答:1

想象以下消息:

“这是给已签名的消息”

我需要在Python 3.6中使用以下标准,使用“ pycryptodome”或“ cryptography”对示例消息进行签名:

  • 格式:x.509;
  • 字符集:UTF-8;
  • 编码:Base64;
  • PKCS1 v1.5;
  • 大小:1024位;
  • 消息格式:SHA-1;

我具有必需的“ privatekey.pem”,但我不知道如何在pycryptodome或密码术中进行。

更新:我已经找到了此示例代码,但仍然不知道这是否是根据原始消息中定义的标准来实现我所需要的正确方法。示例代码(用于pycryptodome):

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA1
import base64
from base64 import b64encode, b64decode

key = open('privatekey.pem', "r").read()
rsakey = RSA.importKey(key)
signer = PKCS1_v1_5.new(rsakey)
digest = SHA1.new()
data = 'This the message to be signed'
digest.update(b64decode(data))
sign = signer.sign(digest)
doc = base64.b64encode(sign)
print(doc)

[我看到我得到了172个字符的签名哈希,但是需要专业建议才能知道这是否符合我描述的标准,以及这样做是否正确。

cryptography sign pycrypto pycryptodome
1个回答
2
投票

这里是一个代码片段,改编自applicable documentation page

from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA1
from Crypto.PublicKey import RSA
from base64 import b64encode

message = 'This the message to be signed'
key = RSA.import_key(open('private_key.der').read())
h = SHA1.new(message)
signature = pkcs1_15.new(key).sign(h)
print(b64encode(signature))
© www.soinside.com 2019 - 2024. All rights reserved.