List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
private String getAliasForX509Cert(String issuer, BigInteger serialNumber, boolean useSerialNumber) throws WSSecurityException { Object issuerName = null;//from ww w . j a v a2s . co m Certificate cert = null; if (keystore == null) { return null; } // // Convert the issuer DN to a java X500Principal object first. This is to ensure // interop with a DN constructed from .NET, where e.g. it uses "S" instead of "ST". // Then convert it to a BouncyCastle X509Name, which will order the attributes of // the DN in a particular way (see WSS-168). If the conversion to an X500Principal // object fails (e.g. if the DN contains "E" instead of "EMAILADDRESS"), then fall // back on a direct conversion to a BC X509Name // try { X500Principal issuerRDN = new X500Principal(issuer); issuerName = createBCX509Name(issuerRDN.getName()); } catch (java.lang.IllegalArgumentException ex) { issuerName = createBCX509Name(issuer); } try { for (Enumeration e = keystore.aliases(); e.hasMoreElements();) { String alias = (String) e.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keystore.getCertificate(alias); if (cert == null) { continue; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } X509Certificate x509cert = (X509Certificate) cert; if (!useSerialNumber || x509cert.getSerialNumber().compareTo(serialNumber) == 0) { Object certName = createBCX509Name(x509cert.getIssuerX500Principal().getName()); if (certName.equals(issuerName)) { return alias; } } } } catch (KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e); } return null; }
From source file:be.fedict.eid.applet.service.signer.facets.KeyInfoSignatureFacet.java
public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) { LOG.debug("postSign"); String signatureNamespacePrefix = signatureElement.getPrefix(); /*// w w w .j a v a 2s .c om * Make sure we insert right after the ds:SignatureValue element, just * before the first ds:Object element. */ Node nextSibling; NodeList objectNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object"); if (0 == objectNodeList.getLength()) { nextSibling = null; } else { nextSibling = objectNodeList.item(0); } /* * Construct the ds:KeyInfo element using JSR 105. */ KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI()); List<Object> x509DataObjects = new LinkedList<Object>(); X509Certificate signingCertificate = signingCertificateChain.get(0); List<Object> keyInfoContent = new LinkedList<Object>(); if (this.includeKeyValue) { KeyValue keyValue; try { keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey()); } catch (KeyException e) { throw new RuntimeException("key exception: " + e.getMessage(), e); } keyInfoContent.add(keyValue); } if (this.includeIssuerSerial) { x509DataObjects.add(keyInfoFactory.newX509IssuerSerial( signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber())); } if (this.includeEntireCertificateChain) { for (X509Certificate certificate : signingCertificateChain) { x509DataObjects.add(certificate); } } else { x509DataObjects.add(signingCertificate); } if (false == x509DataObjects.isEmpty()) { X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); } KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo; Key key = new Key() { private static final long serialVersionUID = 1L; public String getAlgorithm() { return null; } public byte[] getEncoded() { return null; } public String getFormat() { return null; } }; XMLSignContext xmlSignContext = new DOMSignContext(key, signatureElement); DOMCryptoContext domCryptoContext = (DOMCryptoContext) xmlSignContext; try { domKeyInfo.marshal(signatureElement, nextSibling, signatureNamespacePrefix, domCryptoContext); } catch (MarshalException e) { throw new RuntimeException("marshall error: " + e.getMessage(), e); } }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java
/** * Tests ocsp message// w w w. j a va 2s .co m * * @throws Exception * error */ @Test public void test03OcspRevoked() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); final X509Certificate ocspTestCert = getRevokedTestCert(); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), getCaCert(ocspTestCert), ocspTestCert.getSerialNumber())); OCSPReq req = gen.build(); // Send the request and receive a singleResponse SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), null, 0, 200); assertEquals("No of SingResps should be 1.", 1, singleResps.length); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertTrue("Status (" + status + ") is not RevokedStatus", status instanceof RevokedStatus); RevokedStatus rev = (RevokedStatus) status; assertTrue("Status does not have reason", rev.hasRevocationReason()); }
From source file:com.fine47.http.SecureSocketFactory.java
private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); ActivityHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Found expired SSL certificate in this store: " + factoryId); }//from www . j a v a2 s. c o m // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; // Get the public key. publicKey = rootca.getPublicKey(); sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid"); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid"); } else try { for (X509Certificate cert : chain) { if (ActivityHttpClient.isDebugging()) { Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:"); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion()); Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); } // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's chain. cert.verify(publicKey); } } catch (InvalidKeyException ex) { error = ex; } catch (NoSuchAlgorithmException ex) { error = ex; } catch (NoSuchProviderException ex) { error = ex; } catch (SignatureException ex) { error = ex; } if (null != error && ActivityHttpClient.isDebugging()) { Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
From source file:eu.stork.peps.auth.engine.core.impl.SignHW.java
/** * @see/*from w w w. ja va 2 s . c om*/ * 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:eu.stork.peps.auth.engine.core.impl.SignSW.java
/** * Sign the token SAML./*from ww w . java 2 s. c o m*/ * * @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:eu.stork.peps.auth.engine.core.impl.SignP12.java
/** * Sign the token SAML./* w w w .j a va2 s . 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: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); }//from ww w . j a va 2 s. co 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:es.mityc.firmaJava.libreria.pkcs7.ValidaTarjeta.java
public String getAlias(X509Certificate cert) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { String alias = null;/*from ww w. j av a 2 s . c o m*/ Enumeration aliasesEnum; aliasesEnum = ks.aliases(); X509Certificate certKeyStore = null; if (aliasesEnum != null) { while (aliasesEnum.hasMoreElements()) { alias = (String) aliasesEnum.nextElement(); certKeyStore = (X509Certificate) ks.getCertificate(alias); if (certKeyStore.getSerialNumber().equals(cert.getSerialNumber())) { break; } } } return alias; }
From source file:es.mityc.firmaJava.libreria.pkcs7.ValidaTarjeta.java
public PrivateKey getPrivateKey(X509Certificate cert) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { pk = null;// w w w . j a va 2 s .c om String alias = null; Enumeration aliasesEnum; aliasesEnum = ks.aliases(); X509Certificate certKeyStore = null; if (aliasesEnum != null) { while (aliasesEnum.hasMoreElements()) { alias = (String) aliasesEnum.nextElement(); certKeyStore = (X509Certificate) ks.getCertificate(alias); if (certKeyStore.getSerialNumber().equals(cert.getSerialNumber())) { pk = (PrivateKey) ks.getKey(alias, jPinPasswordField.getPassword()); } } } return pk; }