List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generateSpkac() throws Exception { // Edit our favorite test user UserDataVOWS user1 = new UserDataVOWS(); user1.setUsername(CA1_WSTESTUSER1);/*ww w.j ava2s. co m*/ user1.setPassword(PASSWORD); user1.setClearPwd(true); user1.setSubjectDN(getDN(CA1_WSTESTUSER1)); user1.setCaName(CA1); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); user1.setEndEntityProfileName("EMPTY"); user1.setCertificateProfileName("ENDUSER"); ejbcaraws.editUser(user1); CertificateResponse certenv = ejbcaraws.spkacRequest(CA1_WSTESTUSER1, PASSWORD, SPCAK, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); }
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);/*from www . j av a2s . 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:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generatePkcs12() throws Exception { log.trace(">generatePkcs12"); boolean exceptionThrown = false; try {/*www . ja v a 2 s . c om*/ ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); } catch (EjbcaException_Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown);// Should fail // Change token to P12 UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertNotNull(userdatas); assertEquals(1, userdatas.size()); userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_P12); userdatas.get(0).setSubjectDN(getDN(CA1_WSTESTUSER1)); ejbcaraws.editUser(userdatas.get(0)); exceptionThrown = false; try { ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); } catch (EjbcaException_Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown); // Should fail // Change password to foo456 and status to NEW userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword("foo456"); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); KeyStore ksenv = null; try { ksenv = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); } catch (EjbcaException_Exception e) { assertTrue(e.getMessage(), false); } assertNotNull(ksenv); java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks); Enumeration<String> en = ks.aliases(); String alias = en.nextElement(); X509Certificate cert = (X509Certificate) ks.getCertificate(alias); assertEquals(cert.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1)); PrivateKey privK1 = (PrivateKey) ks.getKey(alias, "foo456".toCharArray()); log.info("test04GeneratePkcs12() Certificate " + cert.getSubjectDN().toString() + " equals " + getDN(CA1_WSTESTUSER1)); // Generate a new one and make sure it is a new one and that key // recovery does not kick in by mistake // Set status to new usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null); assertTrue(userdatas.size() == 1); userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword("foo456"); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); // A new PK12 request now should return the same key and certificate KeyStore ksenv2 = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1)); PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); // Compare certificates, must not be the same assertFalse(cert.getSerialNumber().toString(16).equals(cert2.getSerialNumber().toString(16))); // Compare keys, must not be the same String key1 = new String(Hex.encode(privK1.getEncoded())); String key2 = new String(Hex.encode(privK2.getEncoded())); assertFalse(key1.equals(key2)); // Test the method for adding/editing and requesting a PKCS#12 KeyStore // in a single transaction ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1)); privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); // Test the method for adding/editing and requesting a JKS KeyStore in a // single transaction userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_JKS); ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "JKS", "foo456"); assertNotNull(ks2); en = ks2.aliases(); alias = (String) en.nextElement(); cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectX500Principal().getName(), getReversedDN(CA1_WSTESTUSER1)); privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray()); log.trace("<generatePkcs12"); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generateCrmf() throws Exception { // Edit our favorite test user UserDataVOWS user1 = new UserDataVOWS(); user1.setUsername(CA1_WSTESTUSER1);// w w w . j a va 2 s . co m user1.setPassword(PASSWORD); user1.setClearPwd(true); user1.setSubjectDN(getDN(CA1_WSTESTUSER1)); user1.setCaName(CA1); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); user1.setEndEntityProfileName(WS_EEPROF_EI); user1.setCertificateProfileName(WS_CERTPROF_EI); ejbcaraws.editUser(user1); final AuthenticationToken admin = new TestAlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("SYSTEMTEST")); KeyPair keys = KeyTools.genKeys("512", "RSA"); CAInfo info = caSession.getCAInfo(admin, CA1); CertReqMsg req = createCrmfRequest(info.getSubjectDN(), getDN(CA1_WSTESTUSER1), keys, "1.2.3.4"); CertReqMessages msgs = new CertReqMessages(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(msgs); byte[] ba = bao.toByteArray(); String reqstr = new String(Base64.encode(ba)); //CertificateResponse certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, CRMF, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); CertificateResponse certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, reqstr, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); log.info(cert.getSubjectDN().toString()); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); byte[] ext = cert.getExtensionValue("1.2.3.4"); // Certificate profile did not allow extension override assertNull("no extension should exist", ext); // Allow extension override CertificateProfile profile = certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI); profile.setAllowExtensionOverride(true); certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile); // Now our extension should be possible to get in there try { ejbcaraws.editUser(user1); keys = KeyTools.genKeys("512", "RSA"); info = caSession.getCAInfo(admin, CA1); req = createCrmfRequest(info.getSubjectDN(), getDN(CA1_WSTESTUSER1), keys, "1.2.3.4"); msgs = new CertReqMessages(req); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(msgs); ba = bao.toByteArray(); reqstr = new String(Base64.encode(ba)); certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, reqstr, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); ext = cert.getExtensionValue("1.2.3.4"); assertNotNull("there should be an extension", ext); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(ext)); try { DEROctetString oct = (DEROctetString) (asn1InputStream.readObject()); assertEquals("Extension did not have the correct value", "foo123", (new String(oct.getOctets()).trim())); } finally { asn1InputStream.close(); } } finally { // restore profile.setAllowExtensionOverride(false); certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile); } }
From source file:org.apache.juddi.webconsole.hub.UddiHub.java
/** * Converts a UDDI Signature to a readable representation of the signing * certificate subject name/*from ww w . j a v a2 s . c o m*/ * * @param sig * @return human readable signature */ public static String SignatureToReadable(SignatureType sig) { StringBuilder sb = new StringBuilder(); // X509Certificate signingcert = null; //sb.append("Signature Id: ").append(sig.getKeyInfo().getId()); for (int i = 0; i < sig.getKeyInfo().getContent().size(); i++) { //sb.append("Signature #").append((i + 1)).append(": "); JAXBElement get = (JAXBElement) sig.getKeyInfo().getContent().get(i); if (get.getValue() instanceof org.w3._2000._09.xmldsig_.X509DataType) { X509DataType xd = (X509DataType) get.getValue(); for (int k = 0; k < xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().size(); k++) { if (xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().get(k) instanceof JAXBElement) { JAXBElement element = (JAXBElement) xd.getX509IssuerSerialOrX509SKIOrX509SubjectName() .get(k); if (element.getValue() instanceof byte[]) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream is = new ByteArrayInputStream((byte[]) element.getValue()); X509Certificate cert = (X509Certificate) cf.generateCertificate(is); is.close(); sb.append(cert.getSubjectDN().getName()); } catch (Exception ex) { } } else if (element.getValue() instanceof String) { // sb.append((String) element.getValue()); } } } } } return sb.toString(); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void certificateRequestThrowAway() throws Exception { final AuthenticationToken authenticationToken = new TestAlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("SYSTEMTEST-certificateRequestThrowAway")); final String username = "CA1_WSTESTUSER_ThrowAway"; String certificateFingerprint = null; // Use throw away CA mode (don't store UserData, CertificateData or CertReqHistoryData) final CAInfo caInfo = caSession.getCAInfo(authenticationToken, CA1); final boolean originalUseCertificateStorage = caInfo.isUseCertificateStorage(); final boolean originalUseCertReqHistory = caInfo.isUseCertReqHistory(); final boolean originalUseUserStorage = caInfo.isUseUserStorage(); try {/*from ww w . j av a2 s .com*/ caInfo.setUseCertificateStorage(false); caInfo.setUseCertReqHistory(false); caInfo.setUseUserStorage(false); caSession.editCA(authenticationToken, caInfo); // Setup user data to make the request final UserDataVOWS userDataVOWS = new UserDataVOWS(); userDataVOWS.setUsername(username); userDataVOWS.setPassword(PASSWORD); userDataVOWS.setClearPwd(true); userDataVOWS.setSubjectDN("CN=" + username); userDataVOWS.setCaName(caInfo.getName()); userDataVOWS.setEmail(null); userDataVOWS.setSubjectAltName(null); userDataVOWS.setStatus(UserDataVOWS.STATUS_NEW); userDataVOWS.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); userDataVOWS.setEndEntityProfileName(WS_EEPROF_EI); userDataVOWS.setCertificateProfileName(WS_CERTPROF_EI); // Generate a certificate request final String pkcs10AsBase64 = getP10(); // Request a certificate via the WS API final CertificateResponse certificateResponse; try { certificateResponse = ejbcaraws.certificateRequest(userDataVOWS, pkcs10AsBase64, CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); } catch (EjbcaException_Exception e) { final ErrorCode errorCode = e.getFaultInfo().getErrorCode(); log.info(errorCode.getInternalErrorCode(), e); fail("Throw away certificate request failed with error code " + errorCode); throw new Error("JUnit test should have bailed out before this happens."); } // Verify that the response is of the right type and that a certificate was issued correctly assertNotNull(certificateResponse); assertTrue(certificateResponse.getResponseType().equals(CertificateHelper.RESPONSETYPE_CERTIFICATE)); final X509Certificate x509Certificate = certificateResponse.getCertificate(); assertNotNull(x509Certificate); assertTrue(x509Certificate.getSubjectDN().toString().equals(userDataVOWS.getSubjectDN())); certificateFingerprint = CertTools.getFingerprintAsString(x509Certificate); // Verify that no UserData was written to the database assertFalse("UserData was persisted dispite the CA being told not to store it.", endEntityManagementSession.existsUser(username)); // Verify that no CertificateData was written to the database final java.security.cert.Certificate certificate = certificateStoreSession .findCertificateByFingerprint(certificateFingerprint); assertNull("CertificateData was persisted dispite the CA being told not to store it.", certificate); // Verify that no CertReqHistoryData was written to the database final List<CertReqHistory> certReqHistoryList = certReqHistorySession.retrieveCertReqHistory(username); assertEquals("CertReqHistoryData was persisted dispite the CA being told not to store it.", 0, certReqHistoryList.size()); } finally { final CAInfo caInfoToRestore = caSession.getCAInfo(authenticationToken, CA1); caInfoToRestore.setUseCertificateStorage(originalUseCertificateStorage); caInfoToRestore.setUseCertReqHistory(originalUseCertReqHistory); caInfoToRestore.setUseUserStorage(originalUseUserStorage); caSession.editCA(authenticationToken, caInfoToRestore); if (endEntityManagementSession.existsUser(username)) { endEntityManagementSession.deleteUser(authenticationToken, username); } if (certificateFingerprint != null && certificateStoreSession.findCertificateByFingerprint(certificateFingerprint) != null) { internalCertStoreSession.removeCertificate(certificateFingerprint); } if (certReqHistorySession.retrieveCertReqHistory(username).size() > 0) { certReqHistorySession.removeCertReqHistoryData(certificateFingerprint); } } }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generatePkcs10() throws Exception { UserDataVOWS user1 = new UserDataVOWS(); user1.setUsername(CA1_WSTESTUSER1);// ww w . j a v a 2 s. c om user1.setPassword(PASSWORD); user1.setClearPwd(true); user1.setSubjectDN(getDN(CA1_WSTESTUSER1)); user1.setCaName(CA1); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); user1.setEndEntityProfileName(WS_EEPROF_EI); user1.setCertificateProfileName(WS_CERTPROF_EI); ejbcaraws.editUser(user1); final AuthenticationToken admin = new TestAlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("SYSTEMTEST")); PKCS10CertificationRequest pkcs10 = getP10Request(); // Submit the request CertificateResponse certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); byte[] ext = cert.getExtensionValue("1.2.3.4"); // Certificate profile did not allow extension override assertNull("no extension should exist", ext); // Allow extension override CertificateProfile profile = certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI); profile.setAllowExtensionOverride(true); certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile); // Now our extension should be possible to get in there try { ejbcaraws.editUser(user1); pkcs10 = getP10Request(); certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); ext = cert.getExtensionValue("1.2.3.4"); assertNotNull("there should be an extension", ext); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(ext)); try { DEROctetString oct = (DEROctetString) (asn1InputStream.readObject()); assertEquals("Extension did not have the correct value", "foo123", (new String(oct.getOctets())).trim()); } finally { asn1InputStream.close(); } } finally { // restore profile.setAllowExtensionOverride(false); certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile); } }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void keyRecover() throws Exception { log.trace(">keyRecover"); GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); boolean krenabled = gc.getEnableKeyRecovery(); if (krenabled == true) { gc.setEnableKeyRecovery(false);//from w w w . j av a2s .c o m globalConfigurationSession.saveConfiguration(intAdmin, gc); } boolean trows = false; try { // This should throw an exception that key recovery is not enabled ejbcaraws.keyRecoverNewest(CA1_WSTESTUSER1); } catch (EjbcaException_Exception e) { trows = true; // e.printStackTrace(); assertEquals(e.getMessage(), "Keyrecovery have to be enabled in the system configuration in order to use this command."); } assertTrue(trows); // Set key recovery enabled gc.setEnableKeyRecovery(true); globalConfigurationSession.saveConfiguration(intAdmin, gc); trows = false; try { // This should throw an exception that the user does not exist ejbcaraws.keyRecoverNewest("sdfjhdiuwerw43768754###"); } catch (NotFoundException_Exception e) { trows = true; // e.printStackTrace(); assertEquals(e.getMessage(), "Wrong username or password"); } assertTrue(trows); // Add a new End entity profile, KEYRECOVERY EndEntityProfile profile = new EndEntityProfile(); profile.addField(DnComponents.COMMONNAME); profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true); profile.setValue(EndEntityProfile.KEYRECOVERABLE, 0, EndEntityProfile.TRUE); profile.setUse(EndEntityProfile.KEYRECOVERABLE, 0, true); profile.setUse(EndEntityProfile.CLEARTEXTPASSWORD, 0, true); profile.setReUseKeyRecoveredCertificate(true); profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS)); endEntityProfileSession.addEndEntityProfile(intAdmin, "KEYRECOVERY", profile); assertTrue("Unable to create KEYRECOVERY end entity profile.", endEntityProfileSession.getEndEntityProfile("KEYRECOVERY") != null); // 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("WSTESTUSERKEYREC1"); user1.setPassword("foo456"); user1.setClearPwd(true); user1.setSubjectDN("CN=WSTESTUSERKEYREC1"); 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("WSTESTUSERKEYREC1", "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456"); assertNotNull(ks); Enumeration<String> en = ks.aliases(); String alias = en.nextElement(); if (!ks.isKeyEntry(alias)) { alias = en.nextElement(); } X509Certificate cert = (X509Certificate) ks.getCertificate(alias); assertEquals("CN=WSTESTUSERKEYREC1", cert.getSubjectDN().toString()); PrivateKey privK = (PrivateKey) ks.getKey(alias, "foo456".toCharArray()); // This should work now ejbcaraws.keyRecoverNewest("WSTESTUSERKEYREC1"); // Set status to keyrecovery UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue("WSTESTUSERKEYREC1"); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null); assertTrue(userdatas.size() == 1); userdatas.get(0).setStatus(EndEntityConstants.STATUS_KEYRECOVERY); ejbcaraws.editUser(userdatas.get(0)); // A new PK12 request now should return the same key and certificate KeyStore ksenv2 = ejbcaraws.pkcs12Req("WSTESTUSERKEYREC1", "foo456", null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.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 (!ks2.isKeyEntry(alias)) { alias = (String) en.nextElement(); } X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias); assertEquals(cert2.getSubjectDN().toString(), "CN=WSTESTUSERKEYREC1"); 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("<keyRecover"); }
From source file:org.apache.rahas.impl.SAML2TokenIssuer.java
/** * This method is used to create the subject of an assertion * @param config//from w w w. j a va 2 s .c o m * @param doc * @param crypto * @param creationTime * @param expirationTime * @param data * @return Subject * @throws Exception */ private Subject createSubjectWithHolderOfKeySC(SAMLTokenIssuerConfig config, Document doc, Crypto crypto, DateTime creationTime, DateTime expirationTime, RahasData data) throws Exception { XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); SAMLObjectBuilder<Subject> subjectBuilder = (SAMLObjectBuilder<Subject>) builderFactory .getBuilder(Subject.DEFAULT_ELEMENT_NAME); Subject subject = subjectBuilder.buildObject(); Element keyInfoElem = null; // If it is a Symmetric Key if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) { isSymmetricKeyBasedHoK = true; Element encryptedKeyElem; X509Certificate serviceCert = null; try { if (data.getPrincipal() != null) { //get subject's name from Rahas data String subjectNameID = data.getPrincipal().getName(); //Create NameID and attach it to the subject NameID nameID = new NameIDBuilder().buildObject(); nameID.setValue(subjectNameID); nameID.setFormat(NameIdentifier.EMAIL); subject.setNameID(nameID); } // Get ApliesTo to figure out which service to issue the token // for serviceCert = config.getServiceCert(crypto, data.getAppliesToAddress()); // Create the encrypted key WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey(); // Use thumbprint id encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); // SEt the encryption cert encrKeyBuilder.setUseThisCert(serviceCert); // set keysize int keysize = data.getKeysize(); keysize = (keysize != -1) ? keysize : config.keySize; encrKeyBuilder.setKeySize(keysize); encrKeyBuilder .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize)); // Set key encryption algo encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); // Build encrKeyBuilder.prepare(doc, crypto); // Extract the base64 encoded secret value byte[] tempKey = new byte[keysize / 8]; System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8); data.setEphmeralKey(tempKey); // Extract the Encryptedkey DOM element encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement(); } catch (WSSecurityException e) { throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal", new String[] { serviceCert.getSubjectDN().getName() }, e); } keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo"); ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX); ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX); keyInfoElem.appendChild(encryptedKeyElem); } // If it is a public Key else if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) { try { String subjectNameId = data.getPrincipal().getName(); //Create NameID and attach it to the subject NameIDBuilder nb = new NameIDBuilder(); NameID nameID = nb.buildObject(); nameID.setValue(subjectNameId); nameID.setFormat(NameIdentifier.EMAIL); subject.setNameID(nameID); // Create the ds:KeyValue element with the ds:X509Data X509Certificate clientCert = data.getClientCert(); if (clientCert == null) { X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName()); clientCert = certs[0]; } byte[] clientCertBytes = clientCert.getEncoded(); String base64Cert = Base64.encode(clientCertBytes); Text base64CertText = doc.createTextNode(base64Cert); //----------------------------------------- Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Certificate"); x509CertElem.appendChild(base64CertText); Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Data"); x509DataElem.appendChild(x509CertElem); if (x509DataElem != null) { keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo"); ((OMElement) x509DataElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX); keyInfoElem.appendChild(x509DataElem); } } catch (Exception e) { throw new TrustException("samlAssertionCreationError", e); } } // Unmarshall the keyInfo DOM element into an XMLObject String keyInfoElementString = keyInfoElem.toString(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes())); Element element = document.getDocumentElement(); // Get appropriate unmarshaller UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); // Unmarshall using the document root element, an keyInfo element in this case XMLObject keyInfoElement = null; try { keyInfoElement = unmarshaller.unmarshall(element); } catch (UnmarshallingException e) { throw new TrustException("Error unmarshalling KeyInfo Element", e); } //Build the Subject Confirmation SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) builderFactory .getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME); SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject(); //Set the subject Confirmation method subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"); SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder = (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory .getBuilder(KeyInfoConfirmationDataType.TYPE_NAME); //Build the subject confirmation data element KeyInfoConfirmationDataType scData = keyInfoSubjectConfirmationDataBuilder .buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME); //Set the keyInfo element scData.getKeyInfos().add(keyInfoElement); // Set the validity period scData.setNotBefore(creationTime); scData.setNotOnOrAfter(expirationTime); //Set the subject confirmation data subjectConfirmation.setSubjectConfirmationData(scData); //set the subject confirmation subject.getSubjectConfirmations().add(subjectConfirmation); log.debug("SAML2.0 subject is constructed successfully."); return subject; }
From source file:org.codice.ddf.security.filter.login.LoginFilter.java
private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException { List<String> confirmationMethods = assertion.getConfirmationMethods(); boolean hasHokMethod = false; for (String method : confirmationMethods) { if (OpenSAMLUtil.isMethodHolderOfKey(method)) { hasHokMethod = true;/*from w w w . j av a 2 s .c o m*/ } } if (hasHokMethod) { if (x509Certs != null && x509Certs.length > 0) { List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject() .getSubjectConfirmations(); for (SubjectConfirmation subjectConfirmation : subjectConfirmations) { if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) { Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM(); Node keyInfo = dom.getFirstChild(); Node x509Data = keyInfo.getFirstChild(); Node dataNode = x509Data.getFirstChild(); Node dataText = dataNode.getFirstChild(); X509Certificate tlsCertificate = x509Certs[0]; if (dataNode.getLocalName().equals("X509Certificate")) { String textContent = dataText.getTextContent(); byte[] byteValue = Base64.getMimeDecoder().decode(textContent); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(byteValue)); //check that the certificate is still valid cert.checkValidity(); //HoK spec section 2.5: //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession. //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte. //if the certs aren't the same, verify if (!tlsCertificate.equals(cert)) { //verify that the cert was signed by the same private key as the TLS cert cert.verify(tlsCertificate.getPublicKey()); } } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with certificate."); } } else if (dataNode.getLocalName().equals("X509SubjectName")) { String textContent = dataText.getTextContent(); //HoK spec section 2.5: //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate. //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion. if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject DN."); } } else if (dataNode.getLocalName().equals("X509IssuerSerial")) { //we have no way to support this confirmation type so we have to throw an error throw new SecurityServiceException( "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED"); } else if (dataNode.getLocalName().equals("X509SKI")) { String textContent = dataText.getTextContent(); byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14"); byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent); if (tlsSKI != null && tlsSKI.length > 0) { ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI); ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI); SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier .getInstance(tlsOs.getOctets()); SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier .getInstance(assertionOs.getOctets()); //HoK spec section 2.5: //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate. //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension, //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion. if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject key identifier."); } } else { throw new SecurityServiceException( "Unable to validate Holder of Key assertion with subject key identifier."); } } } } } else { throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS."); } } }