M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier

Matthias Güntert MatzeGuentert at gmx.de
Tue Aug 4 18:51:39 CEST 2009


I am trying to add the extensions "subjectKeyIdentifier" and
"authorityKeyIdentifier" to a x509v3 certificate. 

Regarding rfc5280, section the key identifier is composed of the
160-bit SHA-1 hash of the BIT STRING subjectPublicKey


I don't know how or which function to use from EVP.PKey() to compose a
fingerprint from the public key, as you can see below I was playing
around with some functions, which simply returned nonsense (at least for

I would be happy if someone could provide some example code on how to
generate a fingerprint from the public key.

"print keyp.final()" nor "print keyp.sign_final() on the last line does
return anything... 
from M2Crypto import X509, m2, RSA, EVP
from config import *

import os.path

class Keypair(object):
    def __init__(self):
        self.config = Config()
        self.keypair = EVP.PKey()
    def create_keypair(self, key_size=1024):
        # generate an RSA key pair
        # OpenSSL book page 232
        # second argument should be a constant RSA_F4 or RSA_3 
        rsa_key_pair = RSA.gen_key(key_size, m2.RSA_F4)

        # check if RSA key pair is usable 
        # OpenSSL book page 232
        if rsa_key_pair.check_key() != 1:
            print 'error while generating key!'
        # EVP object which can hold either a DSA or an RSA object
        # OpenSSL book page 236
        evp_key_container = EVP.PKey()
        self.keypair = evp_key_container
    def save_keypair(self, filename):
        if not os.path.exists(filename):
            self.keypair.save_key(filename, None)
            print "error in save_keypair(): cannot save key, it already
    def load_keypair(self, filename):
            self.keypair = EVP.load_key(filename)
        except TypeError:
            print "error in load_keypair(): maybe file does not exist?" 
    def get_keypair(self):
        return self.keypair
    def get_public_key(self):
        return self.keypair.pkey
    def print_keypair(self):
        print self.keypair.as_pem(None)

if __name__ == "__main__":
    keypair = Keypair() 
    # keypair.save_keypair("test.keys")
    keyp = keypair.get_keypair()
    print keyp.final()
    print keyp.sign_final()

And this maybe some OT question but how can I use OpenSSL to generate
some fingerprint for testing and comparison purpose?

For example I have got a certificate client.crt and the keys client.key

$ openssl x509 -noout -text -in client.crt 
X509v3 Subject Key Identifier: 
X509v3 Authority Key Identifier: 

But openssl provides me different fingerprint... so whats wrong here?

$ openssl rsa -pubout -in client_1.key | openssl sha1 -c
writing RSA key

More information about the Python-list mailing list