Java Code Examples for java.security.KeyPair#getPrivate()

The following examples show how to use java.security.KeyPair#getPrivate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenerateJWTTest.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 6 votes vote down vote up
@Test
public void generateJWT(TestReporter reporter) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    Assumptions.assumeTrue(kpg.getAlgorithm().equals("RSA"));
    kpg.initialize(2048);
    reporter.publishEntry("Created RSA key pair generator of size 2048");
    KeyPair keyPair = kpg.generateKeyPair();
    reporter.publishEntry("Created RSA key pair");
    Assumptions.assumeTrue(keyPair != null, "KeyPair is not null");
    PublicKey publicKey = keyPair.getPublic();
    reporter.publishEntry("RSA.publicKey", publicKey.toString());
    PrivateKey privateKey = keyPair.getPrivate();
    reporter.publishEntry("RSA.privateKey", privateKey.toString());

    assertAll("GenerateJWTTest",
        () -> assertEquals("X.509", publicKey.getFormat()),
        () -> assertEquals("PKCS#8", privateKey.getFormat()),
        () -> assertEquals("RSA", publicKey.getAlgorithm()),
        () -> assertEquals("RSA", privateKey.getAlgorithm())
    );
}
 
Example 2
Source File: GenerateKeysExample.java    From jlibra with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("Ed25519", "BC");
    KeyPair keyPair = kpGen.generateKeyPair();

    BCEdDSAPrivateKey privateKey = (BCEdDSAPrivateKey) keyPair.getPrivate();

    BCEdDSAPublicKey publicKey = (BCEdDSAPublicKey) keyPair.getPublic();

    AuthenticationKey authenticationKey = AuthenticationKey.fromPublicKey(publicKey);
    logger.info("Libra address: {}",
            AccountAddress.fromAuthenticationKey(authenticationKey));
    logger.info("Authentication key: {}", authenticationKey);
    logger.info("Public key: {}", ByteArray.from(publicKey.getEncoded()));
    logger.info("Private key: {}", ByteArray.from(privateKey.getEncoded()));
}
 
Example 3
Source File: EncrypRSA.java    From ProjectStudy with MIT License 6 votes vote down vote up
/**
 * 测试
 *
 * @param args
 * @return void
 * @author Wang926454
 * @date 2018/8/21 15:13
 */
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    EncrypRSA rsa = new EncrypRSA();
    String msg = "dhdslkaflkf";
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // 初始化密钥对生成器,密钥大小为1024位
    keyPairGen.initialize(1024);
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    // 得到私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    // 得到公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // 用公钥加密
    byte[] srcBytes = msg.getBytes();
    byte[] resultBytes = rsa.encrypt(publicKey, srcBytes);

    // 用私钥解密
    byte[] decBytes = rsa.decrypt(privateKey, resultBytes);

    System.out.println("明文是:" + msg);
    System.out.println("加密后是:" + new String(resultBytes));
    System.out.println("解密后是:" + new String(decBytes));
}
 
Example 4
Source File: HTTPJwtAuthenticatorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testES512() throws Exception {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    keyGen.initialize(571);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    String jwsToken = Jwts.builder().setSubject("Leonard McCoy").signWith(SignatureAlgorithm.ES512, priv).compact();
    Settings settings = Settings.builder().put("signing_key", BaseEncoding.base64().encode(pub.getEncoded())).build();

    HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null);
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", "Bearer "+jwsToken);

    AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null);
    Assert.assertNotNull(creds);
    Assert.assertEquals("Leonard McCoy", creds.getUsername());
    Assert.assertEquals(0, creds.getBackendRoles().size());
}
 
Example 5
Source File: HTTPJwtAuthenticatorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testRS256() throws Exception {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    String jwsToken = Jwts.builder().setSubject("Leonard McCoy").signWith(SignatureAlgorithm.RS256, priv).compact();
    Settings settings = Settings.builder().put("signing_key", "-----BEGIN PUBLIC KEY-----\n"+BaseEncoding.base64().encode(pub.getEncoded())+"-----END PUBLIC KEY-----").build();

    HTTPJwtAuthenticator jwtAuth = new HTTPJwtAuthenticator(settings, null);
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", "Bearer "+jwsToken);

    AuthCredentials creds = jwtAuth.extractCredentials(new FakeRestRequest(headers, new HashMap<String, String>()), null);
    Assert.assertNotNull(creds);
    Assert.assertEquals("Leonard McCoy", creds.getUsername());
    Assert.assertEquals(0, creds.getBackendRoles().size());
}
 
Example 6
Source File: FinalizeHalf.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void test(String algo, Provider provider, boolean priv,
        Consumer<Key> method) throws Exception {
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance(algo, provider);
    } catch (NoSuchAlgorithmException nsae) {
        return;
    }

    System.out.println("Checking " + provider.getName() + ", " + algo);

    KeyPair pair = generator.generateKeyPair();
    Key key = priv ? pair.getPrivate() : pair.getPublic();

    pair = null;
    for (int i = 0; i < 32; ++i) {
        System.gc();
    }

    try {
        method.accept(key);
    } catch (ProviderException pe) {
        failures++;
    }
}
 
Example 7
Source File: KeySizeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param kpair test key pair.
 * @return true if test passed. false if test failed.
 */
private static boolean sizeTest(KeyPair kpair) {
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
        if (!priv.getModulus().equals(pub.getModulus())) {
            System.err.println("priv.getModulus() = " + priv.getModulus());
            System.err.println("pub.getModulus() = " + pub.getModulus());
            return false;
        }
    }
    return true;
}
 
Example 8
Source File: ECDHKeyExchange.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
ECDHEPossession(ECDHECredentials credentials, SecureRandom random) {
    ECParameterSpec params = credentials.popPublicKey.getParams();
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        kpg.initialize(params, random);
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        publicKey = (ECPublicKey)kp.getPublic();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(
            "Could not generate ECDH keypair", e);
    }

    this.namedGroup = credentials.namedGroup;
}
 
Example 9
Source File: KeySizeTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param kpair test key pair.
 * @return true if test passed. false if test failed.
 */
private static boolean sizeTest(KeyPair kpair) {
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
        if (!priv.getModulus().equals(pub.getModulus())) {
            System.err.println("priv.getModulus() = " + priv.getModulus());
            System.err.println("pub.getModulus() = " + pub.getModulus());
            return false;
        }
    }
    return true;
}
 
Example 10
Source File: Correctness.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }
 
Example 11
Source File: private_key.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
private private_key(KeyPair ecKey) {
    BCECPrivateKey privateKey = (BCECPrivateKey) ecKey.getPrivate();
    byte[] privateKeyGenerate = privateKey.getD().toByteArray();
    if (privateKeyGenerate.length == 33) {
        System.arraycopy(privateKeyGenerate, 1, key_data, 0, key_data.length);
    } else {
        System.arraycopy(privateKeyGenerate, 0, key_data, 0, key_data.length);
    }
}
 
Example 12
Source File: TestOzoneDelegationTokenSecretManager.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to create certificate client.
 * */
private CertificateClient setupCertificateClient() throws Exception {
  KeyPair keyPair = KeyStoreTestUtil.generateKeyPair("RSA");
  X509Certificate cert = KeyStoreTestUtil
      .generateCertificate("CN=OzoneMaster", keyPair, 30, "SHA256withRSA");

  return new OMCertificateClient(securityConfig) {
    @Override
    public X509Certificate getCertificate() {
      return cert;
    }

    @Override
    public PrivateKey getPrivateKey() {
      return keyPair.getPrivate();
    }

    @Override
    public PublicKey getPublicKey() {
      return keyPair.getPublic();
    }

    @Override
    public X509Certificate getCertificate(String serialId) {
      return cert;
    }
  };
}
 
Example 13
Source File: RSAEncryptDecrypt.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        KeyPairGenerator generator =
            KeyPairGenerator.getInstance("RSA", "SunMSCAPI");

        KeyPair keyPair = generator.generateKeyPair();
        Key publicKey = keyPair.getPublic();
        Key privateKey = keyPair.getPrivate();

        Cipher cipher = null;

        try {
            cipher = Cipher.getInstance("RSA", "SunMSCAPI");

        } catch (GeneralSecurityException e) {
            System.out.println("Cipher not supported by provider, skipping...");
            return;
        }

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        displayBytes("Plaintext data:", PLAINTEXT);
        byte[] data = cipher.doFinal(PLAINTEXT);
        displayBytes("Encrypted data:", data);

        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        data = cipher.doFinal(data);
        displayBytes("Decrypted data:", data);
    }
 
Example 14
Source File: Offsets.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static Offsets init(String provider, String algorithm)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    // fill the cleartext data with random bytes
    byte[] cleartext = new byte[100];
    RandomFactory.getRandom().nextBytes(cleartext);

    // NONEwith requires input to be of 20 bytes
    int size = algorithm.contains("NONEwith") ? 20 : 100;

    // create signature instance
    Signature signature = Signature.getInstance(algorithm, provider);

    String keyAlgo;
    int keySize = 2048;
    if (algorithm.contains("RSA")) {
        keyAlgo = "RSA";
    } else if (algorithm.contains("ECDSA")) {
        keyAlgo = "EC";
        keySize = 256;
    } else if (algorithm.contains("DSA")) {
        keyAlgo = "DSA";
        if (algorithm.startsWith("SHAwith") ||
                algorithm.startsWith("SHA1with")) {
            keySize = 1024;
        }
    } else {
        throw new RuntimeException("Test doesn't support this signature "
                + "algorithm: " + algorithm);
    }

    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
    kpg.initialize(keySize);
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubkey = kp.getPublic();
    PrivateKey privkey = kp.getPrivate();

    return new Offsets(signature, pubkey, privkey, size, cleartext);
}
 
Example 15
Source File: RSACoder.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
private AsymmetricKeyPair doInitKey() throws NoSuchAlgorithmException, UnsupportedEncodingException {
    initProvider();
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(KEY_SIZE);
    KeyPair keyPair = keyPairGen.generateKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    AsymmetricKeyPair aKeyPair = AsymmetricKeyPairBuilder
            .withPublicKey(StringUtilsEx.encodeBase64String((publicKey.getEncoded())))
            .withPrivateKey(StringUtilsEx.encodeBase64String(privateKey.getEncoded())).build();

    return aKeyPair;
}
 
Example 16
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public KeyPair generatekeys() throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException, InvalidAlgorithmParameterException, InvalidKeyException, SignatureException {

        //generate ECDSA keypair
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", "BCFIPS");
        ECGenParameterSpec paramSpec = new ECGenParameterSpec(("secp256r1"));

        //initialize
        kpg.initialize(paramSpec, new SecureRandom());
        //generate
        KeyPair keyPair = kpg.generateKeyPair();
        Key priK = (PrivateKey) keyPair.getPrivate();
        return keyPair;
    }
 
Example 17
Source File: BouncyCastleSecurityProviderTool.java    From CapturePacket with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createServerCertificate(CertificateInfo certificateInfo,
                                                 X509Certificate caRootCertificate,
                                                 PrivateKey caPrivateKey,
                                                 KeyPair serverKeyPair,
                                                 String messageDigest) {
    // make sure certificateInfo contains all fields necessary to generate the certificate
    if (certificateInfo.getCommonName() == null) {
        throw new IllegalArgumentException("Must specify CN for server certificate");
    }

    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the subject for the new server certificate. when impersonating an upstream server, this should contain
    // the hostname of the server we are trying to impersonate in the CN field
    X500Name serverCertificateSubject = createX500NameForCertificate(certificateInfo);

    // get the algorithm that will be used to sign the new certificate, which is a combination of the message digest
    // and the digital signature from the CA's private key
    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, caPrivateKey);

    // get a ContentSigner with our CA private key that will be used to sign the new server certificate
    ContentSigner signer = getCertificateSigner(caPrivateKey, signatureAlgorithm);

    // generate a serial number for the new certificate. serial numbers only need to be unique within our
    // certification authority; a large random integer will satisfy that requirement.
    BigInteger serialNumber = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    // create the X509Certificate using Bouncy Castle. the BC X509CertificateHolder can be converted to a JCA X509Certificate.
    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(caRootCertificate,
                serialNumber,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                serverCertificateSubject,
                serverKeyPair.getPublic())
                .addExtension(Extension.subjectAlternativeName, false, getDomainNameSANsAsASN1Encodable(certificateInfo.getSubjectAlternativeNames()))
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(serverKeyPair.getPublic()))
                .addExtension(Extension.basicConstraints, false, new BasicConstraints(false))
                .build(signer);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating new server certificate", e);
    }

    // convert the Bouncy Castle certificate holder into a JCA X509Certificate
    X509Certificate serverCertificate = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(serverCertificate, serverKeyPair.getPrivate());
}
 
Example 18
Source File: ECDSAUtilsTest.java    From rhizobia_J with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
    public void sign() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        keyPairGenerator.initialize(160);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
        ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

        ECDSAUtils ecInstance = ECDSAUtils.getInstance(ecPrivateKey, ecPublicKey);

//        String priKeyPath = "/tmp/pri.key";
//        String pubKeyPath = "/tmp/pub.key";
//        ECDSAUtils ecInstance = ECDSAUtils.getInstance(priKeyPath, pubKeyPath);


        String plaintext = "123";

        byte[] sigintext = ecInstance.sign(plaintext);
        System.out.println(sigintext.toString());
        String signtRet = new BASE64Encoder().encode(sigintext);
        System.out.println("sign : " + signtRet);

        //验签
        byte[] verified = new BASE64Decoder().decodeBuffer(signtRet);
        boolean ifPass = ecInstance.verify(verified, plaintext);
        System.out.println("pass or not : " + ifPass);
        assertTrue(ifPass);

        plaintext = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";

        sigintext = ecInstance.sign(plaintext);
        System.out.println(sigintext.toString());
        signtRet = new BASE64Encoder().encode(sigintext);
        System.out.println("sign : " + signtRet);

        //验签
        verified = new BASE64Decoder().decodeBuffer(signtRet);
        ifPass = ecInstance.verify(verified, plaintext);
        System.out.println("pass or not : " + ifPass);
        assertTrue(ifPass);

    }
 
Example 19
Source File: XMLDSigWithSecMgr.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    System.setProperty("java.security.policy",
            System.getProperty("test.src", ".") + File.separator + "policy");
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 20
Source File: BouncyCastleSecurityProviderTool.java    From browserup-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public CertificateAndKey createCARootCertificate(CertificateInfo certificateInfo,
                                                 KeyPair keyPair,
                                                 String messageDigest) {
    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the X500Name that will be both the issuer and the subject of the new root certificate
    X500Name issuer = createX500NameForCertificate(certificateInfo);

    BigInteger serial = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    PublicKey rootCertificatePublicKey = keyPair.getPublic();

    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, keyPair.getPrivate());

    // this is a CA root certificate, so it is self-signed
    ContentSigner selfSigner = getCertificateSigner(keyPair.getPrivate(), signatureAlgorithm);

    ASN1EncodableVector extendedKeyUsages = new ASN1EncodableVector();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    extendedKeyUsages.add(KeyPurposeId.anyExtendedKeyUsage);

    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(
                issuer,
                serial,
                Date.from(certificateInfo.getNotBefore()),
                Date.from(certificateInfo.getNotAfter()),
                issuer,
                rootCertificatePublicKey)
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(rootCertificatePublicKey))
                .addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, false, new KeyUsage(
                        KeyUsage.keyCertSign
                                | KeyUsage.digitalSignature
                                | KeyUsage.keyEncipherment
                                | KeyUsage.dataEncipherment
                                | KeyUsage.cRLSign))
                .addExtension(Extension.extendedKeyUsage, false, new DERSequence(extendedKeyUsages))
                .build(selfSigner);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating root certificate", e);
    }

    // convert the Bouncy Castle X590CertificateHolder to a JCA cert
    X509Certificate cert = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(cert, keyPair.getPrivate());
}