如何获取公钥字符串并将其转换为Pycryptodome键(Python)

时间:2017-06-01 00:31:09

标签: python python-3.x public-key-encryption pycryptodome

我有一把公钥,但是,我不知道如何把它变成Pycryptodome上的钥匙。我一直在使用这个代码,我发现here

keyDER = b64decode(key64)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct((seq[0], seq[1]))

print(keyPub.encrypt('test',"Unguessable"))

然而,使用key64作为PublicKey,我得到ValueError: Unexpected DER tag。在使用Pycryptodome的python 3.6中有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我们需要这些模块:

import os
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import pkcs1_15

我们有一个计划文本:

message = b'hello!'

从明文查找哈希:

h = SHA256.new(message)

生成随机密钥:

key = RSA.generate(1024, os.urandom)

创建签名:

signature = pkcs1_15.new(key).sign(h)

最后拿一张公钥:

pub_key = key.publickey()

check func将如下所示:

 def sign(message, pubkey, signature):
      h = SHA256.new(message)
      try:
          pkcs1_15.new(pubkey).verify(h, signature)
          print('Success!')
      except ValueError:
          print('Invalid signature!')