We have one system written in Java that will write encrypted files that need to be decrypted by a Python system. I am trying to figure out what kind of keys I need that can be used by both Java and Python API's, and how to generate them. The plan is to use the public key in Java to encrypt the file, and the private key in Python to decrypt it.
I tried generating RSA keys with gpg --generate-key
and in an armor file get a file that looks like:
-----BEGIN PGP PRIVATE KEY BLOCK-----
... encoded key ...
-----END PGP PRIVATE KEY BLOCK-----
and create a public key from that which looks like:
-----BEGIN PGP PUBLIC KEY BLOCK-----
... encoded key ...
-----END PGP PUBLIC KEY BLOCK-----
I can parse the public key file with Bouncy Castle in Java with PGPUtil.getDecoderStream()
, getting a PGPPublicKeyRingCollection
and a PGPPublicKey
which can be converted to a java.security.PublicKey
.
On the Python side I have tried using both the cryptography.hazmat
and PyCrypto
api's but can't figure out how to import the private key file. When I try
from Crypto.PublicKey import RSA
RSA.importKey(open('/path/to/private/key/file').read())
I get RSA key format is not supported
.
I have been reading up on the different types of keys and algorithms but I thought that an ASCII file holding a key like this should work but there is obviously something I'm missing.
I also tried going the other way and generating a new key using PyCrypto
with something like:
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
f = open('/tmp/private.pem','wb')
f.write(key.exportKey('PEM'))
f.close()
f = open('/tmp/public.pem','wb')
f.write(key.publickey().exportKey('PEM'))
f.close
And then reading it via Bouncy Castle's API like this:
PemReader reader = new PemReader(new FileReader("/tmp/public.pem"));
Object publicKey = RSAPublicKey.getInstance(reader.readPemObject().getContent());
But that gives me:
java.lang.IllegalArgumentException: illegal object in getInstance: org.bouncycastle.asn1.DLSequence
at org.bouncycastle.asn1.ASN1Integer.getInstance(Unknown Source)
at org.bouncycastle.asn1.pkcs.RSAPublicKey.<init>(Unknown Source)
Bouncy Castle provides two RSAPublicKey
classes, I tried them both but got the same result.
It doesn't seem like it should be this hard so I am trying to figure out what I'm missing. Thanks for any help.