List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:be.fedict.eid.tsl.TrustServiceList.java
public void addXadesBes(XMLSignatureFactory signatureFactory, Document document, String signatureId, X509Certificate signingCertificate, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("preSign"); // QualifyingProperties QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType(); qualifyingProperties.setTarget("#" + signatureId); // SignedProperties SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType(); String signedPropertiesId = signatureId + "-xades"; signedProperties.setId(signedPropertiesId); qualifyingProperties.setSignedProperties(signedProperties); // SignedSignatureProperties SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); // SigningTime GregorianCalendar signingTime = new GregorianCalendar(); signingTime.setTimeZone(TimeZone.getTimeZone("Z")); XMLGregorianCalendar xmlSigningTime = this.datatypeFactory.newXMLGregorianCalendar(signingTime); xmlSigningTime.setMillisecond(DatatypeConstants.FIELD_UNDEFINED); signedSignatureProperties.setSigningTime(xmlSigningTime); // SigningCertificate CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType(); CertIDType signingCertificateId = this.xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = this.xmldsigObjectFactory.createX509IssuerSerialType(); issuerSerial.setX509IssuerName(signingCertificate.getIssuerX500Principal().toString()); issuerSerial.setX509SerialNumber(signingCertificate.getSerialNumber()); signingCertificateId.setIssuerSerial(issuerSerial); DigestAlgAndValueType certDigest = this.xadesObjectFactory.createDigestAlgAndValueType(); DigestMethodType jaxbDigestMethod = this.xmldsigObjectFactory.createDigestMethodType(); jaxbDigestMethod.setAlgorithm(DigestMethod.SHA256); certDigest.setDigestMethod(jaxbDigestMethod); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digestValue; try {/* w ww. j av a 2s. c o m*/ digestValue = messageDigest.digest(signingCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); } certDigest.setDigestValue(digestValue); signingCertificateId.setCertDigest(certDigest); signingCertificates.getCert().add(signingCertificateId); signedSignatureProperties.setSigningCertificate(signingCertificates); // marshall XAdES QualifyingProperties Node qualifyingPropertiesNode = marshallQualifyingProperties(document, qualifyingProperties); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode)); XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); // add XAdES ds:Reference DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Transform> transforms = new LinkedList<Transform>(); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms, XADES_TYPE, null); references.add(reference); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void getCertificate() throws Exception { List<Certificate> certs = ejbcaraws.findCerts("WSTESTTOKENUSER1", true); Certificate cert = certs.get(0); X509Certificate realcert = (X509Certificate) CertificateHelper.getCertificate(cert.getCertificateData()); cert = ejbcaraws.getCertificate(realcert.getSerialNumber().toString(16), CertTools.getIssuerDN(realcert)); assertNotNull(cert);/*from w w w.ja v a2 s. c o m*/ X509Certificate realcert2 = (X509Certificate) CertificateHelper.getCertificate(cert.getCertificateData()); assertTrue(realcert.getSerialNumber().equals(realcert2.getSerialNumber())); cert = ejbcaraws.getCertificate("1234567", CertTools.getIssuerDN(realcert)); assertNull(cert); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void checkRevokeStatus() throws Exception { final P12TestUser p12TestUser = new P12TestUser(); final X509Certificate cert = p12TestUser.getCertificate("12345678"); String issuerdn = cert.getIssuerDN().toString(); String serno = cert.getSerialNumber().toString(16); RevokeStatus revokestatus = ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus);/*from w w w .ja va 2s . c o m*/ assertTrue(revokestatus.getReason() == RevokedCertInfo.NOT_REVOKED); ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); revokestatus = ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus); assertTrue(revokestatus.getReason() == RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); assertTrue(revokestatus.getCertificateSN().equals(serno)); assertTrue(revokestatus.getIssuerDN().equals(issuerdn)); assertNotNull(revokestatus.getRevocationDate()); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void revokeCertBackdated() throws Exception { final P12TestUser p12TestUser = new P12TestUser(); final X509Certificate cert = p12TestUser.getCertificate(null); final String issuerdn = cert.getIssuerDN().toString(); final String serno = cert.getSerialNumber().toString(16); final String sDate = "2012-06-07T23:55:59+02:00"; final CertificateProfile certProfile = this.certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI); certProfile.setAllowBackdatedRevocation(false); this.certificateProfileSession.changeCertificateProfile(intAdmin, WS_CERTPROF_EI, certProfile); try {/*w ww. jav a2 s .co m*/ this.ejbcaraws.revokeCertBackdated(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, sDate); assertTrue(false); } catch (RevokeBackDateNotAllowedForProfileException_Exception e) { // do nothing } certProfile.setAllowBackdatedRevocation(true); this.certificateProfileSession.changeCertificateProfile(intAdmin, WS_CERTPROF_EI, certProfile); this.ejbcaraws.revokeCertBackdated(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, sDate); final RevokeStatus revokestatus = this.ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus); final Date realRevokeDate = revokestatus.getRevocationDate().toGregorianCalendar().getTime(); final Date expectedRevokeDate; try { expectedRevokeDate = DatatypeConverter.parseDateTime(sDate).getTime(); } catch (IllegalArgumentException e) { assertTrue("Not a valid ISO8601 date revocation date", false); return; } assertEquals("Revocation date not the expected.", expectedRevokeDate, realRevokeDate); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void revokeCert() throws Exception { final P12TestUser p12TestUser = new P12TestUser(); final X509Certificate cert = p12TestUser.getCertificate(null); final String issuerdn = cert.getIssuerDN().toString(); final String serno = cert.getSerialNumber().toString(16); this.ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); {/*w w w . j a v a2s . c om*/ final RevokeStatus revokestatus = this.ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus); assertTrue(revokestatus.getReason() == RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); assertTrue(revokestatus.getCertificateSN().equals(serno)); assertTrue(revokestatus.getIssuerDN().equals(issuerdn)); assertNotNull(revokestatus.getRevocationDate()); } this.ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED); { final RevokeStatus revokestatus = this.ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus); assertTrue(revokestatus.getReason() == RevokedCertInfo.NOT_REVOKED); } { //final long beforeTimeMilliseconds = new Date().getTime(); final Date beforeRevoke = new Date(); this.ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); final Date afterRevoke = new Date(); //final Date beforeRevoke = new Date(beforeTimeMilliseconds-beforeTimeMilliseconds%1000); final RevokeStatus revokestatus = this.ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus); assertTrue(revokestatus.getReason() == RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); final Date revokeDate = revokestatus.getRevocationDate().toGregorianCalendar().getTime(); assertTrue("Too early revocation date. Before time '" + beforeRevoke + "'. Revoke time '" + revokeDate + "'.", !revokeDate.before(beforeRevoke)); assertTrue( "Too late revocation date. After time '" + afterRevoke + "'. Revoke time '" + revokeDate + "'.", !revokeDate.after(afterRevoke)); } try { this.ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED); assertTrue(false); } catch (AlreadyRevokedException_Exception e) { } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
/** * Tests the possibility to use different signature algorithms in CMP requests and responses if protection algorithm * is specified./*from w w w.j av a 2 s. com*/ * * A CMP request is sent to a CA that uses ECDSA with SHA256 as signature and encryption algorithms: * * 1. Send a CRMF request signed using ECDSA with SHA256 algorithm and expects a response signed by the same algorithm * 2. Send a CMP Confirm message without protection. The response is expected to be signed using ECDSA (because that's the CA's key algorithm) * and SHA1 (because that's the default digest algorithm) * 3. Sends a CMP Revocation request signed using ECDSA with SHA256 and expects a response signed by the same algorithm. * * @throws Exception */ @Test public void test22EECAuthWithSHA256AndECDSA() throws Exception { log.trace(">test22EECAuthWithSHA256AndECDSA()"); //-------------- Set the necessary configurations this.cmpConfiguration.setRAEEProfile(ALIAS, "ECDSAEEP"); this.cmpConfiguration.setRACertProfile(ALIAS, "ECDSACP"); this.cmpConfiguration.setCMPDefaultCA(ALIAS, "CmpECDSATestCA"); this.cmpConfiguration.setRACAName(ALIAS, "CmpECDSATestCA"); this.cmpConfiguration.setRAMode(ALIAS, true); this.cmpConfiguration.setRANameGenScheme(ALIAS, "DN"); this.cmpConfiguration.setRANameGenParams(ALIAS, "CN"); this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "CmpECDSATestCA"); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); removeTestCA("CmpECDSATestCA"); try { final CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CryptoTokenManagementSessionRemote.class); final int cryptoTokenId = cryptoTokenManagementSession.getIdFromName("CmpECDSATestCA").intValue(); CryptoTokenTestUtils.removeCryptoToken(ADMIN, cryptoTokenId); } catch (Exception e) {/* do nothing */ } //---------------------- Create the test CA // Create catoken String ecdsaCADN = "CN=CmpECDSATestCA"; String keyspec = "prime256v1"; int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(null, "foo123".toCharArray(), true, false, ecdsaCADN, keyspec); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA, AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA); final List<ExtendedCAServiceInfo> extendedCaServices = new ArrayList<ExtendedCAServiceInfo>(2); extendedCaServices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); String caname = CertTools.getPartFromDN(ecdsaCADN, "CN"); X509CAInfo ecdsaCaInfo = new X509CAInfo(ecdsaCADN, caname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, 3650, CAInfo.SELFSIGNED, null, catoken); ecdsaCaInfo.setExtendedCAServiceInfos(extendedCaServices); X509CA ecdsaCA = new X509CA(ecdsaCaInfo); ecdsaCA.setCAToken(catoken); // A CA certificate Collection<Certificate> cachain = new ArrayList<Certificate>(); final PublicKey publicKey = this.cryptoTokenManagementProxySession .getPublicKey(cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)) .getPublicKey(); //final String keyalg = AlgorithmTools.getKeyAlgorithm(publicKey); String sigalg = AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA; final PrivateKey privateKey = this.cryptoTokenManagementProxySession.getPrivateKey(cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); int keyusage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509Certificate ecdsaCaCert = CertTools.genSelfCertForPurpose(ecdsaCADN, 10L, "1.1.1.1", privateKey, publicKey, sigalg, true, keyusage, true); assertNotNull(ecdsaCaCert); cachain.add(ecdsaCaCert); ecdsaCA.setCertificateChain(cachain); this.caSession.addCA(ADMIN, ecdsaCA); //-------------- Create the EndEntityProfile and the CertificateProfile List<Integer> availableCAs = new ArrayList<Integer>(); availableCAs.add(Integer.valueOf(ecdsaCA.getCAId())); CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.setSignatureAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA); cp.setAvailableCAs(availableCAs); cp.setAllowDNOverride(true); try { this.certProfileSession.addCertificateProfile(ADMIN, "ECDSACP", cp); } catch (CertificateProfileExistsException e) {// do nothing } int cpId = this.certProfileSession.getCertificateProfileId("ECDSACP"); // Configure an EndEntity profile (CmpRA) with allow CN, O, C in DN // and rfc822Name (uncheck 'Use entity e-mail field' and check // 'Modifyable'), MS UPN in altNames in the end entity profile. EndEntityProfile eep = new EndEntityProfile(true); eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId); eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId); eep.setValue(EndEntityProfile.DEFAULTCA, 0, "" + ecdsaCA.getCAId()); eep.setValue(EndEntityProfile.AVAILCAS, 0, "" + ecdsaCA.getCAId()); eep.setModifyable(DnComponents.RFC822NAME, 0, true); eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field // from "email" data try { this.endEntityProfileSession.addEndEntityProfile(ADMIN, "ECDSAEEP", eep); } catch (EndEntityProfileExistsException e) {// do nothing } int eepId = this.endEntityProfileSession.getEndEntityProfileId("ECDSAEEP"); //---------------- Send a CMP initialization request AuthenticationToken admToken = null; final String testAdminDN = "CN=cmptestadmin,C=SE"; final String testAdminName = "cmptestadmin"; X509Certificate admCert = null; String fp = null, fp2 = null; try { KeyPair keys = KeyTools.genKeys(keyspec, AlgorithmConstants.KEYALGORITHM_ECDSA); final X500Name userDN = new X500Name("CN=cmpecdsauser"); final byte[] _nonce = CmpMessageHelper.createSenderNonce(); final byte[] _transid = CmpMessageHelper.createSenderNonce(); final AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA256); PKIMessage req = genCertReq(ecdsaCaInfo.getSubjectDN(), userDN, keys, ecdsaCaCert, _nonce, _transid, false, null, null, null, null, pAlg, null); createUser(testAdminName, testAdminDN, "foo123", true, ecdsaCaInfo.getCAId(), eepId, cpId); KeyPair admkeys = KeyTools.genKeys(keyspec, AlgorithmConstants.KEYALGORITHM_ECDSA); admToken = createAdminToken(admkeys, testAdminName, testAdminDN, ecdsaCA.getCAId(), eepId, cpId); admCert = getCertFromCredentials(admToken); fp = CertTools.getFingerprintAsString(admCert); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), AlgorithmTools.getDigestFromSigAlg(pAlg.getAlgorithm().getId()), "BC");//CMSSignedGenerator.DIGEST_SHA256 assertNotNull(req); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, ecdsaCaInfo.getSubjectDN(), userDN, ecdsaCaCert, _nonce, _transid, true, null, X9ObjectIdentifiers.ecdsa_with_SHA256.getId()); X509Certificate cert = checkCmpCertRepMessage(userDN, ecdsaCaCert, resp, reqId); fp2 = CertTools.getFingerprintAsString(cert); // ------------------- Send a CMP confirm message String hash = "foo123"; PKIMessage confirm = genCertConfirm(userDN, ecdsaCaCert, _nonce, _transid, hash, reqId); assertNotNull(confirm); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(confirm); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpHttp(ba, 200, ALIAS); //Since pAlg was not set in the ConfirmationRequest, the default DigestAlgorithm (SHA1) will be used checkCmpResponseGeneral(resp, ecdsaCaInfo.getSubjectDN(), userDN, ecdsaCaCert, _nonce, _transid, true, null, X9ObjectIdentifiers.ecdsa_with_SHA1.getId()); checkCmpPKIConfirmMessage(userDN, ecdsaCaCert, resp); //------------------------- Send a CMP revocation request PKIMessage rev = genRevReq(ecdsaCaInfo.getSubjectDN(), userDN, cert.getSerialNumber(), ecdsaCaCert, _nonce, _transid, true, pAlg, null); assertNotNull(rev); rev = CmpMessageHelper.buildCertBasedPKIProtection(rev, extraCert, admkeys.getPrivate(), AlgorithmTools.getDigestFromSigAlg(pAlg.getAlgorithm().getId()), "BC"); assertNotNull(rev); ByteArrayOutputStream baorev = new ByteArrayOutputStream(); DEROutputStream outrev = new DEROutputStream(baorev); outrev.writeObject(rev); byte[] barev = baorev.toByteArray(); // Send request and receive response resp = sendCmpHttp(barev, 200, ALIAS); checkCmpResponseGeneral(resp, ecdsaCaInfo.getSubjectDN(), userDN, ecdsaCaCert, _nonce, _transid, true, null, X9ObjectIdentifiers.ecdsa_with_SHA256.getId()); int revStatus = checkRevokeStatus(ecdsaCaInfo.getSubjectDN(), CertTools.getSerialNumber(cert)); assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED, revStatus); } finally { try { removeAuthenticationToken(admToken, admCert, testAdminName); } catch (Exception e) { //NOPMD: Ignore } try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "cmpecdsauser", ReasonFlags.unused); } catch (Exception e) { //NOPMD: Ignore } this.internalCertStoreSession.removeCertificate(fp); this.internalCertStoreSession.removeCertificate(fp2); this.endEntityProfileSession.removeEndEntityProfile(ADMIN, "ECDSAEEP"); this.certProfileSession.removeCertificateProfile(ADMIN, "ECDSACP"); removeTestCA("CmpECDSATestCA"); } log.trace("<test22EECAuthWithSHA256AndECDSA()"); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void revokeToken() throws Exception { final P12TestUser p12TestUser = new P12TestUser(); final X509Certificate cert1 = p12TestUser.getCertificate("12345678"); final X509Certificate cert2 = p12TestUser.getCertificate("12345678"); ejbcaraws.revokeToken("12345678", RevokeStatus.REVOKATION_REASON_KEYCOMPROMISE); String issuerdn1 = cert1.getIssuerDN().toString(); String serno1 = cert1.getSerialNumber().toString(16); RevokeStatus revokestatus = ejbcaraws.checkRevokationStatus(issuerdn1, serno1); assertNotNull(revokestatus);//from w w w. ja va 2s.c om assertTrue(revokestatus.getReason() == RevokeStatus.REVOKATION_REASON_KEYCOMPROMISE); String issuerdn2 = cert2.getIssuerDN().toString(); String serno2 = cert2.getSerialNumber().toString(16); revokestatus = ejbcaraws.checkRevokationStatus(issuerdn2, serno2); assertNotNull(revokestatus); assertTrue(revokestatus.getReason() == RevokeStatus.REVOKATION_REASON_KEYCOMPROMISE); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void keyRecoverAny() throws Exception { log.trace(">keyRecoverAny"); GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); boolean krenabled = gc.getEnableKeyRecovery(); if (!krenabled == true) { gc.setEnableKeyRecovery(true);// w ww . j a v a 2 s .c o m globalConfigurationSession.saveConfiguration(intAdmin, gc); } // Add a new user, set token to P12, status to new and end entity // profile to key recovery UserDataVOWS user1 = new UserDataVOWS(); user1.setKeyRecoverable(true); user1.setUsername("WSTESTUSERKEYREC2"); user1.setPassword("foo456"); user1.setClearPwd(true); user1.setSubjectDN("CN=WSTESTUSERKEYREC2"); user1.setCaName(getAdminCAName()); user1.setEmail(null); user1.setSubjectAltName(null); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_P12); user1.setEndEntityProfileName("KEYRECOVERY"); user1.setCertificateProfileName("ENDUSER"); ejbcaraws.editUser(user1); UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue("WSTESTUSERKEYREC2"); List<java.security.KeyStore> keyStores = new ArrayList<java.security.KeyStore>(); // generate 4 certificates for (int i = 0; i < 4; i++) { List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null); assertTrue(userdatas.size() == 1); user1 = userdatas.get(0); // Surely not all of these properties need to be set again? user1.setKeyRecoverable(true); user1.setUsername("WSTESTUSERKEYREC2"); user1.setPassword("foo456"); user1.setClearPwd(true); user1.setSubjectDN("CN=WSTESTUSERKEYREC2"); user1.setCaName(getAdminCAName()); user1.setEmail(null); user1.setSubjectAltName(null); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_P12); user1.setEndEntityProfileName("KEYRECOVERY"); user1.setCertificateProfileName("ENDUSER"); ejbcaraws.editUser(user1); KeyStore ksenv = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC2", "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks); keyStores.add(ks); } // user should have 4 certificates assertTrue(keyStores.size() == 4); // recover all keys for (java.security.KeyStore ks : keyStores) { Enumeration<String> en = ks.aliases(); String alias = (String) en.nextElement(); // You never know in which order the certificates in the KS are returned, it's different between java 6 and 7 for ex if (!ks.isKeyEntry(alias)) { alias = (String) en.nextElement(); } X509Certificate cert = (X509Certificate) ks.getCertificate(alias); assertEquals(cert.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC2"); PrivateKey privK = (PrivateKey) ks.getKey(alias, "foo456".toCharArray()); log.info("recovering key. sn " + cert.getSerialNumber().toString(16) + " issuer " + cert.getIssuerDN().toString()); // recover key ejbcaraws.keyRecover("WSTESTUSERKEYREC2", cert.getSerialNumber().toString(16), cert.getIssuerDN().toString()); // A new PK12 request now should return the same key and certificate KeyStore ksenv = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC2", "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); // You never know in which order the certificates in the KS are returned, it's different between java 6 and 7 for ex if (!ks.isKeyEntry(alias)) { alias = (String) en.nextElement(); } X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC2"); PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); // Compare certificates assertEquals(cert.getSerialNumber().toString(16), cert2.getSerialNumber().toString(16)); // Compare keys String key1 = new String(Hex.encode(privK.getEncoded())); String key2 = new String(Hex.encode(privK2.getEncoded())); assertEquals(key1, key2); } log.trace("<keyRecoverAny"); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Create a Truststore alias that would be used for adding the given trusted * X509 certificate to the Truststore. The alias is cretaed as * "trustedcert#"<CERT_SUBJECT_COMMON_NAME>"#"<CERT_ISSUER_COMMON_NAME>"#"< * CERT_SERIAL_NUMBER>/* ww w . j a v a 2 s . c o m*/ * * @param cert * certificate to generate the alias for * @return the alias for the given certificate */ @Override public String createTrustedCertificateAlias(X509Certificate cert) { String ownerDN = cert.getSubjectX500Principal().getName(RFC2253); ParsedDistinguishedName parsedDN = dnParser.parseDN(ownerDN); String owner; String ownerCN = parsedDN.getCN(); // owner's common name String ownerOU = parsedDN.getOU(); String ownerO = parsedDN.getO(); if (!ownerCN.equals("none")) { // try owner's CN first owner = ownerCN; } // try owner's OU else if (!ownerOU.equals("none")) { owner = ownerOU; } else if (!ownerO.equals("none")) { // finally use owner's Organisation owner = ownerO; } else { owner = "<Not Part of Certificate>"; } /* Get the hexadecimal representation of the certificate's serial number */ String serialNumber = new BigInteger(1, cert.getSerialNumber().toByteArray()).toString(16).toUpperCase(); String issuerDN = cert.getIssuerX500Principal().getName(RFC2253); parsedDN = dnParser.parseDN(issuerDN); String issuer; String issuerCN = parsedDN.getCN(); // issuer's common name String issuerOU = parsedDN.getOU(); String issuerO = parsedDN.getO(); if (!issuerCN.equals("none")) { // try issuer's CN first issuer = issuerCN; } // try issuer's OU else if (!issuerOU.equals("none")) { issuer = issuerOU; } else if (!issuerO.equals("none")) { // finally use issuer's // Organisation issuer = issuerO; } else { issuer = "<Not Part of Certificate>"; } String alias = "trustedcert#" + owner + "#" + issuer + "#" + serialNumber; return alias; }
From source file:eu.stork.peps.auth.engine.STORKSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * // w w w . j a v a2s . c om * @param keyInfo the key info * @param storkOwnKeyStore * @param storkOwnKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore storkOwnKeyStore) { LOG.debug("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(16); final X509Principal tokenIssuerDN = new X509Principal(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(16); X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X509PrincipalUtil.equals2(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.error("Procces getAlias from certificate associated into the signing keystore..", e); } catch (CertificateException e) { LOG.error("Procces getAlias from certificate associated into the signing keystore..", e); } catch (RuntimeException e) { LOG.error("Procces getAlias from certificate associated into the signing keystore..", e); } return alias; }