org.apache.xml.security.signature.XMLSignature Java Examples

The following examples show how to use org.apache.xml.security.signature.XMLSignature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SAMLSignatureProfileValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validate an instance of {@link SignatureImpl}, which is in turn based on underlying Apache XML Security
 * <code>XMLSignature</code> instance.
 * 
 * @param sigImpl the signature implementation object to validate
 * @throws ValidationException thrown if the signature is not valid with respect to the profile
 */
protected void validateSignatureImpl(SignatureImpl sigImpl) throws ValidationException {

    if (sigImpl.getXMLSignature() == null) {
        log.error("SignatureImpl did not contain the an Apache XMLSignature child");
        throw new ValidationException("Apache XMLSignature does not exist on SignatureImpl");
    }
    XMLSignature apacheSig = sigImpl.getXMLSignature();

    if (!(sigImpl.getParent() instanceof SignableSAMLObject)) {
        log.error("Signature is not an immedidate child of a SignableSAMLObject");
        throw new ValidationException("Signature is not an immediate child of a SignableSAMLObject.");
    }
    SignableSAMLObject signableObject = (SignableSAMLObject) sigImpl.getParent();

    Reference ref = validateReference(apacheSig);

    String uri = ref.getURI();
    
    validateReferenceURI(uri, signableObject);

    validateTransforms(ref);
    
    validateObjectChildren(apacheSig);
}
 
Example #2
Source File: KeyInfoBuilderTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSignKeyInfo() throws Exception
{
    System.out.println("signKeyInfo");

    KeyInfoBuilder keyInfoBuilder = new KeyInfoBuilder(
            new BasicSignatureOptions().signKeyInfo(true),
            new TestAlgorithmsProvider(),
            new TestAlgorithmsParametersMarshallingProvider(),
            new DefaultX500NameStyleProvider());
    XMLSignature xmlSignature = getTestSignature();

    keyInfoBuilder.buildKeyInfo(certificates, xmlSignature);

    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    Assert.assertEquals(1, signedInfo.getLength());

    Node refNode = signedInfo.item(0).getContentsBeforeTransformation().getSubNode();
    Assert.assertSame(xmlSignature.getKeyInfo().getElement(), refNode);
}
 
Example #3
Source File: SAMLSignatureProfileValidator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validate the Signature's SignedInfo Reference.
 * 
 * The SignedInfo must contain exactly 1 Reference.
 * 
 * @param apacheSig the Apache XML Signature instance
 * @return the valid Reference contained within the SignedInfo
 * @throws ValidationException thrown if the Signature does not contain exactly 1 Reference, or if there is an error
 *             obtaining the Reference instance
 */
protected Reference validateReference(XMLSignature apacheSig) throws ValidationException {
    int numReferences = apacheSig.getSignedInfo().getLength();
    if (numReferences != 1) {
        log.error("Signature SignedInfo had invalid number of References: " + numReferences);
        throw new ValidationException("Signature SignedInfo must have exactly 1 Reference element");
    }

    Reference ref = null;
    try {
        ref = apacheSig.getSignedInfo().item(0);
    } catch (XMLSecurityException e) {
        log.error("Apache XML Security exception obtaining Reference", e);
        throw new ValidationException("Could not obtain Reference from Signature/SignedInfo", e);
    }
    if (ref == null) {
        log.error("Signature Reference was null");
        throw new ValidationException("Signature Reference was null");
    }
    return ref;
}
 
Example #4
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void addOptionalAfterSignatureParts(UnsignedPropertiesBuilder unsignedProps, XMLSignature sig, String uuid, Map<String, Object> options) throws TechnicalConnectorException {
   try {
      X509Certificate signing = sig.getKeyInfo().getX509Certificate();
      OCSPData ocsp = (OCSPData)OCSPCheckerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.RECEIVER_MANDATORY).build().validate(signing).getData();
      unsignedProps.addCertificate(signing);
      Iterator i$ = ocsp.getCrls().iterator();

      while(i$.hasNext()) {
         X509CRL crl = (X509CRL)i$.next();
         unsignedProps.addCrlRef(crl);
      }

      unsignedProps.addOCSPRef(this.convertToOCSPResp(ocsp));
   } catch (Exception var9) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{"Unable to add optional Signature parts"});
   }
}
 
Example #5
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void addOptionalAfterSignatureParts(UnsignedPropertiesBuilder unsignedProps, XMLSignature sig, String uuid, Map<String, Object> options) throws TechnicalConnectorException {
   try {
      X509Certificate signing = sig.getKeyInfo().getX509Certificate();
      OCSPData ocsp = (OCSPData)OCSPCheckerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.RECEIVER_MANDATORY).build().validate(signing).getData();
      unsignedProps.addCertificate(signing);
      Iterator i$ = ocsp.getCrls().iterator();

      while(i$.hasNext()) {
         X509CRL crl = (X509CRL)i$.next();
         unsignedProps.addCrlRef(crl);
      }

      unsignedProps.addOCSPRef(this.convertToOCSPResp(ocsp));
   } catch (Exception var9) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{"Unable to add optional Signature parts"});
   }
}
 
Example #6
Source File: SignKeyDataHolder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public SignKeyDataHolder() throws Exception {
    try {
        String keyAlias = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.KeyAlias");
        KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);
        Certificate[] certificates = keyMan.getPrimaryKeyStore().getCertificateChain(keyAlias);
        issuerPK = keyMan.getDefaultPrivateKey();
        issuerCerts = new X509Certificate[certificates.length];
        int i = 0;
        for (Certificate certificate : certificates) {
            issuerCerts[i++] = (X509Certificate) certificate;
        }
        signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA;
        String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
            signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA;
        }

    } catch (Exception e) {
        throw new Exception("Error while reading the key", e);
    }

}
 
Example #7
Source File: XadesCSpecification.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void addOptionalAfterSignatureParts(UnsignedPropertiesBuilder unsignedProps, XMLSignature sig, String uuid, Map<String, Object> options) throws TechnicalConnectorException {
   try {
      X509Certificate signing = sig.getKeyInfo().getX509Certificate();
      OCSPData ocsp = (OCSPData)OCSPCheckerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.RECEIVER_MANDATORY).build().validate(signing).getData();
      unsignedProps.addCertificate(signing);
      Iterator i$ = ocsp.getCrls().iterator();

      while(i$.hasNext()) {
         X509CRL crl = (X509CRL)i$.next();
         unsignedProps.addCrlRef(crl);
      }

      unsignedProps.addOCSPRef(this.convertToOCSPResp(ocsp));
   } catch (Exception var9) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var9, new Object[]{"Unable to add optional Signature parts"});
   }
}
 
Example #8
Source File: KeyInfoBuilderTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testIncludeCertChain() throws Exception
{
    System.out.println("includeCertChain");

    KeyInfoBuilder keyInfoBuilder = new KeyInfoBuilder(
            new BasicSignatureOptions().includeSigningCertificate(SigningCertificateMode.FULL_CHAIN),
            new TestAlgorithmsProvider(),
            new TestAlgorithmsParametersMarshallingProvider(),
            new DefaultX500NameStyleProvider());
    XMLSignature xmlSignature = getTestSignature();

    keyInfoBuilder.buildKeyInfo(certificates, xmlSignature);

    Assert.assertEquals(0, xmlSignature.getSignedInfo().getLength());
    
    Assert.assertEquals(1, xmlSignature.getKeyInfo().lengthX509Data());
    Assert.assertEquals(2, xmlSignature.getKeyInfo().itemX509Data(0).lengthCertificate());

    XMLX509Certificate x509Certificate = xmlSignature.getKeyInfo().itemX509Data(0).itemCertificate(0);
    Assert.assertEquals(testCertificate, x509Certificate.getX509Certificate());
    
    x509Certificate = xmlSignature.getKeyInfo().itemX509Data(0).itemCertificate(1);
    Assert.assertEquals(intermCertificate, x509Certificate.getX509Certificate());
}
 
Example #9
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyXmlDsigSignature(SignatureVerificationResult result, Element sigElement, Document signedContent, Map<String, Object> options) {
   try {
      String uri = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XMLSignature xmlSignature = new XMLSignature(sigElement, uri);
      Boolean followNestedManifest = (Boolean)SignatureUtils.getOption("followNestedManifest", options, Boolean.FALSE);
      xmlSignature.setFollowNestedManifests(followNestedManifest.booleanValue());
      xmlSignature.addResourceResolver(new DocumentResolver(signedContent));
      KeyInfo keyInfo = xmlSignature.getKeyInfo();
      keyInfo.setSecureValidation(false);
      Extractor extractor = new X509DataExctractor();
      result.getCertChain().addAll(extractor.extract(keyInfo));
      X509Certificate signingCert = this.extractEndCertificate(result.getCertChain());
      result.setSigningCert(signingCert);
      if (!xmlSignature.checkSignatureValue(signingCert)) {
         result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
      }
   } catch (Exception var11) {
      LOG.error("Unable to verify XmlDsig Signature", var11);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

}
 
Example #10
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void addKeyInfo(Credential signatureCredential, XMLSignature sig) throws TechnicalConnectorException, XMLSecurityException {
   if (signatureCredential.getCertificateChain() != null) {
      Certificate[] arr$ = signatureCredential.getCertificateChain();
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Certificate cert = arr$[i$];
         if (sig.getKeyInfo().itemX509Data(0) == null) {
            X509Data x509data = new X509Data(sig.getDocument());
            sig.getKeyInfo().add(x509data);
         }

         sig.getKeyInfo().itemX509Data(0).addCertificate((X509Certificate)cert);
      }
   }

}
 
Example #11
Source File: KeyInfoBuilderTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testIncludeIssuerSerial() throws Exception
{
    System.out.println("includeIssuerSerial");

    KeyInfoBuilder keyInfoBuilder = new KeyInfoBuilder(
            new BasicSignatureOptions().includeIssuerSerial(true),
            new TestAlgorithmsProvider(),
            new TestAlgorithmsParametersMarshallingProvider(),
            new DefaultX500NameStyleProvider());
    XMLSignature xmlSignature = getTestSignature();

    keyInfoBuilder.buildKeyInfo(certificates, xmlSignature);

    Assert.assertEquals(1, xmlSignature.getKeyInfo().lengthX509Data());
    Assert.assertEquals(1, xmlSignature.getKeyInfo().itemX509Data(0).lengthIssuerSerial());
}
 
Example #12
Source File: XmlSigOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private XMLSignature prepareEnvelopedSignature(Document doc,
        String id,
        String referenceURI,
        String sigAlgo,
        String digestAlgo) throws Exception {
    doc.getDocumentElement().setAttributeNS(null, "Id", id);
    doc.getDocumentElement().setIdAttributeNS(null, "Id", true);

    XMLSignature sig = new XMLSignature(doc, "", sigAlgo);
    doc.getDocumentElement().appendChild(sig.getElement());
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);

    sig.addDocument(referenceURI, transforms, digestAlgo);
    return sig;
}
 
Example #13
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void verifyXmlDsigSignature(SignatureVerificationResult result, Element sigElement, Document signedContent, Map<String, Object> options) {
   try {
      String uri = IdGeneratorFactory.getIdGenerator("uuid").generateId();
      XMLSignature xmlSignature = new XMLSignature(sigElement, uri);
      Boolean followNestedManifest = (Boolean)SignatureUtils.getOption("followNestedManifest", options, Boolean.FALSE);
      xmlSignature.setFollowNestedManifests(followNestedManifest);
      xmlSignature.addResourceResolver(new DocumentResolver(signedContent));
      KeyInfo keyInfo = xmlSignature.getKeyInfo();
      keyInfo.setSecureValidation(false);
      Extractor extractor = new X509DataExctractor();
      result.getCertChain().addAll(extractor.extract(keyInfo));
      X509Certificate signingCert = this.extractEndCertificate(result.getCertChain());
      result.setSigningCert(signingCert);
      if (!xmlSignature.checkSignatureValue(signingCert)) {
         result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
      }
   } catch (Exception var11) {
      LOG.error("Unable to verify XmlDsig Signature", var11);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

}
 
Example #14
Source File: KeyInfoBuilderTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testIncludeCertAndKey() throws Exception
{
    System.out.println("includeCertAndKey");

    KeyInfoBuilder keyInfoBuilder = new KeyInfoBuilder(
            new BasicSignatureOptions().includeSigningCertificate(SigningCertificateMode.SIGNING_CERTIFICATE).includePublicKey(true),
            new TestAlgorithmsProvider(),
            new TestAlgorithmsParametersMarshallingProvider(),
            new DefaultX500NameStyleProvider());
    XMLSignature xmlSignature = getTestSignature();

    keyInfoBuilder.buildKeyInfo(certificates, xmlSignature);

    Assert.assertEquals(0, xmlSignature.getSignedInfo().getLength());

    KeyValue kv = xmlSignature.getKeyInfo().itemKeyValue(0);
    Assert.assertTrue(kv.getPublicKey().getAlgorithm().startsWith("RSA"));

    XMLX509Certificate x509Certificate = xmlSignature.getKeyInfo().itemX509Data(0).itemCertificate(0);
    Assert.assertEquals(testCertificate, x509Certificate.getX509Certificate());
}
 
Example #15
Source File: XadesSignatureFormatExtenderImplTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testEnrichSignatureWithA() throws Exception
{
    System.out.println("enrichSignatureWithA");

    Document doc = getDocument("document.verified.c.xl.xml");
    Element signatureNode = (Element)doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature").item(0);

    XadesSignatureFormatExtenderImpl instance = (XadesSignatureFormatExtenderImpl)new XadesFormatExtenderProfile().getFormatExtender();
    XMLSignature sig = new XMLSignature(signatureNode, "");
    Collection<UnsignedSignatureProperty> usp = new ArrayList<UnsignedSignatureProperty>(1);
    usp.add(new ArchiveTimeStampProperty());

    instance.enrichSignature(sig, new UnsignedProperties(usp));

    outputDocument(doc, "document.verified.c.xl.a.xml");
}
 
Example #16
Source File: SignedDataObjectsProcessorTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testAddNullReference() throws Exception
{
    System.out.println("addNullReference");

    Document doc = SignatureServicesTestBase.getNewDocument();

    SignedDataObjects dataObjsDescs = new SignedDataObjects()
        .withSignedDataObject(new AnonymousDataObjectReference("data".getBytes()));

    XMLSignature xmlSignature = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
    xmlSignature.setId("sigId");

    SignedDataObjectsProcessor processor = new SignedDataObjectsProcessor(new TestAlgorithmsProvider(), new AllwaysNullAlgsParamsMarshaller());
    Map<DataObjectDesc, Reference> result = processor.process(dataObjsDescs, xmlSignature);

    assertEquals(1, result.size());
    assertEquals(0, xmlSignature.getObjectLength());
    assertEquals(1, xmlSignature.getSignedInfo().getLength());

    Reference r = xmlSignature.getSignedInfo().item(0);
    assertNull(r.getElement().getAttributeNodeNS(Constants.SignatureSpecNS, "URI"));
}
 
Example #17
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteArrayToSign, Map<String, Object> options) throws TechnicalConnectorException {
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, byteArrayToSign);

   try {
      String xmldsigId = "xmldsig-" + IdGeneratorFactory.getIdGenerator("uuid").generateId();
      String baseURI = (String)SignatureUtils.getOption("baseURI", optionMap, "");
      String signatureMethodURI = (String)SignatureUtils.getOption("signatureMethodURI", optionMap, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
      String canonicalizationMethodURI = (String)SignatureUtils.getOption("canonicalizationMethodURI", optionMap, "http://www.w3.org/2001/10/xml-exc-c14n#");
      String digestURI = (String)SignatureUtils.getOption("digestURI", optionMap, "http://www.w3.org/2001/04/xmlenc#sha256");
      String encapsulateLocation = (String)SignatureUtils.getOption("encapsulate-xpath", optionMap, (Object)null);
      EncapsulationTransformer encapsulationTranformer = (EncapsulationTransformer)SignatureUtils.getOption("encapsulate-transformer", optionMap, new XmlSignatureBuilder.PassthroughEncapsulationTransformer());
      List<String> transformerList = getTransformerList(optionMap);
      Document doc = ConnectorXmlUtils.toDocument(byteArrayToSign);
      XMLSignature sig = new XMLSignature(doc, baseURI, signatureMethodURI, canonicalizationMethodURI);
      sig.addResourceResolver(new DocumentResolver(doc));
      sig.addDocument(ref(baseURI), transforms(transformerList, doc), digestURI);
      addKeyInfo(signatureCredential, sig);
      XadesHandler handler = new XadesHandler(sig, signatureCredential, options, this.specs);
      handler.before();
      sig.sign(signatureCredential.getPrivateKey());
      sig.setId(xmldsigId);
      handler.after();
      return transform(mustEncapsulate(transformerList), encapsulateLocation, encapsulationTranformer, doc, sig);
   } catch (Exception var16) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var16, new Object[]{var16.getMessage()});
   }
}
 
Example #18
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdPMetadataDefault() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort()
        + "/fediz-idp/metadata";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setSSLClientCertificate(
        this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks");

    final XmlPage rpPage = webClient.getPage(url);
    final String xmlContent = rpPage.asXml();
    Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor"));

    // Now validate the Signature
    Document doc = rpPage.getXmlDocument();

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    Node signatureNode =
        DOMUtils.getChild(doc.getDocumentElement(), "Signature");
    Assert.assertNotNull(signatureNode);

    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

    webClient.close();
}
 
Example #19
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteArrayToSign, Map<String, Object> options) throws TechnicalConnectorException {
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, byteArrayToSign);

   try {
      String xmldsigId = "xmldsig-" + IdGeneratorFactory.getIdGenerator("uuid").generateId();
      String baseURI = (String)SignatureUtils.getOption("baseURI", optionMap, "");
      String signatureMethodURI = (String)SignatureUtils.getOption("signatureMethodURI", optionMap, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
      String canonicalizationMethodURI = (String)SignatureUtils.getOption("canonicalizationMethodURI", optionMap, "http://www.w3.org/2001/10/xml-exc-c14n#");
      String digestURI = (String)SignatureUtils.getOption("digestURI", optionMap, "http://www.w3.org/2001/04/xmlenc#sha256");
      String encapsulateLocation = (String)SignatureUtils.getOption("encapsulate-xpath", optionMap, (Object)null);
      EncapsulationTransformer encapsulationTranformer = (EncapsulationTransformer)SignatureUtils.getOption("encapsulate-transformer", optionMap, new XmlSignatureBuilder.PassthroughEncapsulationTransformer());
      List<String> transformerList = getTransformerList(optionMap);
      Document doc = ConnectorXmlUtils.toDocument(byteArrayToSign);
      XMLSignature sig = new XMLSignature(doc, baseURI, signatureMethodURI, canonicalizationMethodURI);
      sig.addResourceResolver(new DocumentResolver(doc));
      sig.addDocument(ref(baseURI), transforms(transformerList, doc), digestURI);
      addKeyInfo(signatureCredential, sig);
      XadesHandler handler = new XadesHandler(sig, signatureCredential, options, this.specs);
      handler.before();
      sig.sign(signatureCredential.getPrivateKey());
      sig.setId(xmldsigId);
      handler.after();
      return transform(mustEncapsulate(transformerList), encapsulateLocation, encapsulationTranformer, doc, sig);
   } catch (Exception var16) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var16, new Object[]{var16.getMessage()});
   }
}
 
Example #20
Source File: XadesVerifierImpl.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Date getValidationDate(
        Collection<PropertyDataObject> qualifPropsData,
        XMLSignature signature,
        SignatureSpecificVerificationOptions verificationOptions) throws XAdES4jException
{
    List sigTsData = CollectionUtils.filterByType(qualifPropsData, SignatureTimeStampData.class);

    // If no signature time-stamp is present, use the current date.
    if (sigTsData.isEmpty())
    {
        return verificationOptions.getDefaultVerificationDate();
    }

    // TODO support multiple SignatureTimeStamps (section 7.3 last paragraph of Standard v.1.4.2)
    // This is a temporary solution.
    // - Properties should probably be verified in two stages (before and after cert path creation).
    // - Had to remove the custom structure verifier that checked if the SigningCertificate data was present.
    QualifyingPropertyVerificationContext ctx = new QualifyingPropertyVerificationContext(
            signature,
            new QualifyingPropertyVerificationContext.CertificationChainData(
            new ArrayList<X509Certificate>(0),
            new ArrayList<X509CRL>(0),
            null,
            this.x500NameStyleProvider),
            /**/
            new QualifyingPropertyVerificationContext.SignedObjectsData(
            new ArrayList<RawDataObjectDesc>(0),
            signature));
    Collection<PropertyInfo> props = this.qualifyingPropertiesVerifier.verifyProperties(sigTsData, ctx);
    QualifyingProperty sigTs = props.iterator().next().getProperty();

    return ((SignatureTimeStampProperty) sigTs).getTime();
}
 
Example #21
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static byte[] transform(boolean encapsulate, String xpathLocation, EncapsulationTransformer encapsulationTranformer, Document doc, XMLSignature sig) {
   if (!encapsulate) {
      return ConnectorXmlUtils.toByteArray((Node)sig.getElement());
   } else {
      Node toInsert = doc.adoptNode(encapsulationTranformer.transform(sig.getElement()));
      Node insertBeforeNode = null;
      if (StringUtils.isNotBlank(xpathLocation)) {
         try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList)xPath.evaluate(xpathLocation, doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() == 1) {
               LOG.debug("1 node found, inserting at location [" + xpathLocation + "]");
               insertBeforeNode = nodes.item(0);
            } else {
               LOG.warn("XPATH error: " + nodes.getLength() + "found at location [" + xpathLocation + "],using default.");
            }
         } catch (XPathExpressionException var9) {
            LOG.info("Unable to determine XPath Location, using default.", var9);
         }
      } else {
         LOG.debug("Using default location (last child tag)");
      }

      doc.getFirstChild().insertBefore(toInsert, insertBeforeNode);
      return ConnectorXmlUtils.toByteArray((Node)doc);
   }
}
 
Example #22
Source File: AuthenticationRequestBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Generate an authentication request with passive support.
 *
 * @return AuthnRequest Object
 * @throws Exception
 */
public AuthnRequest buildAuthenticationRequest(String subjectName, String nameIdPolicyFormat, boolean isPassive)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Building Authentication Request");
    }
    Util.doBootstrap();
    AuthnRequest authnRequest = (AuthnRequest) Util
            .buildXMLObject(AuthnRequest.DEFAULT_ELEMENT_NAME);
    authnRequest.setID(Util.createID());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(buildIssuer());
    authnRequest.setNameIDPolicy(buildNameIDPolicy(nameIdPolicyFormat));
    authnRequest.setIsPassive(isPassive);
    authnRequest.setDestination(Util.getIdentityProviderSSOServiceURL());
    String acs = Util.getAssertionConsumerServiceURL();
    if (acs != null && acs.trim().length() > 0) {
        authnRequest.setAssertionConsumerServiceURL(acs);
    } else {
        authnRequest.setAssertionConsumerServiceURL(CarbonUIUtil.getAdminConsoleURL("").replace("carbon/", "acs"));
    }

    if (subjectName != null) {
        Subject subject = new SubjectBuilder().buildObject();
        NameID nameId = new NameIDBuilder().buildObject();
        nameId.setValue(subjectName);
        nameId.setFormat(NameIdentifier.EMAIL);
        subject.setNameID(nameId);
        authnRequest.setSubject(subject);

    }

    Util.setSignature(authnRequest, XMLSignature.ALGO_ID_SIGNATURE_RSA, new SignKeyDataHolder());

    return authnRequest;
}
 
Example #23
Source File: SAMLMetaDataTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void validateMetaDataWithAlias() throws ProcessingException, XMLSignatureException, XMLSecurityException {

    FedizContext config = loadConfig("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(2);
    EasyMock.expect(req.getContextPath()).andReturn(CONTEXT_PATH).times(2);
    EasyMock.replay(req);

    Document doc = wfProc.getMetaData(req, config);
    Assert.assertNotNull(doc);

    Node signatureNode = doc.getElementsByTagName("Signature").item(0);
    Assert.assertNotNull(signatureNode);

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    try {
        DOMUtils.writeXml(doc, System.out);
    } catch (TransformerException e) {
        fail("Exception not expected: " + e.getMessage());
    }

    // Validate the signature
    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));

}
 
Example #24
Source File: FederationMetaDataTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void validateMetaDataWithAlias() throws ProcessingException, XMLSignatureException, XMLSecurityException {

    FedizContext config = loadConfig("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    Document doc = wfProc.getMetaData(null, config);
    Assert.assertNotNull(doc);

    Node signatureNode = doc.getElementsByTagName("Signature").item(0);
    Assert.assertNotNull(signatureNode);

    doc.getDocumentElement().setIdAttributeNS(null, "ID", true);

    try {
        DOMUtils.writeXml(doc, System.out);
    } catch (TransformerException e) {
        fail("Exception not expected: " + e.getMessage());
    }

    // Validate the signature
    XMLSignature signature = new XMLSignature((Element)signatureNode, "");
    KeyInfo ki = signature.getKeyInfo();
    Assert.assertNotNull(ki);
    Assert.assertNotNull(ki.getX509Certificate());

    Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate()));
}
 
Example #25
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteArrayToSign, Map<String, Object> options) throws TechnicalConnectorException {
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, byteArrayToSign);

   try {
      String xmldsigId = "xmldsig-" + IdGeneratorFactory.getIdGenerator("uuid").generateId();
      String baseURI = (String)SignatureUtils.getOption("baseURI", optionMap, "");
      String signatureMethodURI = (String)SignatureUtils.getOption("signatureMethodURI", optionMap, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
      String canonicalizationMethodURI = (String)SignatureUtils.getOption("canonicalizationMethodURI", optionMap, "http://www.w3.org/2001/10/xml-exc-c14n#");
      String digestURI = (String)SignatureUtils.getOption("digestURI", optionMap, "http://www.w3.org/2001/04/xmlenc#sha256");
      String encapsulateLocation = (String)SignatureUtils.getOption("encapsulate-xpath", optionMap, (Object)null);
      EncapsulationTransformer encapsulationTranformer = (EncapsulationTransformer)SignatureUtils.getOption("encapsulate-transformer", optionMap, new XmlSignatureBuilder.PassthroughEncapsulationTransformer());
      List<String> transformerList = getTransformerList(optionMap);
      Document doc = ConnectorXmlUtils.toDocument(byteArrayToSign);
      XMLSignature sig = new XMLSignature(doc, baseURI, signatureMethodURI, canonicalizationMethodURI);
      sig.addResourceResolver(new DocumentResolver(doc));
      sig.addDocument(ref(baseURI), transforms(transformerList, doc), digestURI);
      addKeyInfo(signatureCredential, sig);
      XadesHandler handler = new XadesHandler(sig, signatureCredential, options, this.specs);
      handler.before();
      sig.sign(signatureCredential.getPrivateKey());
      sig.setId(xmldsigId);
      handler.after();
      return transform(mustEncapsulate(transformerList), encapsulateLocation, encapsulationTranformer, doc, sig);
   } catch (Exception var16) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var16, new Object[]{var16.getMessage()});
   }
}
 
Example #26
Source File: KeyInfoBuilderTest.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
private XMLSignature getTestSignature() throws Exception
{
    Document doc = getNewDocument();
    XMLSignature xmlSignature = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
    xmlSignature.setId("sigId");
    doc.appendChild(xmlSignature.getElement());
    return xmlSignature;
}
 
Example #27
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void addKeyInfo(Credential signatureCredential, XMLSignature sig) throws TechnicalConnectorException, XMLSecurityException {
   if (signatureCredential.getCertificateChain() != null) {
      Certificate[] arr$ = signatureCredential.getCertificateChain();
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Certificate cert = arr$[i$];
         sig.addKeyInfo((X509Certificate)cert);
      }
   }

}
 
Example #28
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void addKeyInfo(Credential signatureCredential, XMLSignature sig) throws TechnicalConnectorException, XMLSecurityException {
   if (signatureCredential.getCertificateChain() != null) {
      Certificate[] arr$ = signatureCredential.getCertificateChain();
      int len$ = arr$.length;

      for(int i$ = 0; i$ < len$; ++i$) {
         Certificate cert = arr$[i$];
         sig.addKeyInfo((X509Certificate)cert);
      }
   }

}
 
Example #29
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static byte[] transform(boolean encapsulate, String xpathLocation, EncapsulationTransformer encapsulationTranformer, Document doc, XMLSignature sig) {
   if (!encapsulate) {
      return ConnectorXmlUtils.toByteArray((Node)sig.getElement());
   } else {
      Node toInsert = doc.adoptNode(encapsulationTranformer.transform(sig.getElement()));
      Node insertBeforeNode = null;
      if (StringUtils.isNotBlank(xpathLocation)) {
         try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList)xPath.evaluate(xpathLocation, doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() == 1) {
               LOG.debug("1 node found, inserting at location [" + xpathLocation + "]");
               insertBeforeNode = nodes.item(0);
            } else {
               LOG.warn("XPATH error: " + nodes.getLength() + "found at location [" + xpathLocation + "],using default.");
            }
         } catch (XPathExpressionException var9) {
            LOG.info("Unable to determine XPath Location, using default.", var9);
         }
      } else {
         LOG.debug("Using default location (last child tag)");
      }

      doc.getFirstChild().insertBefore(toInsert, insertBeforeNode);
      return ConnectorXmlUtils.toByteArray((Node)doc);
   }
}
 
Example #30
Source File: XmlSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public byte[] sign(Credential signatureCredential, byte[] byteArrayToSign, Map<String, Object> options) throws TechnicalConnectorException {
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, byteArrayToSign);

   try {
      String xmldsigId = "xmldsig-" + IdGeneratorFactory.getIdGenerator("uuid").generateId();
      String baseURI = (String)SignatureUtils.getOption("baseURI", optionMap, "");
      String signatureMethodURI = (String)SignatureUtils.getOption("signatureMethodURI", optionMap, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
      String canonicalizationMethodURI = (String)SignatureUtils.getOption("canonicalizationMethodURI", optionMap, "http://www.w3.org/2001/10/xml-exc-c14n#");
      String digestURI = (String)SignatureUtils.getOption("digestURI", optionMap, "http://www.w3.org/2001/04/xmlenc#sha256");
      String encapsulateLocation = (String)SignatureUtils.getOption("encapsulate-xpath", optionMap, (Object)null);
      EncapsulationTransformer encapsulationTranformer = (EncapsulationTransformer)SignatureUtils.getOption("encapsulate-transformer", optionMap, new XmlSignatureBuilder.PassthroughEncapsulationTransformer());
      List<String> transformerList = getTransformerList(optionMap);
      Document doc = ConnectorXmlUtils.toDocument(byteArrayToSign);
      XMLSignature sig = new XMLSignature(doc, baseURI, signatureMethodURI, canonicalizationMethodURI);
      sig.addResourceResolver(new DocumentResolver(doc));
      sig.addDocument(ref(baseURI), transforms(transformerList, doc), digestURI);
      addKeyInfo(signatureCredential, sig);
      XadesHandler handler = new XadesHandler(sig, signatureCredential, options, this.specs);
      handler.before();
      sig.sign(signatureCredential.getPrivateKey());
      sig.setId(xmldsigId);
      handler.after();
      return transform(mustEncapsulate(transformerList), encapsulateLocation, encapsulationTranformer, doc, sig);
   } catch (Exception var16) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_GENERAL, var16, new Object[]{var16.getMessage()});
   }
}