org.apache.xml.security.c14n.Canonicalizer Java Examples

The following examples show how to use org.apache.xml.security.c14n.Canonicalizer. 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: XAdESLevelBEnvelopedTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
	super.verifyOriginalDocuments(validator, diagnosticData);
	
	List<DSSDocument> originals = validator.getOriginalDocuments(diagnosticData.getFirstSignatureId());
	assertEquals(1, originals.size());

	DSSDocument original = originals.get(0);

	try {
		Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS);
		String firstDocument = new String(canon.canonicalize(DSSUtils.toByteArray(documentToSign)));
		String secondDocument = new String(canon.canonicalize(DSSUtils.toByteArray(original)));
		assertEquals(firstDocument, secondDocument);
	} catch (Exception e) {
		fail(e);
	}
}
 
Example #2
Source File: SignedInfo.java    From ebics-java-client with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Canonizes and signs a given input with the authentication private key.
 * of the EBICS user.
 * 
 * <p>The given input to be signed is first Canonized using the 
 * http://www.w3.org/TR/2001/REC-xml-c14n-20010315 algorithm.
 * 
 * <p>The element to be canonized is only the SignedInfo element that should be
 * contained in the request to be signed. Otherwise, a {@link TransformationException}
 * is thrown.
 * 
 * <p> The namespace of the SignedInfo element should be named <b>ds</b> as specified in
 * the EBICS specification for common namespaces nomination.
 * 
 * <p> The signature is ensured using the user X002 private key. This step is done in
 * {@link EbicsUser#authenticate(byte[]) authenticate}.
 * 
 * @param toSign the input to sign
 * @return the signed input
 * @throws EbicsException signature fails.
 */
public byte[] sign(byte[] toSign) throws EbicsException {
  try {
    DocumentBuilderFactory 		factory;
    DocumentBuilder			builder;
    Document				document;
    Node 				node;
    Canonicalizer 			canonicalizer;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new IgnoreAllErrorHandler());
    document = builder.parse(new ByteArrayInputStream(toSign));
    node = XPathAPI.selectSingleNode(document, "//ds:SignedInfo");
    canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    return user.authenticate(canonicalizer.canonicalizeSubtree(node));
  } catch(Exception e) {
    throw new EbicsException(e.getMessage());
  }
}
 
Example #3
Source File: CanonicalizerUtils.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if all the transforms in a ds:Reference are canonicalization transforms.
 * @param r the reference
 * @return true if all transforms are c14n, false otherwise.
 * @throws XMLSecurityException
 */
public static boolean allTransformsAreC14N(Reference r) throws XMLSecurityException
{
    Transforms transforms = r.getTransforms();
    try
    {
        for (int i = 0; i < transforms.getLength(); ++i)
        {
            Canonicalizer.getInstance(transforms.item(i).getURI());
        }
        return true;
    }
    catch (InvalidCanonicalizerException ex)
    {
        return false;
    }
}
 
Example #4
Source File: XAdESLevelBEnvelopingTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
	super.verifyOriginalDocuments(validator, diagnosticData);
	
	List<DSSDocument> originals = validator.getOriginalDocuments(diagnosticData.getFirstSignatureId());
	assertEquals(1, originals.size());

	DSSDocument original = originals.get(0);

	try {
		Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS);
		String firstDocument = new String(canon.canonicalize(DSSUtils.toByteArray(documentToSign)));
		String secondDocument = new String(canon.canonicalize(DSSUtils.toByteArray(original)));
		assertEquals(firstDocument, secondDocument);
	} catch (Exception e) {
		fail(e);
	}
}
 
Example #5
Source File: SignedInfo.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Canonizes and signs a given input with the authentication private key. of the EBICS user.
 *
 * <p>The given input to be signed is first Canonized using the
 * http://www.w3.org/TR/2001/REC-xml-c14n-20010315 algorithm.
 *
 * <p>The element to be canonized is only the SignedInfo element that should be contained in the
 * request to be signed. Otherwise, a {@link TransformationException} is thrown.
 *
 * <p>The namespace of the SignedInfo element should be named <b>ds</b> as specified in the EBICS
 * specification for common namespaces nomination.
 *
 * <p>The signature is ensured using the user X002 private key. This step is done in {@link
 * EbicsUser#authenticate(byte[]) authenticate}.
 *
 * @param toSign the input to sign
 * @return the signed input
 * @throws EbicsException signature fails.
 */
public byte[] sign(byte[] toSign) throws AxelorException {
  try {
    DocumentBuilderFactory factory;
    DocumentBuilder builder;
    Document document;
    Node node;
    Canonicalizer canonicalizer;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new IgnoreAllErrorHandler());
    document = builder.parse(new ByteArrayInputStream(toSign));
    node = XPathAPI.selectSingleNode(document, "//ds:SignedInfo");
    canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    return Beans.get(EbicsUserService.class)
        .authenticate(user, canonicalizer.canonicalizeSubtree(node));
  } catch (Exception e) {
    e.printStackTrace();
    throw new AxelorException(e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR);
  }
}
 
Example #6
Source File: XAdESLevelBEnvelopingWithRefsTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
	super.verifyOriginalDocuments(validator, diagnosticData);
	
	List<DSSDocument> originals = validator.getOriginalDocuments(diagnosticData.getFirstSignatureId());
	assertEquals(2, originals.size());

	DSSDocument orig1 = originals.get(0);
	DSSDocument orig2 = originals.get(1);

	try {
		Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS);
		String firstDocument = new String(canon.canonicalize(DSSUtils.toByteArray(doc1)));
		String secondDocument = new String(canon.canonicalize(DSSUtils.toByteArray(orig1)));
		assertEquals(firstDocument, secondDocument);

		firstDocument = new String(canon.canonicalize(DSSUtils.toByteArray(doc2)));
		secondDocument = new String(canon.canonicalize(DSSUtils.toByteArray(orig2)));
		assertEquals(firstDocument, secondDocument);
	} catch (Exception e) {
		fail(e);
	}
	
	assertEquals(doc1.getDigest(DigestAlgorithm.SHA256), orig1.getDigest(DigestAlgorithm.SHA256));
	assertEquals(doc2.getDigest(DigestAlgorithm.SHA256), orig2.getDigest(DigestAlgorithm.SHA256));
}
 
Example #7
Source File: XAdESLevelBDetachedTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
	super.verifyOriginalDocuments(validator, diagnosticData);
	
	List<DSSDocument> originals = validator.getOriginalDocuments(diagnosticData.getFirstSignatureId());
	assertEquals(1, originals.size());

	DSSDocument original = originals.get(0);

	try {
		Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS);
		String firstDocument = new String(canon.canonicalize(DSSUtils.toByteArray(documentToSign)));
		String secondDocument = new String(canon.canonicalize(DSSUtils.toByteArray(original)));
		assertEquals(firstDocument, secondDocument);
	} catch (Exception e) {
		fail(e);
	}
}
 
Example #8
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static Signature setSignatureRaw(String signatureAlgorithm, X509Credential cred) throws SSOAgentException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        org.opensaml.xml.signature.X509Certificate cert =
                (org.opensaml.xml.signature.X509Certificate) buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
        String value =
                org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
        return signature;

    } catch (CertificateEncodingException e) {
        throw new SSOAgentException("Error getting certificate", e);
    }
}
 
Example #9
Source File: SAML1TokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void setSignature(String signatureAlgorithm, X509Credential cred) throws IdentityProviderException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        String value = Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
    } catch (CertificateEncodingException e) {
        log.error("Error while getting the encoded certificate", e);
        throw new IdentityProviderException("Error while getting the encoded certificate");
    }

    assertion.setSignature(signature);
    signatureList.add(signature);
}
 
Example #10
Source File: SAML2TokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public void setSignature(String signatureAlgorithm, X509Credential cred) throws IdentityProviderException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        String value = Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
    } catch (CertificateEncodingException e) {
        log.error("Failed to get encoded certificate", e);
        throw new IdentityProviderException("Error while getting encoded certificate");
    }

    assertion.setSignature(signature);
    signatureList.add(signature);
}
 
Example #11
Source File: XAdESLevelBEnvelopedHtmlUTF8Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	service = new XAdESService(getOfflineCertificateVerifier());
	service.setTspSource(getAlternateGoodTsa());

	documentToSign = new FileDocument(new File("src/test/resources/htmlUTF8.html"));

	signatureParameters = new XAdESSignatureParameters();
	signatureParameters.bLevel().setSigningDate(new Date());
	signatureParameters.setSigningCertificate(getSigningCert());
	signatureParameters.setCertificateChain(getCertificateChain());
	signatureParameters.setSignaturePackaging(SignaturePackaging.ENVELOPED);
	signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B);

	XAdESTimestampParameters contentTimestampParameters = new XAdESTimestampParameters();
	contentTimestampParameters.setDigestAlgorithm(DigestAlgorithm.SHA512);
	contentTimestampParameters.setCanonicalizationMethod(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
	signatureParameters.setContentTimestampParameters(contentTimestampParameters);
	TimestampToken contentTimestamp = service.getContentTimestamp(documentToSign, signatureParameters);

	contentTimestampParameters = new XAdESTimestampParameters();
	contentTimestampParameters.setDigestAlgorithm(DigestAlgorithm.SHA1);
	contentTimestampParameters.setCanonicalizationMethod(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS);
	signatureParameters.setContentTimestampParameters(contentTimestampParameters);
	TimestampToken contentTimestamp2 = service.getContentTimestamp(documentToSign, signatureParameters);

	signatureParameters.setContentTimestamps(Arrays.asList(contentTimestamp, contentTimestamp2));
}
 
Example #12
Source File: XAdESReferenceCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Stream<Arguments> data() {
	Object[] canonicalizations = { Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS,
			Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS, Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS };
	Object[] packagings = { SignaturePackaging.ENVELOPED, SignaturePackaging.ENVELOPING, 
			SignaturePackaging.DETACHED, SignaturePackaging.INTERNALLY_DETACHED };
	return combine(canonicalizations, packagings);
}
 
Example #13
Source File: XAdESCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkSignedProperties(Document doc) {
	// ------------------------------------ SIGNED PROPERTIES
	// -----------------------------------------------------
	try {
		// Signed properties extraction + verification
		NodeList signedPropertiesNodeList = DomUtils.getNodeList(doc, AbstractPaths.all(XAdES132Element.SIGNED_PROPERTIES));
		assertNotNull(signedPropertiesNodeList);
		assertEquals(1, signedPropertiesNodeList.getLength());

		Node signedProperties = signedPropertiesNodeList.item(0);

		NamedNodeMap signedPropertiesAttributes = signedProperties.getAttributes();
		Node signedPropertiesId = signedPropertiesAttributes.getNamedItem("Id");
		assertNotNull(signedPropertiesId);

		Canonicalizer canonicalizer = Canonicalizer.getInstance(canonicalizationSignedProperties);

		// Verify KeyInfo Canonicalization Algorithm
		NodeList transformNodes = getReferenceTransforms(doc, "#" + signedPropertiesId.getNodeValue());
		String signedPropertiesTransformAlgo = getTransformAlgo(transformNodes.item(0));
		assertEquals(canonicalizer.getURI(), signedPropertiesTransformAlgo);

		// Verify KeyInfo Digest
		String signedPropertiesDigest = getReferenceDigest(doc, "#" + signedPropertiesId.getNodeValue());
		byte[] canonicalizedSignedProperties = canonicalizer.canonicalizeSubtree(signedProperties);
		byte[] digestProperties = DSSUtils.digest(DigestAlgorithm.SHA256, canonicalizedSignedProperties);
		String propertiesBase64 = Base64.getEncoder().encodeToString(digestProperties);
		assertEquals(propertiesBase64, signedPropertiesDigest);
	} catch (Exception e) {
		fail(e.getMessage());
	}
}
 
Example #14
Source File: XAdESCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkKeyInfo(Document doc) throws InvalidCanonicalizerException, CanonicalizationException {
	// ------------------------------------ KEY INFO
	// -----------------------------------------------------
	// Key info extraction + Verification
	NodeList keyInfoNodeList = DomUtils.getNodeList(doc, AbstractPaths.all(XMLDSigElement.KEY_INFO));
	assertNotNull(keyInfoNodeList);
	assertEquals(1, keyInfoNodeList.getLength());

	Node keyInfo = keyInfoNodeList.item(0);

	NamedNodeMap keyInfoAttributes = keyInfo.getAttributes();
	Node keyInfoId = keyInfoAttributes.getNamedItem("Id");
	assertNotNull(keyInfoId);

	Canonicalizer canonicalizer = Canonicalizer.getInstance(canonicalizationKeyInfo);

	// Verify KeyInfo Canonicalization Algorithm
	NodeList transformNodes = getReferenceTransforms(doc, "#" + keyInfoId.getNodeValue());
	String keyInfoTransformAlgo = getTransformAlgo(transformNodes.item(0));
	assertEquals(canonicalizer.getURI(), keyInfoTransformAlgo);

	// Verify KeyInfo Digest
	String keyInfoDigest = getReferenceDigest(doc, "#" + keyInfoId.getNodeValue());
	byte[] canonicalizedKeyInfo = canonicalizer.canonicalizeSubtree(keyInfo);
	byte[] digestKeyInfo = DSSUtils.digest(DigestAlgorithm.SHA256, canonicalizedKeyInfo);
	String keyInfoBase64 = Base64.getEncoder().encodeToString(digestKeyInfo);
	assertEquals(keyInfoBase64, keyInfoDigest);
}
 
Example #15
Source File: XAdESCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void onDocumentSigned(byte[] byteArray) {
	super.onDocumentSigned(byteArray);
	saveDocumentAndDelete(byteArray);

	try {
		Document doc = DomUtils.buildDOM(byteArray);

		checkKeyInfo(doc);
		checkSignedProperties(doc);
		checkOriginalDocument(doc);

		// ------------------------------------ SIGNED INFO
		// -----------------------------------------------------
		// Signed info extraction
		NodeList signedInfoNodeList = DomUtils.getNodeList(doc, AbstractPaths.all(XMLDSigElement.SIGNED_INFO));
		assertNotNull(signedInfoNodeList);
		assertEquals(1, signedInfoNodeList.getLength());

		Node signedInfo = signedInfoNodeList.item(0);

		// ------------------------------------ SIGNATURE VERIFICATION
		// -----------------------------------------------------
		Canonicalizer canonicalizer = Canonicalizer.getInstance(canonicalizationSignedInfo);
		String signatureValueBase64 = DomUtils.getValue(doc, "//ds:Signature/ds:SignatureValue");
		assertNotNull(signatureValueBase64);

		byte[] canonicalized = canonicalizer.canonicalizeSubtree(signedInfo);

		byte[] sigValue = Utils.fromBase64(signatureValueBase64);

		Signature signature = Signature.getInstance("SHA256withRSA");
		signature.initVerify(getSigningCert().getPublicKey());
		signature.update(canonicalized);
		boolean verify = signature.verify(sigValue);
		assertTrue(verify);
	} catch (Exception e) {
		fail(e.getMessage());
	}
}
 
Example #16
Source File: AbstractPkiFactoryTestSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String getDigest(DSSDocument doc, boolean toBeCanonicalized) {
	byte[] byteArray = DSSUtils.toByteArray(doc);
	if (toBeCanonicalized) {
		try {
			// we canonicalize to ignore the header (which is not covered by the signature)
			Canonicalizer c14n = Canonicalizer.getInstance(getCanonicalizationMethod());
			byteArray = c14n.canonicalize(byteArray);
		} catch (XMLSecurityException | ParserConfigurationException | IOException | SAXException e) {
			// Not always able to canonicalize (more than one file can be covered (XML +
			// something else) )
		}
	}
	// LOG.info("Bytes : {}", new String(byteArray));
	return Utils.toBase64(DSSUtils.digest(DigestAlgorithm.SHA256, byteArray));
}
 
Example #17
Source File: DSSXMLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method registers the default canonicalizers.
 */
private static void registerDefaultCanonicalizers() {

	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS);
	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N_PHYSICAL);
	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS);
	registerCanonicalizer(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS);
}
 
Example #18
Source File: EbicsUtils.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Canonizes an input with inclusive c14n without comments algorithm.
 *
 * <p>EBICS Specification 2.4.2 - 5.5.1.1.1 EBICS messages in transaction initialization:
 *
 * <p>The identification and authentication signature includes all XML elements of the EBICS
 * request whose attribute value for @authenticate is equal to “true”. The definition of the XML
 * schema “ebics_request.xsd“ guarantees that the value of the attribute @authenticate is equal to
 * “true” for precisely those elements that also need to be signed.
 *
 * <p>Thus, All the Elements with the attribute authenticate = true and their sub elements are
 * considered for the canonization process. This is performed via the {@link
 * XPathAPI#selectNodeIterator(Node, String) selectNodeIterator(Node, String)}.
 *
 * @param input the byte array XML input.
 * @return the canonized form of the given XML
 * @throws EbicsException
 */
public static byte[] canonize(byte[] input) throws AxelorException {
  DocumentBuilderFactory factory;
  DocumentBuilder builder;
  Document document;
  NodeIterator iter;
  ByteArrayOutputStream output;
  Node node;

  try {
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new IgnoreAllErrorHandler());
    document = builder.parse(new ByteArrayInputStream(input));
    iter = XPathAPI.selectNodeIterator(document, "//*[@authenticate='true']");
    output = new ByteArrayOutputStream();
    while ((node = iter.nextNode()) != null) {
      Canonicalizer canonicalizer;

      canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
      output.write(canonicalizer.canonicalizeSubtree(node));
    }

    return output.toByteArray();
  } catch (Exception e) {
    throw new AxelorException(
        e.getCause(), TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, e.getMessage());
  }
}
 
Example #19
Source File: SignedInfo.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void build() throws AxelorException {
  CanonicalizationMethodType canonicalizationMethod;
  SignatureMethodType signatureMethod;
  ReferenceType reference;
  TransformsType transforms;
  DigestMethodType digestMethod;
  TransformType transform;
  SignedInfoType signedInfo;

  if (digest == null) {
    throw new AxelorException(
        TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
        I18n.get("digest value cannot be null"));
  }

  transform = EbicsXmlFactory.createTransformType(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
  digestMethod =
      EbicsXmlFactory.createDigestMethodType("http://www.w3.org/2001/04/xmlenc#sha256");
  transforms = EbicsXmlFactory.createTransformsType(new TransformType[] {transform});
  reference =
      EbicsXmlFactory.createReferenceType(
          "#xpointer(//*[@authenticate='true'])", transforms, digestMethod, digest);
  signatureMethod =
      EbicsXmlFactory.createSignatureMethodType(
          "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
  canonicalizationMethod =
      EbicsXmlFactory.createCanonicalizationMethodType(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
  signedInfo =
      EbicsXmlFactory.createSignedInfoType(
          canonicalizationMethod, signatureMethod, new ReferenceType[] {reference});

  document = EbicsXmlFactory.createSignatureType(signedInfo);
}
 
Example #20
Source File: FromXmlBaseTimeStampConverter.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void convertTimeStamps(
        List<XmlXAdESTimeStampType> xmlTimeStamps,
        QualifyingPropertiesDataCollector propertyDataCollector) throws PropertyUnmarshalException
{
    if (null == xmlTimeStamps || xmlTimeStamps.isEmpty())
        return;

    for (XmlXAdESTimeStampType xmlTS : xmlTimeStamps)
    {
        if(!xmlTS.getReferenceInfo().isEmpty())
            throw new PropertyUnmarshalException("ReferenceInfo is not supported in XAdESTimeStamp", propName);

        Algorithm c14n;
        XmlCanonicalizationMethodType xmlCanonMethod = xmlTS.getCanonicalizationMethod();
        if(null == xmlCanonMethod)
        {
            c14n = new GenericAlgorithm(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
        }
        else
        {
            List params = CollectionUtils.filterByType(xmlCanonMethod.getContent(), Element.class);
            c14n = new GenericAlgorithm(xmlCanonMethod.getAlgorithm(), params);
        }
        TPropData tsData = createTSData(c14n);

        List<Object> tsTokens = xmlTS.getEncapsulatedTimeStampOrXMLTimeStamp();
        if (tsTokens.isEmpty())
            throw new PropertyUnmarshalException("No time-stamp tokens", propName);

        for (Object tkn : tsTokens)
        {
            if (!(tkn instanceof XmlEncapsulatedPKIDataType))
                throw new PropertyUnmarshalException("XML time-stamps are not supported", propName);
            tsData.addTimeStampToken(((XmlEncapsulatedPKIDataType)tkn).getValue());
        }

        doSpecificConvert(xmlTS, tsData);
        setTSData(tsData, propertyDataCollector);
    }
}
 
Example #21
Source File: CanonicalizerUtils.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Verifies input C14N Algorithm is in fact a C14N Algorithm by querying the
 * default Apache Canonicalizer.
 *
 * @param c14n - A C14N algorithm.
 * @throws UnsupportedAlgorithmException - If the URI is not registered in
 * the default Canonicalizer.
 */
public static void checkC14NAlgorithm(Algorithm c14n) throws UnsupportedAlgorithmException
{
    // HACK: since we're not using Canonicalizer, do a quick check to ensure
    // that 'c14n' refers to a configured C14N algorithm.
    try
    {
        Canonicalizer.getInstance(c14n.getUri());
    } catch (InvalidCanonicalizerException ex)
    {
        throw new UnsupportedAlgorithmException("Unsupported canonicalization method", c14n.getUri(), ex);
    }
}
 
Example #22
Source File: SignedInfo.java    From ebics-java-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void build() throws EbicsException {
  CanonicalizationMethodType 	canonicalizationMethod;
  SignatureMethodType 	signatureMethod;
  ReferenceType 		reference;
  TransformsType 		transforms;
  DigestMethodType 		digestMethod;
  TransformType 		transform;
  SignedInfoType		signedInfo;

  if (digest == null) {
    throw new EbicsException("digest value cannot be null");
  }

  transform = EbicsXmlFactory.createTransformType(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
  digestMethod = EbicsXmlFactory.createDigestMethodType("http://www.w3.org/2001/04/xmlenc#sha256");
  transforms = EbicsXmlFactory.createTransformsType(new TransformType[] {transform});
  reference = EbicsXmlFactory.createReferenceType("#xpointer(//*[@authenticate='true'])",
                                           transforms,
                                           digestMethod,
                                           digest);
  signatureMethod = EbicsXmlFactory.createSignatureMethodType("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
  canonicalizationMethod = EbicsXmlFactory.createCanonicalizationMethodType(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
  signedInfo = EbicsXmlFactory.createSignedInfoType(canonicalizationMethod,
                                             signatureMethod,
                                             new ReferenceType[] {reference});

  document = EbicsXmlFactory.createSignatureType(signedInfo);
}
 
Example #23
Source File: Utils.java    From ebics-java-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Canonizes an input with inclusive c14n without comments algorithm.
 * 
 * <p>EBICS Specification 2.4.2 - 5.5.1.1.1 EBICS messages in transaction initialization:
 * 
 * <p>The identification and authentication signature includes all XML elements of the
 * EBICS request whose attribute value for @authenticate is equal to “true”. The
 * definition of the XML schema “ebics_request.xsd“ guarantees that the value of the
 * attribute @authenticate is equal to “true” for precisely those elements that also
 * need to be signed.
 * 
 * <p>Thus, All the Elements with the attribute authenticate = true and their 
 * sub elements are considered for the canonization process. This is performed 
 * via the {@link XPathAPI#selectNodeIterator(Node, String) selectNodeIterator(Node, String)}.
 * 
 * @param input the byte array XML input.
 * @return the canonized form of the given XML
 * @throws EbicsException
 */
public static byte[] canonize(byte[] input) throws EbicsException {
  DocumentBuilderFactory 		factory;
  DocumentBuilder			builder;
  Document				document;
  NodeIterator			iter;
  ByteArrayOutputStream		output;
  Node 				node;

  try {
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new IgnoreAllErrorHandler());
    document = builder.parse(new ByteArrayInputStream(input));
    iter = XPathAPI.selectNodeIterator(document, "//*[@authenticate='true']");
    output = new ByteArrayOutputStream();
    while ((node = iter.nextNode()) != null) {
      Canonicalizer 		canonicalizer;

      canonicalizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
      output.write(canonicalizer.canonicalizeSubtree(node));
    }

    return output.toByteArray();
  } catch (Exception e) {
    throw new EbicsException(e.getMessage());
  }
}
 
Example #24
Source File: XmlContentCanonicalizer.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
protected Canonicalizer initialValue() {
    try {
        return Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    } catch (InvalidCanonicalizerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: XmlContentCanonicalizer.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
/**
 * @see ContentCanonicalizer#canonicalize(io.apicurio.registry.content.ContentHandle)
 */
@Override
public ContentHandle canonicalize(ContentHandle content) {
    try {
        Canonicalizer canon = xmlCanonicalizer.get();
        String canonicalized = IoUtil.toString(canon.canonicalize(content.bytes()));
        return ContentHandle.create(canonicalized);
    } catch (CanonicalizationException | ParserConfigurationException | IOException | SAXException e) {
    }
    return content;
}
 
Example #26
Source File: StaxSerializer.java    From cxf with Apache License 2.0 4 votes vote down vote up
public StaxSerializer() throws InvalidCanonicalizerException {
    super(Canonicalizer.ALGO_ID_C14N_PHYSICAL, true);
}
 
Example #27
Source File: XAdESCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void checkOriginalDocument(Document doc) throws Exception {
	// ------------------------------------ ORIGINAL FILE
	// -----------------------------------------------------
	String originalFileDigest = "";
	byte[] originalFileByteArray = null;

	if (packaging == SignaturePackaging.ENVELOPED) {
		// Original File base64 extraction + Verification
		originalFileDigest = getReferenceDigest(doc, "");

		NodeList transformNodes = getReferenceTransforms(doc, "");
		String algo = getTransformAlgo(transformNodes.item(1));

		Canonicalizer canonicalizer = Canonicalizer.getInstance(algo);

		File orginalFile = new File("src/test/resources/sample.xml");
		// Transform original file into byte array
		byte[] fileContent = Files.readAllBytes(orginalFile.toPath());
		originalFileByteArray = canonicalizer.canonicalize(fileContent);
	} else {
		// Original File base64 extraction + Verification
		NodeList originalFileNodeList = DomUtils.getNodeList(doc, AbstractPaths.all(XMLDSigElement.OBJECT));
		assertNotNull(originalFileNodeList);
		assertEquals(2, originalFileNodeList.getLength());

		Node orignalFile = originalFileNodeList.item(1);

		NamedNodeMap originalFileAttributes = orignalFile.getAttributes();
		Node originalFileId = originalFileAttributes.getNamedItem("Id");
		assertNotNull(originalFileId);

		// Extract original file digest
		originalFileDigest = getReferenceDigest(doc, "#" + originalFileId.getNodeValue());

		// Calculate Original File digest from retrieved base64
		String originalBase64String = orignalFile.getTextContent();
		// Get byte array from base64 string
		originalFileByteArray = Base64.getDecoder().decode(originalBase64String);
	}

	// Calculate Original File Digest
	byte[] digestOriginalFile = DSSUtils.digest(DigestAlgorithm.SHA256, originalFileByteArray);
	String originalDigestBase64 = Base64.getEncoder().encodeToString(digestOriginalFile);

	// Assert that both values are equivalent
	assertEquals(originalFileDigest, originalDigestBase64);
}
 
Example #28
Source File: XAdESCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static Stream<Arguments> data() {
	Object[] arr = { Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS };
	return random(arr);
}
 
Example #29
Source File: SantuarioInitializer.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Dynamically initialise the library by registering the default
 * algorithms/implementations
 */
private static void dynamicInit() {
	//
	// Load the Resource Bundle - the default is the English resource bundle.
	// To load another resource bundle, call I18n.init(...) before calling this
	// method.
	//
	I18n.init("en", "US");

	if (LOG.isDebugEnabled()) {
		LOG.debug("Registering default algorithms");
	}
	try {
		//
		// Bind the default prefixes
		//
		ElementProxy.registerDefaultPrefixes();
	} catch (XMLSecurityException ex) {
		LOG.error(ex.getMessage(), ex);
	}

	//
	// Set the default Transforms
	//
	Transform.registerDefaultAlgorithms();

	//
	// Set the default signature algorithms
	//
	SignatureAlgorithm.registerDefaultAlgorithms();

	//
	// Set the default JCE algorithms
	//
	JCEMapper.registerDefaultAlgorithms();

	//
	// Set the default c14n algorithms
	//
	Canonicalizer.registerDefaultAlgorithms();

	//
	// Register the default resolvers (custom)
	//
	registerDefaultResolvers();

	//
	// Register the default key resolvers
	//
	KeyResolver.registerDefaultResolvers();
}
 
Example #30
Source File: ExclusiveCanonicalXMLWithComments.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
public ExclusiveCanonicalXMLWithComments(Set<String> inclusiveNamespacePrefixes)
{
    super(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS, inclusiveNamespacePrefixes);
}