M2crypto Signature vs OpenSSL Signature

2019-08-05 15:38发布

问题:

I have a pair of ECDSA keys and using the following code, I am trying to compare the signatures for a 'hello' string computed using OpenSSL and M2Crypto library in python.

Here is the code:

import subprocess
from hashlib import sha256

public_key_filename = 'ca_pu.pem'
private_key_filename = 'ca_pr.pem'
signature_filename = 'signature'

sigoutput = open(signature_filename, 'w')

cmd = 'openssl dgst -sha256 -sign'.split()
cmd.append(private_key_filename)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=sigoutput)
p.stdin.write('hello')
x = p.communicate()[0]
p.stdin.close()


cmd = 'openssl dgst -sha256 -sign'.split()
cmd.append(private_key_filename)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write('hello')
x = p.communicate()[0]
p.stdin.close()

print "OpenSSL Stdout:", x.encode('hex_codec')

cmd = 'openssl dgst -sha256 -verify'.split()
cmd.append(public_key_filename)
cmd.append('-signature')
cmd.append(signature_filename)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write('hello')
x = p.communicate()[0]
p.stdin.close()

with open(signature_filename, 'rb') as f:
    signature = f.read()

print "OpenSSL Signaure file:", signature.encode('hex_codec')

from M2Crypto import EC

pkey = EC.load_pub_key(public_key_filename)
prkey = EC.load_key(private_key_filename)

dgst = sha256("hello").digest()

s = prkey.sign_dsa_asn1(dgst)
print "M2C Signature:", s.encode('hex_codec')
if pkey.verify_dsa_asn1(dgst,s):
    print "ok"

And here is the output:

OpenSSL Stdout: 30818702415efdc431f684fad778dc2d45997ab9433cf9a94a657f194b11d4b47a379ba4a208be12577245b8ce3bf8d6367f6fb5814e7000c5daa8aa5cb1e74e8940033416240242015f57e2329fe294b9693ead6bb911bdb7f8a3244dc05b36ac8016eb33721a3a6d7fc71972688c51e3b6b5ab3be3598aa1032ed715f7ca0d152eedb342322bfaae1b
OpenSSL Signaure file: 308188024200aabe47fa154f28f143df920135b000aa318bd37a7241bd6b735890d5d2b090cdc9c01ee152b681dc3b9c556fbfae26256d7c20b7a8e915bb9e8dc1355afd8cb29b02420178d780b6b7218dc88afbfc99c8a7ccab4303f70dd72a826009d9dd1ac0baccef56c8a1364edbb76ca294162790f4ca99a86478659cfb20332416a4a55324d333e7
M2C Signature: 30818702414362f629560d740248ce7a863a070a51720cb8a3f42a014b66798edabf00df1e7cb8c7a4c1dbf6d9a3c4106ecd43b2acea713fe0b3246a04bb8484846b74c8af81024200e8d119921b07bf43d4ea5d30a0e8b29b56da27ca4b53045ce994059df9c5a66e1bc3d07b08ac1122d18afe0602493dce9004a9695f57a8ca482c095d4f66d0bb9d
ok

I am wondering why the signatures are all different. Any help is much appreciated.

回答1:

After some digging, it turns out that the signatures are different using DSA key and algorithm, due to having a random k when the signature is created.

I just post that to save you all some time in case you are having a same question.

For more info, checkout this link: https://security.stackexchange.com/questions/46939/dsa-generates-different-signatures-with-the-same-data