Python DER 的加密导出密钥

Python Cryptography export key to DER

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

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 的密码学,但它似乎没有足够的功能。

执行导出的任何文档或搜索词都会有所帮助。


编辑 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', '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.SubjectPublicKeyInfo,
)

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