gpt4 book ai didi

python - 无 M2Crypto 的非分离 PKCS#7 SHA1+RSA 签名

转载 作者:太空狗 更新时间:2023-10-30 01:21:20 25 4
gpt4 key购买 nike

我正在尝试在 python3 上创建一个非分离签名。我目前有使用 m2crypto 在 python2 上执行此操作的代码,但 m2crypto 不适用于 python3。

我一直在尝试 rsa、pycrypto 和 openssl,但还没找到方法。

这是等效的 OpenSSL 命令:

openssl smime -sign -signer $CRTFILE -inkey $KEYFILE -outformDER -nodetach

这是我无法用 rsa 模仿的 nodetach 选项, pyopensslpycrypto .

有人在 python3 上做过吗?我想尽可能避免使用 Popen+openssl。

最佳答案

如果您不介意进行一些较低级别的 OpenSSL 编程,看起来您可以使用 pyca/cryptography 实现此目的。你可以试一试:

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.bindings.openssl.binding import Binding

_lib = Binding.lib
_ffi = Binding.ffi

msg = "Hello, World!"

with open('key.pem', 'rb') as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(), None, default_backend())

with open('cert.pem', 'rb') as cert_file:
cert = x509.load_pem_x509_certificate(
cert_file.read(), default_backend())

bio_in = _lib.BIO_new_mem_buf(msg.encode('utf-8'), len(msg))
pkcs7 = _lib.PKCS7_sign(cert._x509, private_key._evp_pkey, _ffi.NULL, bio_in, 0)

bio_out=_lib.BIO_new(_lib.BIO_s_mem())
_lib.PEM_write_bio_PKCS7(bio_out, pkcs7)

result_buffer = _ffi.new('char**')
buffer_length = _lib.BIO_get_mem_data(bio_out, result_buffer)
sout = _ffi.buffer(result_buffer[0], buffer_length)[:]

print(sout.decode('utf-8'))

此脚本仅用于说明目的,可能有更好的方法来执行此操作。这种方法基本上模仿了您的 openssl smime 命令。

如果您确实想沿着这条路走下去,您将不得不仔细研究内存管理并在完成后释放一些东西。 this stuff is called hazmat是有原因的...

关于python - 无 M2Crypto 的非分离 PKCS#7 SHA1+RSA 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32020356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com