List of usage examples for java.security.cert X509Certificate getIssuerDN
public abstract Principal getIssuerDN();
From source file:org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {//from w w w. java2 s .c om KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LOG.isDebugEnabled()) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LOG.debug(" Certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LOG.isDebugEnabled()) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSLv3"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationException("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationException("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationException("Key management exception: " + e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationException( "I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.signserver.web.GenericProcessServlet.java
private void processRequest(final HttpServletRequest req, final HttpServletResponse res, final int workerId, final byte[] data, String fileName, final String pdfPassword, final ProcessType processType, final MetaDataHolder metadataHolder) throws java.io.IOException, ServletException { final String remoteAddr = req.getRemoteAddr(); if (LOG.isDebugEnabled()) { LOG.debug("Recieved HTTP process request for worker " + workerId + ", from ip " + remoteAddr); }// w w w. j a v a 2 s .c o m // Client certificate Certificate clientCertificate = null; Certificate[] certificates = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); if (certificates != null) { clientCertificate = certificates[0]; } // Create request context and meta data final RequestContext context = new RequestContext(clientCertificate, remoteAddr); RequestMetadata metadata = RequestMetadata.getInstance(context); IClientCredential credential; if (clientCertificate instanceof X509Certificate) { final X509Certificate cert = (X509Certificate) clientCertificate; LOG.debug("Authentication: certificate"); credential = new CertificateClientCredential(cert.getSerialNumber().toString(16), cert.getIssuerDN().getName()); } else { // Check is client supplied basic-credentials final String authorization = req.getHeader(HTTP_AUTH_BASIC_AUTHORIZATION); if (authorization != null) { LOG.debug("Authentication: password"); final String decoded[] = new String(Base64.decode(authorization.split("\\s")[1])).split(":", 2); credential = new UsernamePasswordClientCredential(decoded[0], decoded[1]); } else { LOG.debug("Authentication: none"); credential = null; } } context.put(RequestContext.CLIENT_CREDENTIAL, credential); // Create log map LogMap logMap = LogMap.getInstance(context); final String xForwardedFor = req.getHeader(RequestContext.X_FORWARDED_FOR); // Add HTTP specific log entries logMap.put(IWorkerLogger.LOG_REQUEST_FULLURL, req.getRequestURL().append("?").append(req.getQueryString()).toString()); logMap.put(IWorkerLogger.LOG_REQUEST_LENGTH, String.valueOf(data.length)); logMap.put(IWorkerLogger.LOG_FILENAME, fileName); logMap.put(IWorkerLogger.LOG_XFORWARDEDFOR, xForwardedFor); logMap.put(IWorkerLogger.LOG_WORKER_NAME, getWorkerSession().getCurrentWorkerConfig(workerId).getProperty(PropertiesConstants.NAME)); if (xForwardedFor != null) { context.put(RequestContext.X_FORWARDED_FOR, xForwardedFor); } // Store filename for use by archiver etc if (fileName != null) { fileName = stripPath(fileName); } context.put(RequestContext.FILENAME, fileName); context.put(RequestContext.RESPONSE_FILENAME, fileName); // PDF Password if (pdfPassword != null) { metadata.put(RequestContext.METADATA_PDFPASSWORD, pdfPassword); } addRequestMetaData(metadataHolder, metadata); if (LOG.isDebugEnabled()) { LOG.debug("Received bytes of length: " + data.length); } final int requestId = random.nextInt(); try { String responseText; switch (processType) { case signDocument: final GenericServletResponse servletResponse = (GenericServletResponse) getWorkerSession().process( new AdminInfo("Client user", null, null), workerId, new GenericServletRequest(requestId, data, req), context); if (servletResponse.getRequestID() != requestId) { // TODO: Is this possible to get at all? LOG.error("Response ID " + servletResponse.getRequestID() + " not matching request ID " + requestId); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Request and response ID missmatch"); return; } byte[] processedBytes = (byte[]) servletResponse.getProcessedData(); res.setContentType(servletResponse.getContentType()); Object responseFileName = context.get(RequestContext.RESPONSE_FILENAME); if (responseFileName instanceof String) { res.setHeader("Content-Disposition", "attachment; filename=\"" + responseFileName + "\""); } res.setContentLength(processedBytes.length); res.getOutputStream().write(processedBytes); break; case validateDocument: final GenericValidationResponse validationResponse = (GenericValidationResponse) getWorkerSession() .process(new AdminInfo("Client user", null, null), workerId, new GenericValidationRequest(requestId, data), context); responseText = validationResponse.isValid() ? "VALID" : "INVALID"; if (LOG.isDebugEnabled()) { final Validation validation = validationResponse.getCertificateValidation(); if (validation != null) { LOG.debug("Cert validation status: " + validationResponse.getCertificateValidation().getStatusMessage()); } } res.setContentType("text/plain"); res.setContentLength(responseText.getBytes().length); res.getOutputStream().write(responseText.getBytes()); break; case validateCertificate: final Certificate cert; try { cert = CertTools.getCertfromByteArray(data); final String certPurposes = req.getParameter(CERT_PURPOSES_PROPERTY_NAME); final ValidateResponse certValidationResponse = (ValidateResponse) getWorkerSession().process( new AdminInfo("Client user", null, null), workerId, new ValidateRequest(cert, certPurposes), context); final Validation validation = certValidationResponse.getValidation(); final StringBuilder sb = new StringBuilder(validation.getStatus().name()); sb.append(";"); final String validPurposes = certValidationResponse.getValidCertificatePurposes(); if (validPurposes != null) { sb.append(certValidationResponse.getValidCertificatePurposes()); } sb.append(";"); sb.append(certValidationResponse.getValidation().getStatusMessage()); sb.append(";"); sb.append(certValidationResponse.getValidation().getRevokationReason()); sb.append(";"); final Date revocationDate = certValidationResponse.getValidation().getRevokedDate(); if (revocationDate != null) { sb.append(certValidationResponse.getValidation().getRevokedDate().getTime()); } responseText = sb.toString(); res.setContentType("text/plain"); res.setContentLength(responseText.getBytes().length); res.getOutputStream().write(responseText.getBytes()); } catch (CertificateException e) { LOG.error("Invalid certificate: " + e.getMessage()); sendBadRequest(res, "Invalid certificate: " + e.getMessage()); return; } break; } ; res.getOutputStream().close(); } catch (AuthorizationRequiredException e) { LOG.debug("Sending back HTTP 401: " + e.getLocalizedMessage()); final String httpAuthBasicRealm = "SignServer Worker " + workerId; res.setHeader(HTTP_AUTH_BASIC_WWW_AUTHENTICATE, "Basic realm=\"" + httpAuthBasicRealm + "\""); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required"); } catch (AccessDeniedException e) { LOG.debug("Sending back HTTP 403: " + e.getLocalizedMessage()); res.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied"); } catch (NoSuchWorkerException ex) { res.sendError(HttpServletResponse.SC_NOT_FOUND, "Worker Not Found"); } catch (IllegalRequestException e) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (CryptoTokenOfflineException e) { res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage()); } catch (ServiceUnavailableException e) { res.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage()); } catch (NotGrantedException e) { res.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (SignServerException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:ch.bfh.unicert.certimport.Certificate.java
/** * Create an object representing a X509 certificate with redundant information * @param cert the X509 certificate to store in the object * @param commonName the common name appearing in the given certificate * @param uniqueId the unique identifier appearing in the given certificate * @param organisation the organisation appearing in the given certificate * @param organisationUnit the organisation unit appearing in the given certificate * @param countryName the country appearing in the given certificate * @param state the state appearing in the given certificate * @param locality the locality appearing in the given certificate * @param surname the surname appearing in the given certificate * @param givenName the given name appearing in the given certificate * @param applicationIdentifier the identifier of the application the certificate is issued for * @param role the role the certificate is issued certificate * @param identityProvider the identity provider used to authenticate the requester of the certificate * @param extension the extension appearing in the given certificate * //ww w . ja v a2 s. c om * If some information does not appear in the certificate, null can be passed */ public Certificate(X509Certificate cert, String commonName, String uniqueId, String organisation, String organisationUnit, String countryName, String state, String locality, String surname, String givenName, String applicationIdentifier, String[] roles, String identityProvider, Map extension) { this.commonName = commonName; this.uniqueIdentifier = uniqueId; this.organisation = organisation; this.organisationUnit = organisationUnit; this.countryName = countryName; this.state = state; this.locality = locality; this.surname = surname; this.givenName = givenName; this.issuer = cert.getIssuerDN().getName(); this.serialNumber = cert.getSerialNumber(); this.validFrom = cert.getNotBefore(); this.validUntil = cert.getNotAfter(); this.applicationIdentifier = applicationIdentifier; this.roles = roles; this.identityProvider = identityProvider; this.extension = extension; try { this.pem = CertificateHelper.x509ToBase64PEMString(cert); } catch (IOException ex) { Logger.getLogger(Certificate.class.getName()).log(Level.SEVERE, null, ex); } this.cert = cert; }
From source file:eu.stork.peps.auth.engine.core.impl.SignHW.java
/** * @see//from ww w . java 2 s.com * eu.stork.peps.auth.engine.core.SAMLEngineSignI#sign(SignableSAMLObject tokenSaml) * @param tokenSaml signable SAML Object * @return the SAMLObject signed. * @throws SAMLEngineException error in sign token saml */ public SAMLObject sign(final SignableSAMLObject tokenSaml) throws SAMLEngineException { try { LOG.info("Star procces of sign"); final char[] pin = properties.getProperty("keyPassword").toCharArray(); storkOwnKeyStore.load(null, pin); final String serialNumber = properties.getProperty("serialNumber"); final String issuer = properties.getProperty("issuer"); String alias = null; 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); // Verified serial number, issuer final String serialNum = certificate.getSerialNumber().toString(16); X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName()); X509Principal issuerDNConf = new X509Principal(issuer); if (serialNum.equalsIgnoreCase(serialNumber) && X509PrincipalUtil.equals(issuerDN, issuerDNConf)) { alias = aliasCert; find = true; } } if (!find) { throw new SAMLEngineException("Certificate cannot be found in keystore "); } certificate = (X509Certificate) storkOwnKeyStore.getCertificate(alias); final PrivateKey privateKey = (PrivateKey) storkOwnKeyStore.getKey(alias, pin); LOG.info("Recover BasicX509Credential."); final BasicX509Credential credential = new BasicX509Credential(); LOG.debug("Load certificate"); credential.setEntityCertificate(certificate); LOG.debug("Load privateKey"); credential.setPrivateKey(privateKey); LOG.info("Star procces of sign"); final Signature signature = (Signature) org.opensaml.xml.Configuration.getBuilderFactory() .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME); LOG.debug("Begin signature with openSaml"); signature.setSigningCredential(credential); /*signature.setSignatureAlgorithm( SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);*/ signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); final SecurityConfiguration securityConf = org.opensaml.xml.Configuration .getGlobalSecurityConfiguration(); final NamedKeyInfoGeneratorManager keyInfoManager = securityConf.getKeyInfoGeneratorManager(); final KeyInfoGeneratorManager keyInfoGenManager = keyInfoManager.getDefaultManager(); final KeyInfoGeneratorFactory keyInfoGenFac = keyInfoGenManager.getFactory(credential); final KeyInfoGenerator keyInfoGenerator = keyInfoGenFac.newInstance(); final KeyInfo keyInfo = keyInfoGenerator.generate(credential); signature.setKeyInfo(keyInfo); LOG.debug("Set Canonicalization Algorithm"); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); //Create a second signature which will be used when signing assertion and response final Signature signature2 = (Signature) Configuration.getBuilderFactory() .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME); final SecurityConfiguration secConfiguration2 = Configuration.getGlobalSecurityConfiguration(); final NamedKeyInfoGeneratorManager keyInfoManager2 = secConfiguration2.getKeyInfoGeneratorManager(); final KeyInfoGeneratorManager keyInfoGenManager2 = keyInfoManager2.getDefaultManager(); final KeyInfoGeneratorFactory keyInfoGenFac2 = keyInfoGenManager2.getFactory(credential); final KeyInfoGenerator keyInfoGenerator2 = keyInfoGenFac2.newInstance(); KeyInfo keyInfo2 = keyInfoGenerator2.generate(credential); signature2.setSigningCredential(credential); signature2.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); signature2.setKeyInfo(keyInfo2); signature2.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); LOG.info("Marshall samlToken."); String qn = tokenSaml.getElementQName().toString(); if (qn.endsWith(CustomAttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME)) { tokenSaml.setSignature(signature); CustomAttributeQueryMarshaller mars = new CustomAttributeQueryMarshaller(); mars.marshall(tokenSaml); Signer.signObject(signature); } else if (qn.endsWith(Response.DEFAULT_ELEMENT_LOCAL_NAME) && !qn.contains(LogoutResponse.DEFAULT_ELEMENT_LOCAL_NAME)) { Response res = (Response) tokenSaml; List<Assertion> asserts = res.getAssertions(); //If multiple assertions we just sign the response and not the assertion if (asserts.size() > 1) { tokenSaml.setSignature(signature); Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); } //If single assertion we sign the assertion and response else { Assertion assertion = (Assertion) asserts.get(0); assertion.setSignature(signature); tokenSaml.setSignature(signature2); Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); Signer.signObject(signature2); } } //Normally we just sign the total saml response else { tokenSaml.setSignature(signature); Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); } } catch (final MarshallingException e) { LOG.error("MarshallingException"); throw new SAMLEngineException(e); } catch (final NoSuchAlgorithmException e) { LOG.error( "A 'xmldsig#rsa-sha1' cryptographic algorithm is requested but is not available in the environment."); throw new SAMLEngineException(e); } catch (final KeyStoreException e) { LOG.error("Generic KeyStore exception."); throw new SAMLEngineException(e); } catch (final SignatureException e) { LOG.error("Signature exception."); throw new SAMLEngineException(e); } catch (final SecurityException e) { LOG.error("Security exception."); throw new SAMLEngineException(e); } catch (final CertificateException e) { LOG.error("Certificate exception."); throw new SAMLEngineException(e); } catch (final IOException e) { LOG.error("IO exception."); throw new SAMLEngineException(e); } catch (final UnrecoverableKeyException e) { LOG.error("UnrecoverableKeyException exception."); throw new SAMLEngineException(e); } return tokenSaml; }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private X509Certificate FindCertByIssuer(String X509IssuerName, String X509SerialNumber) throws Exception { KeyStore ks = GetTrustStore(); if (ks == null) { return null; }/*from ww w . j a v a 2 s. co m*/ Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String nextElement = aliases.nextElement(); Certificate certificate = ks.getCertificate(nextElement); X509Certificate x = (X509Certificate) certificate; if (x.getIssuerDN().getName().equals(X509IssuerName) && x.getSerialNumber().toString().equalsIgnoreCase(X509SerialNumber)) { return x; } } return null; }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private void showCertMessage(String title, String msg, X509Certificate cert, String fingerprint) { Intent nIntent = new Intent(mContext, CertDisplayActivity.class); nIntent.putExtra("issuer", cert.getIssuerDN().getName()); nIntent.putExtra("subject", cert.getSubjectDN().getName()); if (fingerprint != null) nIntent.putExtra("fingerprint", fingerprint); SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.US); df.setTimeZone(TimeZone.getTimeZone("UTC")); nIntent.putExtra("issued", df.format(cert.getNotBefore()) + " GMT"); nIntent.putExtra("expires", df.format(cert.getNotAfter()) + " GMT"); nIntent.putExtra("msg", title + ": " + msg); showToolbarNotification(title, msg, DEFAULT_NOTIFY_ID, mAppIcon, Notification.FLAG_AUTO_CANCEL, nIntent); }
From source file:eu.stork.peps.auth.engine.core.impl.SignP12.java
/** * Sign the token SAML./*from www. ja va2s. co m*/ * * @param tokenSaml token SAML * * @return the X509Certificate signed. * * @throws SAMLEngineException error at sign SAML token * */ @Override public SAMLObject sign(final SignableSAMLObject tokenSaml) throws SAMLEngineException { LOG.info("Start Sign process"); try { final String serialNumber = properties.getProperty("serialNumber"); final String issuer = properties.getProperty("issuer"); String alias = null; String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = p12Store.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) p12Store.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(16); X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName()); X509Principal issuerDNConf = new X509Principal(issuer); if (serialNum.equalsIgnoreCase(serialNumber) && X509PrincipalUtil.equals(issuerDN, issuerDNConf)) { alias = aliasCert; find = true; } } certificate = (X509Certificate) p12Store.getCertificate(alias); final PrivateKey privateKey = (PrivateKey) p12Store.getKey(alias, properties.getProperty("keyPassword").toCharArray()); LOG.info("Recover BasicX509Credential."); final BasicX509Credential credential = new BasicX509Credential(); LOG.debug("Load certificate"); credential.setEntityCertificate(certificate); LOG.debug("Load privateKey"); credential.setPrivateKey(privateKey); LOG.debug("Begin signature with openSaml"); final Signature signature = (Signature) org.opensaml.xml.Configuration.getBuilderFactory() .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME); signature.setSigningCredential(credential); /*signature.setSignatureAlgorithm( SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);*/ signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); final SecurityConfiguration secConfiguration = org.opensaml.xml.Configuration .getGlobalSecurityConfiguration(); final NamedKeyInfoGeneratorManager keyInfoManager = secConfiguration.getKeyInfoGeneratorManager(); final KeyInfoGeneratorManager keyInfoGenManager = keyInfoManager.getDefaultManager(); final KeyInfoGeneratorFactory keyInfoGenFac = keyInfoGenManager.getFactory(credential); final KeyInfoGenerator keyInfoGenerator = keyInfoGenFac.newInstance(); final KeyInfo keyInfo = keyInfoGenerator.generate(credential); signature.setKeyInfo(keyInfo); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); //Create a second signature which will be used when signing assertion and response final Signature signature2 = (Signature) org.opensaml.xml.Configuration.getBuilderFactory() .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME); final SecurityConfiguration secConfiguration2 = org.opensaml.xml.Configuration .getGlobalSecurityConfiguration(); final NamedKeyInfoGeneratorManager keyInfoManager2 = secConfiguration2.getKeyInfoGeneratorManager(); final KeyInfoGeneratorManager keyInfoGenManager2 = keyInfoManager2.getDefaultManager(); final KeyInfoGeneratorFactory keyInfoGenFac2 = keyInfoGenManager2.getFactory(credential); final KeyInfoGenerator keyInfoGenerator2 = keyInfoGenFac2.newInstance(); KeyInfo keyInfo2 = keyInfoGenerator2.generate(credential); signature2.setSigningCredential(credential); signature2.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); signature2.setKeyInfo(keyInfo2); signature2.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); LOG.info("Marshall samlToken."); String qn = tokenSaml.getElementQName().toString(); if (qn.endsWith(CustomAttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME)) { tokenSaml.setSignature(signature); CustomAttributeQueryMarshaller mars = new CustomAttributeQueryMarshaller(); mars.marshall(tokenSaml); Signer.signObject(signature); } else if (qn.endsWith(Response.DEFAULT_ELEMENT_LOCAL_NAME) && !qn.contains(LogoutResponse.DEFAULT_ELEMENT_LOCAL_NAME)) { Response res = (Response) tokenSaml; List<Assertion> asserts = res.getAssertions(); //If multiple assertions we just sign the response and not the assertion if (asserts.size() > 1) { tokenSaml.setSignature(signature); org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml) .marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); } //If single assertion we sign the assertion and response else { Assertion assertion = asserts.get(0); assertion.setSignature(signature); tokenSaml.setSignature(signature2); org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml) .marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); Signer.signObject(signature2); } } //Normally we just sign the total saml response else { tokenSaml.setSignature(signature); org.opensaml.xml.Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); } } catch (MarshallingException e) { LOG.error("MarshallingException"); throw new SAMLEngineException(e); } catch (NoSuchAlgorithmException e) { LOG.error( "A 'xmldsig#rsa-sha1' cryptographic algorithm is requested but is not available in the environment."); throw new SAMLEngineException(e); } catch (KeyStoreException e) { LOG.error("Generic KeyStore exception."); throw new SAMLEngineException(e); } catch (SignatureException e) { LOG.error("Signature exception."); throw new SAMLEngineException(e); } catch (SecurityException e) { LOG.error("Security exception."); throw new SAMLEngineException(e); } catch (UnrecoverableKeyException e) { LOG.error("UnrecoverableKey exception."); throw new SAMLEngineException(e); } return tokenSaml; }
From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/*from www . j a v a 2 s.c om*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreID != null) { KeyStore keystore = createKeyStore(this.keystoreID); if (logger.isDebugEnabled()) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { logger.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; logger.debug(" Certificate " + (c + 1) + ":"); logger.debug(" Subject DN: " + cert.getSubjectDN()); logger.debug(" Signature Algorithm: " + cert.getSigAlgName()); logger.debug(" Valid from: " + cert.getNotBefore()); logger.debug(" Valid until: " + cert.getNotAfter()); logger.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keyPassword); } if (this.truststoreID != null) { KeyStore keystore = createKeyStore(this.truststoreID); if (logger.isDebugEnabled()) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); logger.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; logger.debug(" Subject DN: " + cert.getSubjectDN()); logger.debug(" Signature Algorithm: " + cert.getSigAlgName()); logger.debug(" Valid from: " + cert.getNotBefore()); logger.debug(" Valid until: " + cert.getNotAfter()); logger.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslctx = SSLContext.getInstance("SSL"); sslctx.init(keymanagers, trustmanagers, null); return sslctx; } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { logger.error(e.getMessage(), e); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { logger.error(e.getMessage(), e); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (Exception e) { logger.error(e.getMessage(), e); throw new AuthSSLInitializationError("Error reading keystore/truststore file: " + e.getMessage()); } }
From source file:eu.stork.peps.auth.engine.core.impl.SignSW.java
/** * Sign the token SAML.//ww w . java 2 s . c om * * @param tokenSaml the token SAML. * @return the SAML object * @throws SAMLEngineException the SAML engine exception */ public final SAMLObject sign(final SignableSAMLObject tokenSaml) throws SAMLEngineException { LOG.info("Start Sign process."); try { final String serialNumber = properties.getProperty("serialNumber"); final String issuer = properties.getProperty("issuer"); String alias = null; 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); try { X509Principal issuerDN = new X509Principal(certificate.getIssuerDN().getName()); X509Principal issuerDNConf = new X509Principal(issuer); if (serialNum.equalsIgnoreCase(serialNumber) && X509PrincipalUtil.equals(issuerDN, issuerDNConf)) { alias = aliasCert; find = true; } } catch (Exception ex) { LOG.error("Exception during signing: " + ex.getMessage()); // Added as a workaround for Bouncycastle email error } } if (!find) { throw new SAMLEngineException("Certificate cannot be found in keystore "); } certificate = (X509Certificate) storkOwnKeyStore.getCertificate(alias); final PrivateKey privateKey = (PrivateKey) storkOwnKeyStore.getKey(alias, properties.getProperty("keyPassword").toCharArray()); LOG.info("Recover BasicX509Credential."); final BasicX509Credential credential = new BasicX509Credential(); LOG.debug("Load certificate"); credential.setEntityCertificate(certificate); LOG.debug("Load privateKey"); credential.setPrivateKey(privateKey); LOG.debug("Begin signature with openSaml"); final Signature signature = (Signature) Configuration.getBuilderFactory() .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME); signature.setSigningCredential(credential); signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); //signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); final SecurityConfiguration secConfiguration = Configuration.getGlobalSecurityConfiguration(); final NamedKeyInfoGeneratorManager keyInfoManager = secConfiguration.getKeyInfoGeneratorManager(); final KeyInfoGeneratorManager keyInfoGenManager = keyInfoManager.getDefaultManager(); final KeyInfoGeneratorFactory keyInfoGenFac = keyInfoGenManager.getFactory(credential); final KeyInfoGenerator keyInfoGenerator = keyInfoGenFac.newInstance(); KeyInfo keyInfo = keyInfoGenerator.generate(credential); signature.setKeyInfo(keyInfo); signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); //Create a second signature which will be used when signing assertion and response final Signature signature2 = (Signature) Configuration.getBuilderFactory() .getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME); final SecurityConfiguration secConfiguration2 = Configuration.getGlobalSecurityConfiguration(); final NamedKeyInfoGeneratorManager keyInfoManager2 = secConfiguration2.getKeyInfoGeneratorManager(); final KeyInfoGeneratorManager keyInfoGenManager2 = keyInfoManager2.getDefaultManager(); final KeyInfoGeneratorFactory keyInfoGenFac2 = keyInfoGenManager2.getFactory(credential); final KeyInfoGenerator keyInfoGenerator2 = keyInfoGenFac2.newInstance(); KeyInfo keyInfo2 = keyInfoGenerator2.generate(credential); signature2.setSigningCredential(credential); signature2.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); //signature2.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); signature2.setKeyInfo(keyInfo2); signature2.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); LOG.info("Marshall samlToken."); String qn = tokenSaml.getElementQName().toString(); if (qn.endsWith(CustomAttributeQuery.DEFAULT_ELEMENT_LOCAL_NAME)) { tokenSaml.setSignature(signature); CustomAttributeQueryMarshaller mars = new CustomAttributeQueryMarshaller(); mars.marshall(tokenSaml); Signer.signObject(signature); } else if (qn.endsWith(Response.DEFAULT_ELEMENT_LOCAL_NAME) && !qn.contains(LogoutResponse.DEFAULT_ELEMENT_LOCAL_NAME)) { Response res = (Response) tokenSaml; List<Assertion> asserts = res.getAssertions(); //If multiple assertions we just sign the response and not the assertion if (asserts.size() > 1) { tokenSaml.setSignature(signature); Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); } //If single assertion we sign the assertion and response else { Assertion assertion = (Assertion) asserts.get(0); assertion.setSignature(signature); tokenSaml.setSignature(signature2); Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); Signer.signObject(signature2); } } //Normally we just sign the total saml response else { tokenSaml.setSignature(signature); Configuration.getMarshallerFactory().getMarshaller(tokenSaml).marshall(tokenSaml); LOG.info("Sign samlToken."); Signer.signObject(signature); } } catch (MarshallingException e) { LOG.error("MarshallingException"); throw new SAMLEngineException(e); } catch (NoSuchAlgorithmException e) { LOG.error( "A 'xmldsig#rsa-sha1' cryptographic algorithm is requested but is not available in the environment."); throw new SAMLEngineException(e); } catch (KeyStoreException e) { LOG.error("Generic KeyStore exception."); throw new SAMLEngineException(e); } catch (SignatureException e) { LOG.error("Signature exception."); throw new SAMLEngineException(e); } catch (SecurityException e) { LOG.error("Security exception."); throw new SAMLEngineException(e); } catch (UnrecoverableKeyException e) { LOG.error("UnrecoverableKey exception."); throw new SAMLEngineException(e); } return tokenSaml; }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private X509Certificate findCertIssuerInStore(X509Certificate x509cert, KeyStore kStore) throws CertificateException { X509Certificate x509issuer = null; debug("searching store for issuer: " + x509cert.getIssuerDN()); // check in our local root CA Store Enumeration<String> enumAliases; try {/*from ww w .j a v a2s . c om*/ enumAliases = kStore.aliases(); X509Certificate x509search = null; while (enumAliases.hasMoreElements()) { x509search = (X509Certificate) kStore.getCertificate(enumAliases.nextElement()); if (checkSubjectMatchesIssuer(x509search.getSubjectX500Principal(), x509cert.getIssuerX500Principal())) { x509issuer = x509search; debug("found issuer for current cert in chain in ROOT CA store: " + x509issuer.getSubjectDN()); break; } } } catch (KeyStoreException e) { String errMsg = mContext.getString(R.string.error_problem_access_local_root_ca_store); debug(errMsg); throw new CertificateException(errMsg); } return x509issuer; }