使用pycrypto PKCS#7创建签名

时间:2013-04-29 17:00:26

标签: python pkcs#7

我正在查看PassBook的Apple文档,我需要:

  • 创建“清单文件的PKCS#7分离签名”。

我理想情况下喜欢用Python做这件事,我理想的是喜欢使用pycrypto来完成任务,麻烦的是,我在网上找不到任何关于如何做到这一点的示例代码,有很多像这样的代码:

from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA

message = 'To be encrypted'
h = SHA.new(message)

key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_v1_5.new(key)
ciphertext = cipher.encrypt(message+h.digest())

但对PKCS#7的细节不太了解,我不知道我需要做什么......

有没有人有任何想法?

由于

1 个答案:

答案 0 :(得分:1)

这对我有用,我正在尝试为NSDL签名一个字符串,

from OpenSSL import crypto
import base64
try:
    p12 = crypto.load_pkcs12(open("/DSCPFX.pfx", 'rb').read(), "XXXX")
    # print("p12 : ", p12)
    signcert = p12.get_certificate()
    pkey = p12.get_privatekey()

    text = "This is the text to be signed"
    bio_in = crypto._new_mem_buf(text.encode())
    PKCS7_NOSIGS = 0x4
    pkcs7 = crypto._lib.PKCS7_sign(signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS)
    bio_out = crypto._new_mem_buf()
    crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7)

    sigbytes = crypto._bio_to_string(bio_out)

    signed_data = base64.b64encode(sigbytes)
    return SUCCESS, signed_data
except Exception as err:
    print("Exception happens in sign_data and error is: ", err)
    return 0, str(err)