Search code examples
javacryptographybouncycastle

Get PublicKey from key bytes not knowing the key algorithm


I have a byte array containing an encoded public key. I don't know the key algorithm. And I want to get the PublicKey object.

What I have got is:

import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PublicKeyFactory;

AsymmetricKeyParameter keyParameters = PublicKeyFactory.createKey(keyBytes);

The keyParameters class can be RSAKeyParameters, ECPublicKeyParameters, ... so now I can know the key algorithm.

And then:

KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
PublicKey publicKey = keyFactory.generatePublic(keySpec);

But I don't know if there's a more direct way to get the PublicKey. I mean, is there a direct way to get PublicKey from key bytes without the need to get first AsymmetricKeyParameter (and without the need to manually decode the key bytes) ?


Solution

  • Here is a direct way (using Bouncy Castle API):

    public PublicKey publicKeyParse(byte[] publicKeyBytes) {
                InputStream pgpIn = PGPUtil.getDecoderStream(new ByteArrayInputStream(publicKeyBytes));
                PGPObjectFactory pgpFact = new PGPObjectFactory(pgpIn, new JcaKeyFingerprintCalculator());
                PGPPublicKeyRing pgpSecRing = (PGPPublicKeyRing) pgpFact.nextObject();
                PGPPublicKey publicKey = pgpSecRing.getPublicKey();
                JcaPGPKeyConverter converter = new JcaPGPKeyConverter();
                Provider bcProvider = new BouncyCastleProvider();
                converter.setProvider(bcProvider);
                return converter.getPublicKey(publicKey);
        }