1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.