Search code examples
pkcs#11pyopensslecdsa

Verify ECDSA signature from PyKCS11


I have a python program which uses PyKCS11, a python wrapper for pkcs11 interface. I can sign data with a ECC private key (Mechanism CKM_ECDSA) that is stored on a HSM and that is accessed by PyKCS11.

What I now want is to verify with openssl the ECDSA signature by the corresponding public key. This public key is contained in a x509 (NewCert.pem) which was created out of the private key in the HSM.

I tested many ways to verify the signature properly, but I didn't succeed.

openssl dgst -ecdsa-with-SHA1 -verify <(openssl x509 -noout -pubkey -in NewCert.pem) -signature <(cat sign | base64 -d) file

The file 'signature' contains the base64 encoded signature. And the file 'file' the plain data.

Thank you


Solution

  • Finally I found a solution for my problem.

    I) The signature output of PyKCS11 is the concatenation of the r and s value of the ECDSA signature. It is not formatted in ASN1 style. This was the first problem why verification with openssl is not possible, because the latter requires this format.

    II) So I wrote a function that formats the PyKCS11 output to ASN1 conformity and saves the binary signature output to a file.

    III) In order to use hashing functions you first have to hash the data or the file to be signed. This can be done in Python with the command digest() of hashlib. After this you give this binary hash of the data as input to PyKCS11 and create the signature.

    IV) Verification of the hashed ECDSA signature can be done with the following command in openssl:

    openssl dgst -sha384 -verify pubkey -signature file.sign file
    

    Make sure that pubkey is the EC public key from the corresponding x509 certificate (not the x509 itself). And file.sign means to be the binary file which contains the ECDSA signature that represents the binary hash of the original data (see step III).

    Hope this helps for somebody else.