简体   繁体   中英

Why can't Bouncycastle's PEMReader read this M2Crypto-generated PEM?

I use the following Python code, using M2Crypto, to generate an RSA key pair in PEM format:

bio = BIO.MemoryBuffer()
key_pair = RSA.gen_key(1024, 65537)
key_pair.save_key_bio(bio, cipher=None)
return bio.read()

And the following Java code, using Bouncycastle, to try to read it:

String signPem = ...;
PEMReader pemReader = new PEMReader(new StringReader(signPem));
Object signingKey = pemReader.readObject();

The signPem string is the same as what bio.read() returned; no data that I can see is getting munged between the two programs; it's -----BEGIN RSA PRIVATE KEY-----\\n etc.

However, the readObject() call throws a ClassCastException:

java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence
    at org.bouncycastle.asn1.ASN1Object.fromByteArray(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readKeyPair(Unknown Source)
    at org.bouncycastle.openssl.PEMReader.readObject(Unknown Source)

So obviously BC misidentifies the data in the PEM is not a key pair for some reason - but why?

After taking a debugger to Bouncycastle, I have discovered the "cause", but it only puzzles me more; the cast is failing even though all types seem to be correct.

If A extends B extends C, why can I cast to A but get a ClassCastException casting to C?

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