4

I am trying to encrypt a string using bouncy castle. The library I am using to retrieve the public key for the encryption returns it as a java.security.PublicKey object. How do I convert it into a PGPPublicKey object so that I can use it to encrypt the file.

user2078217
  • 129
  • 2
  • 12
  • 2
    X.509 keys and OpenPGP keys can both rely on the same cryptographic principles, but have completely different formats. There's more to an OpenPGP key than just the RSA numbers. Generally, you should never need to convert them, and usually you'll be trying to do things more complicated than required. If you need OpenPGP keys and encryption, generate/read them through BouncyCastle. If you need X.5009 keys and encryption, use the standard Java libraries. – Jens Erat May 12 '16 at 07:42
  • The keys have been generated using gpg. However the source that we use to store the keys returns them as a java.security.PublicKey object. I know that whenever I do key.getEncoded() I will be getting the byte array representation of the key itself. However all the methods that I know to create the key require getting them through the keyrings. Is it possible to create a PGPPublicKey object directly using a byte array? – user2078217 May 12 '16 at 08:37
  • You can read up on how OpenPGP keys are formed in [RFC 4880](https://tools.ietf.org/html/rfc4880). For recreation of the OpenPGP key, you at least also need the key creation timestamp. I'm not really used to either the Java API nor BouncyCastle, so I won't be able to help you out with details. – Jens Erat May 12 '16 at 08:46
  • 1
    You wold need to change the way you store the keys to something that preserves the OpenPGP key completely. – Eugene Mayevski 'Callback May 12 '16 at 11:30

1 Answers1

0

You can convert the key using Bouncy Castle JcaPGPKeyConverter.getPGPPublicKey(int algorithm, PublicKey pubKey, Date time)

Note: the time passed in affects the value of the key's keyID, so you probably only want to do this once for a JCA key, or make sure you keep track of the time you used.

See https://borelly.net/cb/docs/javaBC-1.4.8/pg/org/bouncycastle/openpgp/operator/jcajce/JcaPGPKeyConverter.html

Sergey
  • 3,253
  • 2
  • 33
  • 55