问题
I have the following code which works perfectly for signing strings. However, I now need to programatically sign and get a signature for a file in the same way as I would using OpenSSL on the commandline
e.g. openssl dgst -sha1 –sign key.pem -out sig1 file.tar
.
import OpenSSL
from OpenSSL import crypto
import base64
key_file = open("key.pem", "r")
key = key_file.read()
key_file.close()
password = "password"
if key.startswith('-----BEGIN '):
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key, password)
else:
pkey = crypto.load_pkcs12(key, password).get_privatekey()
print pkey
data = "data"
sign = OpenSSL.crypto.sign(pkey, data, "sha256")
print sign
data_base64 = base64.b64encode(sign)
print data_base64
If open a file and try to sign:
with open('file.tar', 'r') as the_file:
sign = OpenSSL.crypto.sign(pkey, the_file, "sha256")
the_file.write(sign)
the_file.close()
OpenSSL throws an error:
sign = OpenSSL.crypto.sign(pkey, the_file, "sha256")
TypeError: must be string or read-only buffer, not file
How can sign the file object ?
回答1:
The error states that you are passing an instance of file, when a string or read-only buffer was expected. Try replacing the_file with the_file.read().
Side note: if you are attempting to encrypt and/or sign files, take a look at Cryptographic Message Syntax (CMS) which is supported by ctypescrypto. This article will introduce the SignedData content type, which I think is what you are really after.
来源:https://stackoverflow.com/questions/37187980/signing-files-file-objects-using-python-and-pyopenssl