Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signing data using openssl with python

I am currently signing data using next opensll command:

openssl dgst -sign key.pem -sha256 -out signature.sig data.txt

How can I achieve this with Python?

like image 418
Maxim Kravchenko Avatar asked Sep 10 '15 15:09

Maxim Kravchenko


People also ask

Can I use OpenSSL in Python?

Currently Python versions 3.6 to 3.9 are compatible with OpenSSL 1.0.


1 Answers

I found answer here(http://nullege.com/ and https://pyopenssl.readthedocs.org/en/stable/api/crypto.html):

import OpenSSL
from OpenSSL import crypto
import base64
key_file = open("C:\my.pem", "r")
key = key_file.read()
key_file.close()
password = "password of prk"

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
like image 86
Maxim Kravchenko Avatar answered Oct 03 '22 22:10

Maxim Kravchenko