Signing files/file objects using python and pyopenssl
Question: 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 ?


Answer: 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](https://en.wikipedia.org/wiki/Cryptographic_Message_Syntax) (CMS)
which is supported by
[ctypescrypto](https://pypi.python.org/pypi/ctypescrypto). [This
article](http://www.cryptosys.net/pki/manpki/pki_signeddata.html) will
introduce the SignedData content type, which I think is what you are really
after.

