How to get PublicKey from AsymmetricCipherKeyPair and not public encryption options?

I am creating a key pair on the platform using Bouncy Castle .

SecureRandom random = new SecureRandom();

ECKeyPairGenerator pGen = new ECKeyPairGenerator();

ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params,random);

pGen.init(genParam);

AsymmetricCipherKeyPair pair = pGen.generateKeyPair();

It pairhas a type here AsymmetricCipherKeyPair. And I need to create an X509V1Certificate on the server using this pair. But the X509Certificate setPublicKey(PublicKey pubkey)only accepts type objects PublicKey. Therefore, I need to get PublicKeyfrom AsymmetricCipherKeyPairon the server. But I get ECPublicKeyParametersthat which is not accepted in the method setPublicKey.

So my requirement here is to get PublicKeyfrom AsymmetricCipherKeyPair.

+5
source share
1 answer

The easiest way is to use a BouncyCastle as a JavaCryptoProvider:

  • Create KeyPair

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC");
    ECGenParameterSpec ecsp = new ECGenParameterSpec(keyAlg);
    kpg.initialize(ecsp);
    KeyPair kp = kpg.generateKeyPair();
    
  • X509v1

    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=C3");
    Calendar c = Calendar.getInstance();
    c.add(Calendar.YEAR, 10);
    certGen.setSerialNumber(keyId);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(new Date());
    certGen.setNotAfter(c.getTime());
    certGen.setSubjectDN(dnName);                      
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256withECDSA");
    certGen.generate(keyPair.getPrivate(), "BC");
    
+3

All Articles