简体   繁体   中英

PyOpenSSL throws error loading a certificate

I have the following code

key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 1024)
cert = OpenSSL.crypto.X509()
cert.set_pubkey(key)
cert.sign(key, 'sha1')
public_key =  OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
cert2 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, public_key)

the last line throws the following error, that is strange because nowhere I'm uding ASN1

OpenSSL.crypto.Error: [('asn1 encoding routines', 'ASN1_get_object', 'too long'), ('asn1 encoding routines', 'ASN1_CHECK_TLEN', 'bad object header'), ('asn1 encoding routines', 'ASN1_ITEM_EX_D2I', 'nested asn1 error'), ('asn1 encoding routines', 'ASN1_TEMPLATE_NOEXP_D2I', 'nested asn1 error'), ('asn1 encoding routines', 'ASN1_TEMPLATE_NOEXP_D2I', 'nested asn1 error'), ('asn1 encoding routines', 'ASN1_TEMPLATE_NOEXP_D2I', 'nested asn1 error'), ('PEM routines', 'PEM_ASN1_read_bio', 'ASN1 lib')]

this is the content of public_key

-----BEGIN CERTIFICATE-----
MIIBVDCBvgIBADANBgkqhkiG9w0BAQUFADAAMAQfAB8AMAAwgZ8wDQYJKoZIhvcN
AQEBBQADgY0AMIGJAoGBALKnfGRn5ajhcUJTs4PfwBfmjkpaDNeeRJfg8PmFRVFC
nZZPJTQoqrEAWnpGSHP1KWwiRcA7iFOIGe5lOj+vficIxGcNNv6n/OxBKLEeFYkb
+GoLyALEFcBPToe0KSHIcRwZcx6wg0kvtBCzTn1rA195u/tiuZfhza7ho7Se9g+X
AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEArhzT6wsfV5e2JetlZ7erOj0gkG046kow
B2wqmUvvQIxtZX+RYQBJvxlaaSJTSKjzjSafXIraemsPkkej9C9OudU54gfArvSK
UgSfkg4yABNUIWiSjEGdzFAoqmpPhKFXDoeW3SvqQdu+EZD/MF+AxmXufLADYGch
1Ga3c2SkOj8=
-----END CERTIFICATE-----

What causes it?

You're actually producing an invalid certificate with dump_certificate . Openssl should error out, or pyopenssl should check it, but either way - it's a bug.

This is just a guess, but likely it fails because of some required fields missing: serial number, validity, subject, issuer. Try setting those.

If you have time, report this snippet as a bug to pyopenssl too - you should never get bad PEM from it in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM