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:edu.vt.alerts.android.library.tasks.RegistrationTask.java

private KeyStore createKeyStore(KeyPair keyPair, HttpResponse response) throws Exception {
    Log.i("registration", "Got status from registration server: " + response.getStatusLine());

    HttpEntity entity = response.getEntity();
    byte[] contents = getBytes(entity.getContent());
    Collection<?> certs = extractCerts(contents);
    Certificate[] certificates = new Certificate[certs.size()];
    Log.i("registration", "Extracted out " + certs.size() + " certs");

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    Iterator<?> it = certs.iterator();
    int i = 0;/*from   ww  w  .j a va  2  s  .c  o  m*/
    while (it.hasNext()) {
        byte[] encoded = ((X509CertificateHolder) it.next()).getEncoded();
        certificates[i++] = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(encoded));
    }

    Log.d("registration", "Creating local keystore");
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setKeyEntry("Cert", keyPair.getPrivate(), "changeit".toCharArray(), certificates);

    return keyStore;
}

From source file:hudson.cli.Connection.java

public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
    KeyPair keyPair;
    PublicKey otherHalf;/*ww w .  j  av a 2  s.co 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:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:MainClass.java

public static X509Certificate[] buildChain() throws Exception {
    KeyPair pair = generateRSAKeyPair();
    PKCS10CertificationRequest request = generateRequest(pair);

    KeyPair rootPair = generateRSAKeyPair();
    X509Certificate rootCert = generateV1Certificate(rootPair);

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier,

            false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

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

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i != attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }/* ww  w .  j  ava2  s.  c  om*/
        }
    }
    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java

@Test
public void test09CrmfWrongIssuerAndDoNotCheckAdmin()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    this.cmpConfiguration.setAuthenticationParameters(cmpAlias, "-;foo123");
    this.cmpConfiguration.setOmitVerificationsInECC(cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(this.admin, this.cmpConfiguration);

    //-----------------Creating CRMF request
    //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN);
    byte[] senderNonce = CmpMessageHelper.createSenderNonce();
    byte[] transactionID = CmpMessageHelper.createSenderNonce();
    Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago
    Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now
    assertNotNull(nb);// w  w  w. j av  a  2 s.  co m
    assertNotNull(na);

    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, pAlg, new DEROctetString(senderNonce));

    KeyPair nonAdminKeys = KeyTools.genKeys("1024", "RSA");
    Certificate nonAdminCert = CertTools.genSelfCert("CN=cmpTestAdmin,C=SE", 365, null,
            nonAdminKeys.getPrivate(), nonAdminKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA,
            false);
    CMPCertificate[] cmpcert = getCMPCert(nonAdminCert);
    crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, nonAdminKeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(crmfMsg);
    CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent();
    int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    //------------------Creating NestedMessageContent
    String reqSubjectDN = "CN=bogusSubjectNested";
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(crmfMsg);
    DERSequence seq = new DERSequence(v);
    PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent
    assertNotNull("Failed to create nested Message PKIBody", myPKIBody);

    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    assertNotNull("Failed to created nested message PKIMessage", myPKIMessage);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raCrmfSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200);
    // do not check signing if we expect a failure (sFailMessage==null)
    checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert,
            crmfMsg.getHeader().getSenderNonce().getOctets(),
            crmfMsg.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID);
    assertNotNull("CrmfRequest did not return a certificate", cert);
    assertTrue(cert instanceof X509Certificate);
    log.debug("Subject DN of created certificate: "
            + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded()));
}

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

private X509Certificate createIntermediateCertificate(PrivateKey caPrivKey, X509Certificate caCert,
        Date startDate, KeyPair keyPair) throws Exception {
    X500Name issuerDn = JcaX500NameUtil.getSubject(caCert);

    X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    subjectBuilder.addRDN(BCStyle.OU, INTERMEDIATE_CERT_OU);
    subjectBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL);
    X500Name subjectDn = subjectBuilder.build();

    X509CertificateGenerator.V3X509CertificateGenerator v3CertGen = new V3X509CertificateGenerator(startDate,
            issuerDn, subjectDn, keyPair.getPublic(), serialNumber());

    // extensions
    v3CertGen.addSubjectKeyIdExtension(keyPair.getPublic());
    v3CertGen.addAuthorityKeyIdExtension(caCert);
    v3CertGen.addBasicConstraintsExtension();

    X509Certificate cert = v3CertGen.generate(caPrivKey);

    Date now = new Date();
    cert.checkValidity(now);/* www . jav  a2 s.c om*/
    cert.verify(caCert.getPublicKey());

    PKCS12BagAttributeSetter.usingBagAttributeCarrier(cert).setFriendlyName(INTERMEDIATE_CERT_OU);

    PKCS12BagAttributeSetter.usingBagAttributeCarrier(keyPair.getPrivate()).setFriendlyName(FRIENDLY_NAME)
            .setLocalKeyId(keyPair.getPublic());

    return cert;
}

From source file:com.netscape.cmstools.CRMFPopClient.java

public Signature createSigner(CryptoToken token, String algorithm, KeyPair keyPair) throws Exception {

    Signature signer;// ww  w. j  a va  2s  . c  o  m
    if (algorithm.equals("rsa")) {
        signer = token.getSignatureContext(SignatureAlgorithm.RSASignatureWithSHA256Digest);

    } else if (algorithm.equals("ec")) {
        signer = token.getSignatureContext(SignatureAlgorithm.ECSignatureWithSHA256Digest);

    } else {
        throw new Exception("Unknown algorithm: " + algorithm);
    }

    signer.initSign((org.mozilla.jss.crypto.PrivateKey) keyPair.getPrivate());

    return signer;
}

From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java

@Test
public void test05CrmfRACertDoesNotExist()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, Exception {

    //------------------- Creating Certificate Request ---------------
    //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN);
    byte[] senderNonce = CmpMessageHelper.createSenderNonce();
    byte[] transactionID = CmpMessageHelper.createSenderNonce();
    Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago
    Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now
    assertNotNull(nb);//from  w  ww  .ja v  a 2 s  . c  o  m
    assertNotNull(na);

    KeyPair keys = null;
    keys = KeyTools.genKeys("1024", "RSA");
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, null, null);
    assertNotNull("Failed to create crmfMsg.", crmfMsg);

    // ---------------- Creating the NestedMessageContent ----------------------

    String reqSubjectDN = "CN=bogusSubjectNested";
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // nonce
    DEROctetString dernonce = new DEROctetString(nonce);
    myPKIHeader.setSenderNonce(dernonce);
    myPKIHeader.setRecipNonce(dernonce);
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));

    PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    // Don't create a certificate, so there is no RA cert authorized on the server side.
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null,
            "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    assertEquals("Wrong error message",
            "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg);

    NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias,
            this.globalConfigurationSession);
    boolean ret = nestedContent.verify();
    assertFalse("The message verification failed, yet the a certificate was returned.", ret);

}