Java Code Examples for org.apache.xml.security.c14n.Canonicalizer#getInstance()
The following examples show how to use
org.apache.xml.security.c14n.Canonicalizer#getInstance() .
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: SignedInfo.java From axelor-open-suite with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 2
Source File: SignedInfo.java From ebics-java-client with GNU Lesser General Public License v2.1 | 6 votes |
/** * 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 |
/** * 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: XAdESLevelBEnvelopedTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@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: XAdESLevelBEnvelopingTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@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 6
Source File: XAdESLevelBEnvelopingWithRefsTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@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 |
@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: Utils.java From ebics-java-client with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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 9
Source File: CanonicalizerUtils.java From xades4j with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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 10
Source File: EbicsUtils.java From axelor-open-suite with GNU Affero General Public License v3.0 | 5 votes |
/** * 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 11
Source File: AbstractPkiFactoryTestSignature.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
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 12
Source File: XAdESCanonicalizationTest.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
@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 13
Source File: XmlContentCanonicalizer.java From apicurio-registry with Apache License 2.0 | 5 votes |
@Override protected Canonicalizer initialValue() { try { return Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); } catch (InvalidCanonicalizerException e) { throw new RuntimeException(e); } }
Example 14
Source File: XAdESCanonicalizationTest.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
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 |
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 16
Source File: XAdESCanonicalizationTest.java From dss with GNU Lesser General Public License v2.1 | 4 votes |
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 17
Source File: RDFXMLParserTestCase.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
public CanonXMLValueFactory() throws InvalidCanonicalizerException, ParserConfigurationException { org.apache.xml.security.Init.init(); c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); }
Example 18
Source File: DSSXMLUtils.java From dss with GNU Lesser General Public License v2.1 | 3 votes |
/** * This method canonicalizes the given {@code Node}. * If canonicalization method is not provided, the {@code DEFAULT_CANONICALIZATION_METHOD} is being used * * @param canonicalizationMethod * canonicalization method (can be null) * @param node * {@code Node} to canonicalize * @return array of canonicalized bytes */ public static byte[] canonicalizeSubtree(String canonicalizationMethod, final Node node) { try { final Canonicalizer c14n = Canonicalizer.getInstance(getCanonicalizationMethod(canonicalizationMethod)); return c14n.canonicalizeSubtree(node); } catch (Exception e) { throw new DSSException("Cannot canonicalize the subtree", e); } }
Example 19
Source File: DSSXMLUtils.java From dss with GNU Lesser General Public License v2.1 | 3 votes |
/** * This method canonicalizes the given array of bytes using the {@code canonicalizationMethod} parameter. * * @param canonicalizationMethod * canonicalization method * @param toCanonicalizeBytes * array of bytes to canonicalize * @return array of canonicalized bytes * @throws DSSException * if any error is encountered */ public static byte[] canonicalize(final String canonicalizationMethod, final byte[] toCanonicalizeBytes) throws DSSException { try { final Canonicalizer c14n = Canonicalizer.getInstance(getCanonicalizationMethod(canonicalizationMethod)); return c14n.canonicalize(toCanonicalizeBytes); } catch (Exception e) { throw new DSSException("Cannot canonicalize the binaries", e); } }