Friday 18 February 2011

openssl_sign in python

You need to sign something with private RSA key. You have some documentation or make your google search about subject.  And all excamples are with PHP function openssl_sign.
But we don't eat PHP anymore. So let's translate few lines PHP into something better, like Python.


If you see this:
$data = "Beeeeer is really good.. hic...";

$fp = fopen("private.key", "r");
$priv_key = fread($fp, 8192);
fclose($fp);

$binary_signature = "";

openssl_sign( $data,
              $binary_signature,
              $priv_key,
              OPENSSL_ALGO_SHA1
             );

echo $binary_signature;
echo "\n";
Read it like this:
from M2Crypto import EVP
def openssl_sign(data, priv_key):
    key.sign_init()
    key.sign_update(data)
    return key.sign_final()
    
data = "Beeeeer is really good.. hic..."
filename = 'private.key'
key = EVP.load_key(filename)
binary_signature = openssl_sign(data, key)
print binary_signature

2 comments:

  1. Thanks, just the info I needed! Small bug, the parameter to openssl_sign should be named 'key' instead of 'priv_key'.

    ReplyDelete
  2. This code is not works for me, but I find some else solution:
    import M2Crypto, hashlib
    data = "Beeeeer is really good.. hic..."
    filename = 'private.key'
    rsa = M2Crypto.RSA.load_key(filename)
    digest = hashlib.sha1(data.encode('utf-8')).digest()
    binary_signature = rsa.sign(digest)

    ReplyDelete