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 ?