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:mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java

@Test
public void testGenerateSelfSignedV3Certificate() throws Exception {
    X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC");

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(2048, randomSource);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

    issuerBuilder.setCommonName("Martijn Brinkers");
    issuerBuilder.setCountryCode("NL");
    issuerBuilder.setEmail("test@example.com", "test2@example.com");
    issuerBuilder.setGivenName("Martijn");
    issuerBuilder.setSurname("Brinkers");
    issuerBuilder.setLocality("Amsterdam");
    issuerBuilder.setOrganisation("None");
    issuerBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();

    altNamesBuider.setRFC822Names("m.brinkers@pobox.com");
    altNamesBuider.setDNSNames("example.com");

    X500Principal issuer = issuerBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
    keyUsage.add(KeyUsageType.KEYENCIPHERMENT);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    Date notBefore = DateUtils.addHours(new Date(), -1);
    Date notAfter = DateUtils.addYears(new Date(), 10);

    certificateBuilder.setSubject(issuer);
    certificateBuilder.setIssuer(issuer);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true);
    certificateBuilder.setNotBefore(notBefore);
    certificateBuilder.setNotAfter(notAfter);
    certificateBuilder.setPublicKey(keyPair.getPublic());
    certificateBuilder.setSerialNumber(new BigInteger("1"));
    certificateBuilder.setSignatureAlgorithm("SHA256WithRSA");
    certificateBuilder.setIsCA(true, true /* critical */);
    certificateBuilder.setPathLengthConstraint(5);

    Set<String> crlDistPoints = new HashSet<String>();
    crlDistPoints.add("http://example.com");
    crlDistPoints.add("123");

    certificateBuilder.setCRLDistributionPoints(crlDistPoints);

    X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null);

    assertNotNull(certificate);//  www. j  a va  2s.  c  om

    File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer");

    CertificateUtils.writeCertificate(certificate, file);

    X509CertificateInspector certInspector = new X509CertificateInspector(certificate);

    assertEquals(
            "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, "
                    + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL",
            certInspector.getSubjectFriendly());

    assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly());

    AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames());

    List<String> rFC822Names = altNamesInspector.getRFC822Names();

    assertEquals(1, rFC822Names.size());
    assertEquals("m.brinkers@pobox.com", rFC822Names.get(0));

    List<String> dNSNames = altNamesInspector.getDNSNames();

    assertEquals(1, dNSNames.size());
    assertEquals("example.com", dNSNames.get(0));

    assertEquals(3, certInspector.getKeyUsage().size());
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION));

    assertEquals(2, certInspector.getExtendedKeyUsage().size());
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH));
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION));

    // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec
    assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000);
    assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000);

    assertEquals("1", certInspector.getSerialNumberHex());

    assertEquals("SHA256WITHRSA", certificate.getSigAlgName());

    assertTrue(certInspector.isCA());
    assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue());

    Set<String> crlDistPointsCert = CRLDistributionPointsInspector
            .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints());

    assertTrue(crlDistPointsCert.contains("http://example.com"));
    assertTrue(crlDistPointsCert.contains("123"));
}

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

protected Certificate createRACertificate(String username, String password, String raCertsPath, String cmpAlias,
        KeyPair keys, Date notBefore, Date notAfter, String certProfile, int caid)
        throws AuthorizationDeniedException, CertificateException, FileNotFoundException, IOException,
        UserDoesntFullfillEndEntityProfile, ObjectNotFoundException, RemoveException, CADoesntExistsException,
        WaitingForApprovalException, FinderException, EjbcaException, IllegalKeyException,
        CertificateCreateException, IllegalNameException, CertificateRevokeException,
        CertificateSerialNumberException, CryptoTokenOfflineException, IllegalValidityException,
        CAOfflineException, InvalidAlgorithmException, CustomCertificateSerialNumberException {

    createUser(username, "CN=" + username, password, caid);
    Certificate racert = this.signSession.createCertificate(ADMIN, username, password,
            new PublicKeyWrapper(keys.getPublic()), X509KeyUsage.digitalSignature | X509KeyUsage.keyCertSign,
            notBefore, notAfter, this.certProfileSession.getCertificateProfileId(certProfile), caid);

    List<Certificate> certCollection = new ArrayList<Certificate>();
    certCollection.add(racert);//from   ww  w.j a v a  2  s .com
    byte[] pemRaCert = CertTools.getPemFromCertificateChain(certCollection);

    String filename = raCertsPath + "/" + username + ".pem";
    FileOutputStream fout = new FileOutputStream(filename);
    fout.write(pemRaCert);
    fout.flush();
    fout.close();

    this.endEntityManagementSession.deleteUser(ADMIN, username);

    return racert;
}

From source file:org.artifactory.security.SecurityServiceImpl.java

@Override
public String createEncryptedPasswordIfNeeded(UserInfo user, String password) {
    if (isPasswordEncryptionEnabled()) {
        KeyPair keyPair;
        if (StringUtils.isBlank(user.getPrivateKey())) {
            MutableUserInfo mutableUser = InfoFactoryHolder.get().copyUser(user);
            keyPair = CryptoHelper.generateKeyPair();
            mutableUser.setPrivateKey(CryptoHelper.convertToString(keyPair.getPrivate()));
            mutableUser.setPublicKey(CryptoHelper.convertToString(keyPair.getPublic()));
            updateUser(mutableUser, false);
        } else {//from   w  w w.j a  va 2 s .co  m
            keyPair = CryptoHelper.createKeyPair(user.getPrivateKey(), user.getPublicKey(), false);
        }

        SecretKey secretKey = CryptoHelper.generatePbeKeyFromKeyPair(keyPair);
        return CryptoHelper.encryptSymmetric(password, secretKey, false);
    }
    return password;
}

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

@Test
public void test11EECrmfCheckAdminAuthorization()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, null);
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestUnauthorizedAdmin";
    createUser(adminName, "CN=" + adminName + ",C=SE", "foo123", true, this.caid,
            SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    KeyPair admkeys = KeyTools.genKeys("512", "RSA");
    Certificate admCert = this.signSession.createCertificate(ADMIN, adminName, "foo123",
            new PublicKeyWrapper(admkeys.getPublic()));
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);/*from www.  ja  v  a2  s  .c  om*/

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
        assertNotNull(respObject);

        PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        assertEquals("'CN=cmpTestUnauthorizedAdmin,C=SE' is not an authorized administrator.", errMsg);
    } finally {
        inputStream.close();
    }

}

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

@Test
public void test06EERevReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    Collection<Certificate> certs = this.certificateStoreSession
            .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN);
    log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
    Certificate cert = null, tmp = null;
    Iterator<Certificate> itr = certs.iterator();
    while (itr.hasNext()) {
        tmp = itr.next();/* w  w  w. ja va2s  . c om*/
        if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    if (cert == null) {
        createUser("cmprevuser1", "CN=cmprevuser1,C=SE", "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123",
                new PublicKeyWrapper(admkeys.getPublic()));
    }
    assertNotNull("No certificate to revoke.", cert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genRevReq(issuerDN, USER_DN, CertTools.getSerialNumber(cert), this.cacert, this.nonce,
            this.transid, false, pAlg, null);
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
            this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
    assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
            revStatus);

    removeAuthenticationToken(adminToken, admCert, adminName);
}

From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }//  w ww.j  a  v  a 2 s .  c  om

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

    final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(issuerDN);
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);

    // Create standard extensions
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream dOut = new ASN1OutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    if (altNames != null) {
        GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
        dOut.writeObject(san);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.subjectAlternativeName, false, value);
    }

    // KeyUsage
    int bcku = 0;
    bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
    KeyUsage ku = new KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
    // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

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

@Test
public void test04HMACRevReq() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name revUserDN = new X500Name("CN=cmprevuser1,C=SE");
    final String revUsername = "cmprevuser1";
    String fingerprint = null;/*from   w ww  .j a  v  a 2  s  . c  o m*/
    try {

        Collection<Certificate> certs = this.certificateStoreSession
                .findCertificatesBySubjectAndIssuer(revUserDN.toString(), issuerDN);
        log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
        Certificate cert = null, tmp = null;
        Iterator<Certificate> itr = certs.iterator();
        while (itr.hasNext()) {
            tmp = itr.next();
            if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
                cert = tmp;
                break;
            }
        }
        if (cert == null) {
            createUser(revUsername, revUserDN.toString(), "foo123", true, this.caid,
                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
            cert = this.signSession.createCertificate(ADMIN, revUsername, "foo123",
                    new PublicKeyWrapper(admkeys.getPublic()));
        }
        assertNotNull("No certificate to revoke.", cert);

        fingerprint = CertTools.getFingerprintAsString(cert); // to be able to remove

        PKIMessage msg = genRevReq(issuerDN, revUserDN, CertTools.getSerialNumber(cert), this.cacert,
                this.nonce, this.transid, false, null, null);
        assertNotNull("Generating RevocationRequest failed.", msg);
        PKIMessage req = protectPKIMessage(msg, false, "foo123", "mykeyid", 567);
        assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, revUserDN, this.cacert,
                req.getHeader().getSenderNonce().getOctets(), req.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
        Assert.assertNotEquals("Revocation request failed to revoke the certificate",
                RevokedCertInfo.NOT_REVOKED, revStatus);
    } finally {
        if (this.eeAccessSession.findUser(ADMIN, revUsername) != null) {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, revUsername, ReasonFlags.unused);
        }
        this.internalCertStoreSession.removeCertificate(fingerprint);
    }

}

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

@Test
public void test07EERevReqWithUnknownCA()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    Collection<Certificate> certs = this.certificateStoreSession
            .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN);
    log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
    Certificate cert = null, tmp = null;
    Iterator<Certificate> itr = certs.iterator();
    while (itr.hasNext()) {
        tmp = itr.next();//from w w  w .jav  a  2s  . c o  m
        if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    final String userName = "cmprevuser1";
    if (cert == null) {
        createUser(userName, "CN=" + userName + ",C=SE", "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123",
                new PublicKeyWrapper(admkeys.getPublic()));
    }
    try {
        assertNotNull("No certificate to revoke.", cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq("CN=cmprevuser1,C=SE", USER_DN, CertTools.getSerialNumber(cert), cert,
                this.nonce, this.transid, false, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);

        String adminName = "cmpTestAdmin";
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
                this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        Certificate admCert = getCertFromCredentials(adminToken);
        CMPCertificate[] extraCert = getCMPCert(admCert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, "CN=cmprevuser1,C=SE", USER_DN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
        assertEquals("Revocation request succeeded", RevokedCertInfo.NOT_REVOKED, revStatus);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(asn1InputStream.readObject());
            assertNotNull(respObject);

            PKIBody body = respObject.getBody();
            assertEquals(23, body.getType());
            ErrorMsgContent err = (ErrorMsgContent) body.getContent();
            String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
            String expectedErrMsg = "CA with DN 'C=SE,CN=cmprevuser1' is unknown";
            assertEquals(expectedErrMsg, errMsg);
            removeAuthenticationToken(adminToken, admCert, adminName);
        } finally {
            asn1InputStream.close();
        }
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, userName);
    }
}

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 ww.  ja v  a 2  s . c o m*/
    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.gluu.oxtrust.action.UpdateTrustRelationshipAction.java

/**
 * If there is no certificate selected, or certificate is invalid -
 * generates one.//w  ww .j ava2 s.  c om
 * 
 * @author Oleksiy Tataryn
 * @return certificate for generated SP
 * @throws CertificateEncodingException
 */
private String getCertForGeneratedSP() {
    X509Certificate cert = SSLService.instance().getCertificate(certWrapper.getStream());
    if (cert == null) {
        facesMessages.add(Severity.INFO,
                "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA();
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();

            String url = trustRelationship.getUrl().replaceFirst(".*//", "");

            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(
                    new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"),
                    BigInteger.valueOf(new SecureRandom().nextInt()),
                    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
                    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
                    new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(
                    new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_END_LINE);

            saveCert(trustRelationship, pemCertPre);
            saveKey(trustRelationship, keyWriter.toString());

        } catch (Exception e) {

            e.printStackTrace();
        }

        //         String certName = applicationConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(applicationConfiguration.getOrgInum())
        //               + "-shib.crt";
        //         File certFile = new File(certName);
        //         if (certFile.exists()) {
        //            cert = SSLService.instance().getCertificate(certName);
        //         }
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(Severity.ERROR,
                    "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(Severity.INFO,
                "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }

    return certificate;
}