Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:hudson.cli.Connection.java

public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
    KeyPair keyPair;
    PublicKey otherHalf;//w w  w.j  av a 2s. c o m

    if (side) {
        AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
        paramGen.init(keySize);

        KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
        dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
        keyPair = dh.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
    } else {
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
        keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
        keyPair = keyPairGen.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
    }

    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(otherHalf, true);

    return ka;
}

From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java

public PublicKey getPublicKey(int purpose) throws CATokenOfflineException {
    autoActivate();//from  www  .  j a  va 2s.  c o  m
    String keystring = this.keyStrings.getString(purpose);
    KeyPair keyPair = this.mKeys != null ? (KeyPair) this.mKeys.get(keystring) : null;
    if (keyPair == null) {
        String msg = intres.getLocalizedMessage("catoken.errornosuchkey", keystring, purpose);
        throw new CATokenOfflineException(msg);
    }
    return keyPair.getPublic();
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a CSR request.//from  w ww. ja v  a  2s.c  o m
 * 
 * @param alias
 * @param algorithm
 * @param signatureAlgorithm
 * @param keySize
 * @param params
 * @return
 * @throws Exception
 */
protected Pair<PKCS10CertificationRequest, PrivateKey> generateCSR(String alias, String algorithm,
        String signatureAlgorithm, int keySize, JsonValue params) throws Exception {

    // Construct the distinguished name
    StringBuilder sb = new StringBuilder();
    sb.append("CN=").append(params.get("CN").required().asString().replaceAll(",", "\\\\,"));
    sb.append(", OU=").append(params.get("OU").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", O=").append(params.get("O").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", L=").append(params.get("L").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", ST=").append(params.get("ST").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", C=").append(params.get("C").defaultTo("None").asString().replaceAll(",", "\\\\,"));

    // Create the principle subject name
    X509Principal subjectName = new X509Principal(sb.toString());

    //store.getStore().

    // Generate the key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Generate the certificate request
    PKCS10CertificationRequest cr = new PKCS10CertificationRequest(signatureAlgorithm, subjectName, publicKey,
            null, privateKey);

    // Store the private key to use when the signed cert is return and updated
    logger.debug("Storing private key with alias {}", alias);
    storeKeyPair(alias, keyPair);

    return Pair.of(cr, privateKey);
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createClass3RootCert(KeyPair keyPair, PrivateKey ppk, X509Certificate caCert)
        throws Exception {

    X500Name idn = CertificateUtil.getSubject(caCert);
    BigInteger sno = BigInteger.valueOf(5);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);
    X500Name sdn = X500NameUtil.createClass3RootPrincipal();
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);/*from www  . j a v a 2  s.c o m*/
    addAuthorityKID(certBuilder, caCert.getPublicKey());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(Boolean.TRUE));

    X509Certificate certificate = signCert(certBuilder, ppk);
    certificate.checkValidity(new Date());
    certificate.verify(caCert.getPublicKey());

    setPKCS9Info(certificate);

    return certificate;
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createClass1CaCert(KeyPair keyPair, PrivateKey ppk, X509Certificate caCert)
        throws Exception {

    X500Name idn = CertificateUtil.getSubject(caCert);
    BigInteger sno = BigInteger.valueOf(3);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);
    X500Name sdn = X500NameUtil.createClass1RootPrincipal();
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);//w w w. j  a v  a  2  s .c  om
    addAuthorityKID(certBuilder, caCert.getPublicKey());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3));
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));

    X509Certificate certificate = signCert(certBuilder, ppk);
    certificate.checkValidity(new Date());
    certificate.verify(caCert.getPublicKey());

    setPKCS9Info(certificate);

    return certificate;
}

From source file:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java

@Override
public KeyAndCertificate handleRequest(CertificateRequest request) throws CAException {
    KeyAndCertificate keyAndCertificate = null;

    try {//from w ww. ja  v a 2 s . c  o  m
        UserDataVOWS userData = new UserDataVOWS();

        userData.setEmail(request.getEmail());
        userData.setUsername(request.getEmail());
        userData.setPassword(requestHandlerSettings.getDefaultUserPassword());
        userData.setSubjectDN(subjectDNToString(request.getSubject()));
        userData.setSubjectAltName("rfc822Name=" + request.getEmail());
        userData.setEndEntityProfileName(requestHandlerSettings.getEndEntityProfileName());
        userData.setCaName(requestHandlerSettings.getCAName());
        userData.setCertificateProfileName(requestHandlerSettings.getCertificateProfileName());
        userData.setStatus(EJBCAConst.STATUS_NEW);
        userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED);

        if (logger.isDebugEnabled()) {
            StrBuilder sb = new StrBuilder();

            sb.append("UserDataVOWS: ").append("[Email: ").append(userData.getEmail())
                    .append(", DefaultUserPassword: ").append(userData.getPassword() != null ? "***" : "")
                    .append(", SubjectDN: ").append(userData.getSubjectDN()).append(", SubjectAltName: ")
                    .append(userData.getSubjectAltName()).append(", EndEntityProfileName: ")
                    .append(userData.getEndEntityProfileName()).append(", CaName: ")
                    .append(userData.getCaName()).append(", CertificateProfileName: ")
                    .append(userData.getCertificateProfileName()).append("]");

            logger.debug(sb.toString());
        }

        KeyPair keyPair = generateKeyPair(request.getKeyLength());

        PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                X500PrincipalUtils.toX500Name(request.getSubject()),
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        PKCS10CertificationRequest pkcs10 = requestBuilder
                .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

        String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded());

        CertificateResponse certificateResponse;

        /*
         * Since were not sure whether the WS proxy is thread safe, we will synchronize on this
         */
        synchronized (this) {
            certificateResponse = getEjbcaWS().certificateRequest(userData, base64PKCS10,
                    EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE);
        }

        if (certificateResponse != null && certificateResponse.getData() != null) {
            /*
             * The result is a base64 encoded certificate 
             */
            Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates(
                    new ByteArrayInputStream(Base64.decode(certificateResponse.getData())));

            if (CollectionUtils.isNotEmpty(certificates)) {
                X509Certificate generatedCertificate = null;

                for (X509Certificate certificate : certificates) {
                    if (certificate != null) {
                        /*
                         * Use the first one (EJBCA probably will always return just one certificate)
                         */
                        generatedCertificate = certificate;

                        break;
                    }
                }

                if (generatedCertificate != null) {
                    keyAndCertificate = new KeyAndCertificateImpl(keyPair.getPrivate(), generatedCertificate);
                } else {
                    logger.warn("No certificates found");
                }
            } else {
                logger.warn("No certificates found");
            }
        } else {
            logger.warn("certificateResponse is empty");
        }

        return keyAndCertificate;
    } catch (NoSuchAlgorithmException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (NoSuchProviderException e) {
        throw new CAException("Error requesting a certificate", e);
    } catch (CADoesntExistsException_Exception e) {
        throw new CAException("CA doesn't exist.", e);
    } catch (UserDoesntFullfillEndEntityProfile_Exception e) {
        throw new CAException("User doesn't fullfill end entity profile.", e);
    } catch (EjbcaException_Exception e) {
        throw new CAException("EJBCA exception.", e);
    } catch (AuthorizationDeniedException_Exception e) {
        throw new CAException("Authorization denied.", e);
    } catch (WaitingForApprovalException_Exception e) {
        throw new CAException("Waiting for approval.", e);
    } catch (ApprovalException_Exception e) {
        throw new CAException("Approval exception.", e);
    } catch (NotFoundException_Exception e) {
        throw new CAException("Not found exception.", e);
    } catch (CertificateException e) {
        throw new CAException("Certificate exception.", e);
    } catch (Base64DecodingException e) {
        throw new CAException("Error Base64 decoding.", e);
    } catch (OperatorCreationException e) {
        throw new CAException("Error creating a PKCS#10 request.", e);
    } catch (IOException e) {
        throw new CAException("Error requesting a certificate", e);
    }
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();

    Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied");

    KeyPairGenerator keyPairGenerator;

    try {/*from  w w  w .j ava  2 s  .  c  o m*/
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();

        signer = Signature.getInstance(SIGNING_ALGORITHM);
    } catch (GeneralSecurityException generalSecurityException) {
        // generalSecurityException.printStackTrace();
        throw new IllegalStateException(generalSecurityException);
    }

    // prepend the spec necessary SCOPE
    setScope((scope != null && !scope.isEmpty()) ? SCOPE + " " + scope : SCOPE);
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectoryTestCase.java

/**
 * Method to create a X509 certificate used to test the creation and the update of an entry in the ldap.
 *
 * @return A X509 certificate/*from  w ww.jav a 2  s.c  om*/
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IllegalStateException
 * @since 5.9.3
 */
protected X509Certificate createCertificate(String dnNameStr) throws NoSuchAlgorithmException,
        CertificateException, InvalidKeyException, IllegalStateException, SignatureException {
    X509Certificate cert = null;

    // Parameters used to define the certificate
    // yesterday
    Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    // in 2 years
    Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);

    // Generate the key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, new SecureRandom());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Define the content of the certificate
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal(dnNameStr);

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);
    certGen.setIssuerDN(dnName); // use the same
    certGen.setNotBefore(validityBeginDate);
    certGen.setNotAfter(validityEndDate);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSA");

    cert = certGen.generate(keyPair.getPrivate());

    return cert;
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Creates an authenticated certificate chain for the specified X509 name
 *
 * @param x509DN X509 name to for which to create a certificate chain
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return Returns a CABean instance encapsulating certificate chain and key information
 * or null if an error occurred/*from w  w w  .  jav a 2  s  .  co m*/
 */
private CABean createSignedCertificateChain(String x509DN, String keyType) {
    try {
        // Create a public/private keypair...
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType);
        keyGen.initialize(1024, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PrivateKey clientPrivateKey = keypair.getPrivate();
        PublicKey clientPublicKey = keypair.getPublic();

        // ...and a CSR from them...
        PKCS10CertificationRequest csr = generateRequest(x509DN, clientPublicKey, clientPrivateKey, keyType);

        // ...sign it
        KeyStore rootKS = loadRootKeyStore();
        X509Certificate rootCert = (X509Certificate) rootKS.getCertificate(rootCAKeystoreAlias);
        if (rootCert == null) {
            logger.error("Can't get root certificate from CA keystore");
            return null;
        }
        PrivateKey rootPrivKey = (PrivateKey) rootKS.getKey(rootCAKeystoreAlias,
                rootCAKeystorePassword.toCharArray());
        X509Certificate[] signedChain = createSignedCert(rootCert, rootPrivKey, csr, keyType);

        //...package up the result...
        CABean caBean = new CABean();
        caBean.setChain(signedChain);
        caBean.setCSRPrivateKey(clientPrivateKey);
        caBean.setSubjectDN(x509DN);

        // ...and send it back
        return caBean;
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

private X509Certificate createMiddleCaCert(X500Name subject, PublicKey pubKey, KeyPair pKeyPair,
        X500Name issuer) throws Exception {

    BigInteger sno = BigInteger.valueOf(3);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, sno, nb, na, subject,
            pubKey);/*  w  w w . j a v  a2 s .  com*/

    addSubjectKID(certBuilder, pubKey);
    addAuthorityKID(certBuilder, pKeyPair.getPublic());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3));
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));

    X509Certificate certificate = signCert(certBuilder, pKeyPair.getPrivate());
    certificate.checkValidity(new Date());
    certificate.verify(pKeyPair.getPublic());

    setPKCS9Info(certificate);

    return certificate;
}