Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

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

Prototype

public PrivateKey getPrivate() 

Source Link

Document

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

Usage

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

private void testKey(KeyPair pair) throws Exception {
    if (log.isDebugEnabled()) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final PrintStream ps = new PrintStream(baos);
        KeyTools.printPublicKeyInfo(pair.getPublic(), ps);
        ps.flush();/* w  w w.  j  ava 2  s . c  o  m*/
        log.debug("Using of " + baos.toString());
    }
    if (!doPermitExtractablePrivateKey() && KeyTools.isPrivateKeyExtractable(pair.getPrivate())) {
        String msg = intres.getLocalizedMessage("catoken.extractablekey",
                EjbcaConfiguration.doPermitExtractablePrivateKeys());
        if (!EjbcaConfiguration.doPermitExtractablePrivateKeys()) {
            throw new InvalidKeyException(msg);
        }
        log.info(msg);
    }
    KeyTools.testKey(pair.getPrivate(), pair.getPublic(), getProvider());
}

From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java

/** type 1 = ie (pkcs10)
 *  type 2 = csr (pkcs10req)//from w  w  w  .  j  a va 2s  .  co  m
 */
private String sendCsrRequest(int type) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException, IOException, InvalidKeyException, SignatureException,
        OperatorCreationException, MalformedURLException, ProtocolException, UnsupportedEncodingException {
    // Create a PKCS10 request
    KeyPair rsakeys = KeyTools.genKeys("512", "RSA");
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), rsakeys.getPublic(), new DERSet(),
            rsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();
    final StringBuilder request = new StringBuilder();
    if (type == 2) {
        request.append("-----BEGIN CERTIFICATE REQUEST-----\n");
    }
    request.append(new String(Base64.encode(bOut.toByteArray())));
    if (type == 2) {
        request.append("\n-----END CERTIFICATE REQUEST-----\n");
    }
    String p10 = request.toString();
    // System.out.println(p10);

    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceReq);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    OutputStream os = con.getOutputStream();
    final StringBuilder buf = new StringBuilder("user=" + TEST_USERNAME + "&password=foo123&");
    switch (type) {
    case 1:
        buf.append("pkcs10=");
        break;
    case 2:
        buf.append("resulttype=1&pkcs10req=");
        break;
    default:
        break;
    }
    buf.append(URLEncoder.encode(p10, "UTF-8"));
    os.write(buf.toString().getBytes("UTF-8"));
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and PKCS7 responses are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertTrue(respBytes.length > 0);

    String resp = new String(respBytes);
    return resp;
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

private void generateKeyPair(final KeyPairGenerator kpg, final String keyEntryName, final String sigAlgName) {
    // We will make a loop to retry key generation here. Using the IAIK provider it seems to give
    // CKR_OBJECT_HANDLE_INVALID about every second time we try to store keys
    // But if we try again it succeeds
    int bar = 0;/* ww  w  .  j a v a2 s .c  om*/
    while (bar < 3) {
        bar++;
        try {
            log.debug("generating...");
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=some guy, L=around, C=US", (long) 30 * 24 * 60 * 60 * 365,
                    sigAlgName, keyPair);
            log.debug("Creating certificate with entry " + keyEntryName + '.');
            setKeyEntry(keyEntryName, keyPair.getPrivate(), chain);
            break; // success no need to try more
        } catch (KeyStoreException e) {
            log.info("Failed to generate or store new key, will try 3 times. This was try: " + bar, e);
        } catch (CertificateException e) {
            throw new KeyCreationException(
                    "Can't create keystore because dummy certificate chain creation failed.", e);
        } catch (InvalidKeyException e) {
            throw new KeyCreationException("Dummy certificate chain was created with an invalid key", e);
        }
    }
}

From source file:netinf.common.security.identity.impl.IdentityManagerImpl.java

/**
 * @see IdentityManager#createNewMasterIdentity()
 *//* ww w .  j a  va  2 s .c  o m*/
@Override
public IdentityObject createNewMasterIdentity() throws NetInfCheckedException {
    // as soon as a new Master Identity is created, all Identites known to this IdentityManager will be stored to file. Thus,
    // ensure that identities are loaded from file before
    if (this.privateKeys.size() == 0) {
        try {
            loadIdentities();
        } catch (NetInfCheckedException e) {
            LOG.warn("Unable to load key file. " + e.getMessage());
        }
    }

    KeyPairGenerator k;
    try {
        k = KeyPairGenerator.getInstance("RSA");

    } catch (Exception e) {
        LOG.warn(e.getMessage());
        return null;
    }

    k.initialize(1024);
    KeyPair pair = k.generateKeyPair();

    // A new Master Identity implies a new Identity Object. Create it
    IdentityObject newIdentity = ValidCreator.createValidIdentityObject(pair.getPublic());

    // Derive the "Identity-Path"
    String pathToKey = newIdentity.getIdentifier().toString() + IntegrityImpl.PATH_SEPERATOR
            + DefinedAttributeIdentification.PUBLIC_KEY.getURI();

    this.privateKeys.put(pathToKey, pair.getPrivate());

    LOG.info("Private Key: " + Utils.objectToString(pair.getPrivate()));
    LOG.info("Public Key: " + Utils.objectToString(pair.getPublic()));

    // save private keys to file
    writePrivateKeysToFile(this.defaultFilepath, this.defaultKeyAlgorithmName, this.defaultPassword);

    return newIdentity;
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

@Override
protected final void addCertificate(final KeyStore kstore, final String password, final String alias,
        final String issuer) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException,
        OperatorCreationException, CertificateException, IOException, KeyStoreException, SignatureException {
    final KeyPair keypair; // Key pair for the certificate
    final Certificate certificate; // Generated certificate
    final Certificate[] chain; // Certificate chain

    // Creates a key pair
    keypair = getKeyPair();/*from www .  ja v a2  s  . c  om*/

    // Creates a certificate
    certificate = getCertificate(keypair, issuer);

    // Creates the certificates chain
    chain = new Certificate[] { certificate };

    // Sets the key data into the key store
    kstore.setKeyEntry(alias, keypair.getPrivate(), password.toCharArray(), chain);

    LOGGER.debug("Added certificate with alias {} and password {} for issuer {}", alias, password, issuer);
}

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

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

    try {//from ww w .  j a  va 2 s . co  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:cl.nic.dte.util.XMLUtil.java

public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey)
        throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException,
        IOException {/*from  ww w  . jav  a 2  s  . c o m*/
    // Generation of keys

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();

    CAFType caf = template.getAUTORIZACION().getCAF();
    CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK();

    rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray());
    rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray());

    ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults");

    Signature sig = null;
    if (pKey.getAlgorithm().equals("RSA")) {
        sig = Signature.getInstance("SHA1withRSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withRSA");
    } else if (pKey.getAlgorithm().equals("DSA")) {
        sig = Signature.getInstance("SHA1withDSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withDSA");
    } else {
        throw new NoSuchAlgorithmException(
                labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm()));
    }

    template.getAUTORIZACION()
            .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true))
                    + "-----END RSA PRIVATE KEY-----\n");

    template.getAUTORIZACION()
            .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true))
                    + "-----END RSA PUBLIC KEY-----\n");

    sig.initSign(pKey);
    sig.update(XMLUtil.getCleaned(caf.getDA()));

    caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign()));
    return template;
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * This method returns the mapped certificate for a hostname, or generates a "standard"
 * SSL server certificate issued by the CA to the supplied subject if no mapping has been
 * created.  This is not a true duplication, just a shortcut method
 * that is adequate for web browsers.//from  w  ww  . j  a  v a 2  s  . c om
 * 
 * @param hostname
 * @return
 * @throws CertificateParsingException
 * @throws InvalidKeyException
 * @throws CertificateExpiredException
 * @throws CertificateNotYetValidException
 * @throws SignatureException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public X509Certificate getMappedCertificateForHostname(String hostname)
        throws CertificateParsingException, InvalidKeyException, CertificateExpiredException,
        CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException,
        NoSuchProviderException, KeyStoreException, UnrecoverableKeyException {
    String subject = getSubjectForHostname(hostname);

    String thumbprint = _subjectMap.get(subject);

    if (thumbprint == null) {

        KeyPair kp = getRSAKeyPair();

        X509Certificate newCert = CertificateCreator.generateStdSSLServerCertificate(kp.getPublic(),
                getSigningCert(), getSigningPrivateKey(), subject);

        addCertAndPrivateKey(hostname, newCert, kp.getPrivate());

        thumbprint = ThumbprintUtil.getThumbprint(newCert);

        _subjectMap.put(subject, thumbprint);

        if (persistImmediately) {
            persist();
        }

        return newCert;

    }
    return getCertificateByAlias(thumbprint);

}

From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java

@Test
public void testGetKeyPair01() {
    KeyPair keyPair = this.generator.generateKeyPair();

    assertNotNull("The key pair should not be null.", keyPair);

    assertEquals("The algorithm is not correct.", KeyFileUtilities.keyAlgorithm,
            keyPair.getPrivate().getAlgorithm());
    assertEquals("The algorithm is not correct.", KeyFileUtilities.keyAlgorithm,
            keyPair.getPublic().getAlgorithm());
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

private X509Certificate createTypeOneX509Certificate(Date startDate, String principalDn, KeyPair keyPair) {
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal principal = new X500Principal(principalDn);
    certGen.setSerialNumber(serialNumber());
    certGen.setIssuerDN(principal);/*  www . ja v a2  s.co  m*/
    certGen.setNotBefore(startDate);
    DateTime now = new DateTime(new Date());
    certGen.setNotAfter(now.plusYears(YEARS).toDate());
    certGen.setSubjectDN(principal); // note: same as issuer
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(new SystemEnvironment().get(GO_SSL_CERTS_ALGORITHM));

    try {
        return certGen.generate(keyPair.getPrivate(), "BC");
    } catch (Exception e) {
        throw bomb(e);
    }
}