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:com.thoughtworks.go.server.util.HttpTestUtil.java

private X509Certificate generateCert(final KeyPair keyPair) {
    Date startDate = day(-1);/*from w w  w .  j a v a 2 s.  c  o  m*/
    Date expiryDate = day(+1);
    BigInteger serialNumber = new BigInteger("1000200030004000");

    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal("CN=Test CA Certificate");

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(dnName); // note: same as issuer
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WITHRSA");

    try {
        return certGen.generate(keyPair.getPrivate());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

public X509Certificate generateV1Certificate(String subject, char[] ksPass, KeyStore keyStore)
        throws OperatorCreationException, IOException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException {
    KeyPair pair = generateKeyPair();

    BigInteger certSerial = BigInteger.valueOf(System.currentTimeMillis());
    X500Name issuerDN = new X500Name("CN=" + subject);
    X500Name subjectDN = new X500Name("CN=" + subject);
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(System.currentTimeMillis() + 10000);
    PublicKey pubKey = (pair.getPublic());
    X509v1CertificateBuilder certGen = new JcaX509v1CertificateBuilder(issuerDN, certSerial, notBefore,
            notAfter, subjectDN, pubKey);

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(pair.getPrivate());
    byte[] encoded = certGen.build(signer).getEncoded();
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    InputStream is = new ByteArrayInputStream(encoded);
    X509Certificate generateCertificate = (X509Certificate) fact.generateCertificate(is);
    is.close();/*from w  w w . j av a 2 s  .co  m*/

    // set the CA cert as trusted root
    X509Certificate[] chain = new X509Certificate[] { generateCertificate };
    addToKeyStore(pair, chain, K_NAME, keyStore, ksPass);

    String certStr = generateCertificate.toString();

    return generateCertificate;
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore,
        DateTime notAfter) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException {
    PublicKey subjectPublicKey = keyPair.getPublic();
    PrivateKey issuerPrivateKey = keyPair.getPrivate();
    String signatureAlgorithm = "SHA1WithRSAEncryption";
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();//from  ww w  .ja v a  2 s  . co m
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN = new X509Principal(subjectDn);
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    issuerPublicKey = subjectPublicKey;
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

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

/**
 * Returns a {@code Certificate} with the received data.
 *
 * @param keypair//from   ww w  .  jav  a2 s.co  m
 *            key pair for the certificate
 * @param issuer
 *            issuer for the certificate
 * @return a {@code Certificate} with the received data
 * @throws IOException
 *             if there is an I/O or format problem with the certificate
 *             data
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 * @throws InvalidKeyException
 *             if there was a problem with the key
 * @throws NoSuchAlgorithmException
 *             if an algorithm required to create the key store could not be
 *             found
 * @throws NoSuchProviderException
 *             if a required provider is missing
 * @throws SignatureException
 *             if any problem occurs while signing the certificate
 */
private final Certificate getCertificate(final KeyPair keypair, final String issuer)
        throws IOException, OperatorCreationException, CertificateException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    final X509v3CertificateBuilder builder; // Certificate builder
    final X509Certificate certificate; // Certificate

    // Generates the certificate builder
    builder = getCertificateBuilder(keypair.getPublic(), issuer);

    // Generates the signed certificate
    certificate = getSignedCertificate(builder, keypair.getPrivate());

    // Verifies the certificate
    certificate.checkValidity(getCurrentDate());
    certificate.verify(keypair.getPublic());

    LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(),
            Arrays.asList(certificate.getEncoded()));
    LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey());

    return certificate;
}

From source file:com.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java

private X509Certificate generateCertificate(KeyPair keyPair) throws Exception {
    Date from = new Date();
    Date to = new GregorianCalendar(2037, Calendar.DECEMBER, 31).getTime();
    X500Name subject = new X500Name("CN=localhost");
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(subject,
            new BigInteger(64, new SecureRandom()), from, to, subject, subPubKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512WITHRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()));
    X509CertificateHolder certHolder = certBuilder.build(contentSigner);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
}

From source file:mitm.common.security.ca.hibernate.CertificateRequestStoreImplTest.java

@Test
public void testGetKeyPairSpeedTest() throws Exception {
    AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

    KeyPair keyPair = generateKeyPair();

    CertificateRequest request = delegator.addRequest(null, "test@example.com", 365, "SHA1",
            "http://example.com", "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

    long start = System.currentTimeMillis();

    int repeat = 100;

    for (int i = 0; i < repeat; i++) {
        KeyPair keyPairCopy = request.getKeyPair(encryptor);

        assertNotNull(keyPairCopy);//from   w  ww . j av  a  2s. c  o  m
        assertEquals(keyPair.getPublic(), keyPairCopy.getPublic());
        assertEquals(keyPair.getPrivate(), keyPairCopy.getPrivate());
    }

    long diff = System.currentTimeMillis() - start;

    double perSecond = repeat * 1000.0 / diff;

    System.out.println("getKeyPair's/sec: " + perSecond);

    /*
     * NOTE: !!! can fail on a slower system. The speed depends on the system encryptor. If the default settings 
     * (like iteration count) have been changed this might be slower.
     * 
     * On my Quad CPU Q8300, should be about 500/sec
     */
    assertTrue("getKeyPair too slow. !!! this can fail on a slower system !!!", perSecond > 200);
}

From source file:it.zero11.acme.Acme.java

@SuppressWarnings("serial")
protected String getNewCertificateRequest(final KeyPair userKey, final String nonce,
        final PKCS10CertificationRequest csr) throws IOException {
    return Jwts.builder().setHeaderParam(NONCE_KEY, nonce)
            .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic()))
            .setClaims(new TreeMap<String, Object>() {
                {/*from   w  w  w.  j a v  a2 s .  c  om*/
                    put(RESOURCE_KEY, RESOURCE_NEW_CERT);
                    put(CSR_KEY, TextCodec.BASE64URL.encode(csr.getEncoded()));
                }
            }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact();
}

From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java

public String getSignedRequest(int format, InputStream keystoreStream, String keystorePassword, String keyAlias,
        String keyPassword) {//w  w  w.  j a  v  a  2 s  . c om
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    DocumentBuilder builder;
    Document doc;
    try {
        builder = dbf.newDocumentBuilder();
        doc = builder.parse(new InputSource(new ByteArrayInputStream(getRequest(plain).getBytes("utf-8"))));

        // Prepare doc by marking attributes as referenceable:
        tagIdAttributes(doc);

        // Prepare cryptographic environemnt
        KeyStore keystore = getKeystore("JKS", keystoreStream, keystorePassword);
        if (keystore == null)
            return null;

        KeyPair kp;

        kp = getKeyPairFromKeystore(keystore, keyAlias, keyPassword);
        if (kp == null) {
            // Generate key, to prove that it works...
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
            kpg.initialize(512);
            kp = kpg.generateKeyPair();
        }

        // Set signing context with PrivateKey and root of the Document
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());

        // Get SignatureFactory for creating signatures in DOM:
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

        // Create reference for "" -> root of the document
        // SAML requires enveloped transform
        Reference ref = fac.newReference("#" + this._id, fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null, null);

        // Create SignedInfo (SAML2: Exclusive with or without comments is specified)
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

        // Add KeyInfo to the document:
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        // .. get key from the generated keypair:
        KeyValue kv = kif.newKeyValue(kp.getPublic());
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature signature = fac.newXMLSignature(si, ki);

        String before = docToString(doc);

        // Sign!
        signature.sign(dsc);

        _authnRequestDocument = doc; // persist, as we've worked hard for it

        String after = docToString(doc);

        if (_logger.isDebugEnabled()) {
            _logger.debug("Before: {}", before);
            _logger.debug("After : {}", after);
        }

        return after;

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // key generation exception
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        // digest algorithm selection exception
        e.printStackTrace();
    } catch (KeyException e) {
        // when key-value was not available (when adding to KeyInfo)
        e.printStackTrace();
    } catch (MarshalException e) {
        // sign didn't work:
        e.printStackTrace();
    } catch (XMLSignatureException e) {
        // sign didn't work:
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.sshd.client.auth.UserAuthPublicKey.java

public UserAuthPublicKey(ClientSessionImpl session, String username, KeyPair key) throws IOException {
    try {//from   w  w  w.  j a v  a2  s .  c  o m
        log.info("Send SSH_MSG_USERAUTH_REQUEST for publickey");
        Buffer buffer = session.createBuffer(SshConstants.Message.SSH_MSG_USERAUTH_REQUEST, 0);
        int pos1 = buffer.wpos() - 1;
        buffer.putString(username);
        buffer.putString("ssh-connection");
        buffer.putString("publickey");
        buffer.putByte((byte) 1);
        buffer.putString(
                (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS);
        int pos2 = buffer.wpos();
        buffer.putPublicKey(key.getPublic());

        Signature verif = NamedFactory.Utils.create(session.getFactoryManager().getSignatureFactories(),
                (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS);
        verif.init(key.getPublic(), key.getPrivate());

        Buffer bs = new Buffer();
        bs.putString(session.getKex().getH());
        bs.putCommand(SshConstants.Message.SSH_MSG_USERAUTH_REQUEST);
        bs.putString(username);
        bs.putString("ssh-connection");
        bs.putString("publickey");
        bs.putByte((byte) 1);
        bs.putString(
                (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS);
        bs.putPublicKey(key.getPublic());
        verif.update(bs.array(), bs.rpos(), bs.available());

        bs = new Buffer();
        bs.putString(
                (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS);
        bs.putBytes(verif.sign());
        buffer.putBytes(bs.array(), bs.rpos(), bs.available());

        session.writePacket(buffer);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw (IOException) new IOException("Error performing public key authentication").initCause(e);
    }
}

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

public Registration createAgentCertificate(final File authorityKeystore, String agentHostname) {
    Date epoch = new Date(0);
    KeyPair agentKeyPair = generateKeyPair();
    try {//from   w  w  w  . ja v a 2 s  .co  m
        KeyStore store = loadOrCreateCAKeyStore(authorityKeystore);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));

        X509Certificate[] chain = new X509Certificate[3];
        chain[2] = (X509Certificate) store.getCertificate("ca-cert");
        chain[1] = (X509Certificate) intermediateEntry.getCertificate();
        chain[0] = createAgentCertificate(agentKeyPair.getPublic(), intermediateEntry.getPrivateKey(),
                chain[1].getPublicKey(), agentHostname, epoch);
        return new Registration(agentKeyPair.getPrivate(), chain);
    } catch (Exception e) {
        throw bomb("Couldn't create agent certificate", e);
    }
}