加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python密码术导出密钥到DER

发布时间:2020-12-17 17:36:49 所属栏目:Python 来源:网络整理
导读:过去使用PyCrypto时,我能够执行以下操作来生成RSA公钥的指纹: rsa_cipher = PKCS1_v1_5.new(RSA.importKey(pub_rsa_key))hashlib.sha1(rsa_cipher._key.exportKey("DER")).hexdigest() 没有PyCrypto,我该如何做到相同? 编辑 我在pub_rsa_key中提供的是.per

过去使用PyCrypto时,我能够执行以下操作来生成RSA公钥的指纹:

rsa_cipher = PKCS1_v1_5.new(RSA.importKey(pub_rsa_key))
hashlib.sha1(rsa_cipher._key.exportKey("DER")).hexdigest()

没有PyCrypto,我该如何做到相同?

编辑

我在pub_rsa_key中提供的是.perm文件的内容,即:

-----BEGIN PUBLIC KEY-----
MII...AB
-----END PUBLIC KEY-----

PyCrypto被认为是不安全的,并且不再维护,因此我改用Python的密码学,但是它似乎没有足够的功能.

>我在Python密码API中错过了类似的功能吗?
> PyCryptoDome是否有可能是值得(稳定,安全)的PyCrypto替代品,以用于实现此功能?
>如果以上都不是,可以通过自写功能以DER格式导出该密钥吗?

任何用于执行导出操作的文档或搜索字词都会有所帮助.

编辑2
马尔滕·博德威斯(Maarten Bodewes)的评论(谢谢)将我带到了一个我一直在寻找的地方.但是DER导出的结果不同:

# Python 3.7 using Cryptography
from cryptography.hazmat.primitives import serialization

with open('pub_key.perm','rb') as key_file: 
    public_key = serialization.load_pem_public_key(key_file.read(),backend=default_backend())

pub_der = public_key.public_bytes(encoding=serialization.Encoding.DER,format=serialization.PublicFormat.PKCS1)

print(sha1(pub_der).hexdigest())
# gives "d291c142648b7........c2f4676f4213203c4bd"

哪里

# Python 2.7 using PyCrypto
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

with open('pub_key.perm','r') as key_file:
    public_key = RSA.importKey(key_file.read())

pub_der = public_key.exportKey('DER')  # this assumes PKCS1 by default per the __doc__

print(sha1(pub_der).hexdigest())
# gives "bb070664079f5........64c97fcadbad847cce9"

这是从Py2升级到Py3的一种努力-请注意,两个示例使用不同的Python版本.编码可能在这里成为问题吗?

最佳答案
回答我的问题(已通过评论中提供的帮助解决了,再次感谢).

要实现我能够使用PyCrypto进行的操作:

# Python 2.7 using PyCrypto
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

with open('pub_key.perm','r') as key_file:
    public_key = RSA.importKey(key_file.read())

pub_der = public_key.exportKey('DER')  # this assumes PKCS1 by default per the __doc__

print(sha1(pub_der).hexdigest())
# gives "bb070664079f5........64c97fcadbad847cce9"

使用密码术,可以执行以下操作:

# Python 3.7 using Cryptography
from cryptography.hazmat.primitives import serialization

with open('pub_key.perm',backend=default_backend())

pub_der = public_key.public_bytes(
    encoding=serialization.Encoding.DER,format=serialization.PublicFormat.SubjectPublicKeyInfo,)

print(sha1(pub_der).hexdigest())
# gives "bb070664079f5........64c97fcadbad847cce9"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读