use of org.apache.xml.security.c14n.Canonicalizer in project santuario-java by apache.
the class SignedInfo method reparseSignedInfoElem.
private static Element reparseSignedInfoElem(Element element, boolean secureValidation) throws XMLSecurityException {
/*
* If a custom canonicalizationMethod is used, canonicalize
* ds:SignedInfo, reparse it into a new document
* and replace the original not-canonicalized ds:SignedInfo by
* the re-parsed canonicalized one.
*/
Element c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
if (!(c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS))) {
// so reparse the SignedInfo to be sure
try {
Canonicalizer c14nizer = Canonicalizer.getInstance(c14nMethodURI);
c14nizer.setSecureValidation(secureValidation);
byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
javax.xml.parsers.DocumentBuilder db = XMLUtils.createDocumentBuilder(false, secureValidation);
try (InputStream is = new ByteArrayInputStream(c14nizedBytes)) {
Document newdoc = db.parse(is);
Node imported = element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
element.getParentNode().replaceChild(imported, element);
return (Element) imported;
} finally {
XMLUtils.repoolDocumentBuilder(db);
}
} catch (ParserConfigurationException ex) {
throw new XMLSecurityException(ex);
} catch (IOException ex) {
throw new XMLSecurityException(ex);
} catch (SAXException ex) {
throw new XMLSecurityException(ex);
}
}
return element;
}
use of org.apache.xml.security.c14n.Canonicalizer in project poi by apache.
the class XAdESXLSignatureFacet method getC14nValue.
public static byte[] getC14nValue(List<Node> nodeList, String c14nAlgoId) {
ByteArrayOutputStream c14nValue = new ByteArrayOutputStream();
try {
for (Node node : nodeList) {
/*
* Re-initialize the c14n else the namespaces will get cached
* and will be missing from the c14n resulting nodes.
*/
Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId);
c14nValue.write(c14n.canonicalizeSubtree(node));
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("c14n error: " + e.getMessage(), e);
}
return c14nValue.toByteArray();
}
use of org.apache.xml.security.c14n.Canonicalizer in project santuario-java by apache.
the class XMLCipherTest method testSerializedData.
@org.junit.Test
public void testSerializedData() throws Exception {
if (!haveISOPadding) {
LOG.warn("Test testSerializedData skipped as necessary algorithms not available");
return;
}
byte[] bits128 = { (byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1A, (byte) 0x1B, (byte) 0x1C, (byte) 0x1D, (byte) 0x1E, (byte) 0x1F };
Key key = new SecretKeySpec(bits128, "AES");
// source
Document d = document();
Element e = (Element) d.getElementsByTagName(element()).item(index());
// encrypt
cipher = XMLCipher.getInstance(XMLCipher.AES_128);
cipher.init(XMLCipher.ENCRYPT_MODE, key);
// serialize element ...
Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
canon.setWriter(baos);
canon.notReset();
canon.canonicalizeSubtree(e);
baos.close();
String before = baos.toString(StandardCharsets.UTF_8.name());
byte[] serialized = baos.toByteArray();
EncryptedData encryptedData = null;
try (InputStream is = new ByteArrayInputStream(serialized)) {
encryptedData = cipher.encryptData(d, EncryptionConstants.TYPE_ELEMENT, is);
}
// decrypt
XMLCipher dcipher = XMLCipher.getInstance(XMLCipher.AES_128);
dcipher.init(XMLCipher.DECRYPT_MODE, key);
String algorithm = encryptedData.getEncryptionMethod().getAlgorithm();
assertEquals(XMLCipher.AES_128, algorithm);
byte[] bytes = dcipher.decryptToByteArray(dcipher.martial(encryptedData));
String after = new String(bytes, StandardCharsets.UTF_8);
assertEquals(before, after);
// test with null type
try (InputStream is = new ByteArrayInputStream(serialized)) {
encryptedData = cipher.encryptData(d, null, is);
}
}
use of org.apache.xml.security.c14n.Canonicalizer in project santuario-java by apache.
the class Canonicalizer11Test method c14nAndCompare.
private boolean c14nAndCompare(String fileIn, String fileRef, String fileOut, String c14nURI, boolean validating, String xpath, Map<String, String> namespaces) throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, XPathExpressionException {
DocumentBuilder documentBuilder = XMLUtils.createDocumentBuilder(validating, false);
// throw away all warnings and errors
documentBuilder.setErrorHandler(new IgnoreAllErrorHandler());
// org.xml.sax.EntityResolver resolver = new TestVectorResolver();
// documentBuilder.setEntityResolver(resolver);
// Document doc = documentBuilder.parse(resolver.resolveEntity(null, fileIn));
Document doc = documentBuilder.parse(fileIn);
Canonicalizer c14n = Canonicalizer.getInstance(c14nURI);
byte[] c14nBytes = null;
if (xpath == null) {
c14nBytes = c14n.canonicalizeSubtree(doc);
} else {
NodeList nl = null;
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
DSNamespaceContext namespaceContext = new DSNamespaceContext(namespaces);
xPath.setNamespaceContext(namespaceContext);
nl = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
c14nBytes = c14n.canonicalizeXPathNodeSet(nl);
}
// org.xml.sax.InputSource refIs = resolver.resolveEntity(null, fileRef);
// byte refBytes[] = JavaUtils.getBytesFromStream(refIs.getByteStream());
byte[] refBytes = JavaUtils.getBytesFromFile(fileRef);
// if everything is OK, result is true; we do a binary compare, byte by byte
boolean result = java.security.MessageDigest.isEqual(refBytes, c14nBytes);
if (!result) {
File f = new File(fileOut);
if (!f.exists()) {
File parent = new File(f.getParent());
parent.mkdirs();
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream(f);
fos.write(c14nBytes);
LOG.debug("Wrote erroneous result to file " + f.toURI().toURL().toString());
assertEquals(new String(refBytes), new String(c14nBytes));
fos.close();
}
return result;
}
use of org.apache.xml.security.c14n.Canonicalizer in project santuario-java by apache.
the class Canonicalizer20010315Test method testRelativeNSbehaviour.
/**
* Note: This specification supports the recent XML plenary decision to
* deprecate relative namespace URIs as follows: implementations of XML
* canonicalization MUST report an operation failure on documents containing
* relative namespace URIs. XML canonicalization MUST NOT be implemented
* with an XML parser that converts relative URIs to absolute URIs.
*
* Implementations MUST report an operation failure on documents containing
* relative namespace URIs.
*
* @throws CanonicalizationException
* @throws FileNotFoundException
* @throws IOException
* @throws InvalidCanonicalizerException
* @throws ParserConfigurationException
* @throws SAXException
* @throws TransformerException
*/
@org.junit.Test
public void testRelativeNSbehaviour() throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException {
// J-
String inputStr = "" + "<absolute:correct xmlns:absolute='http://www.absolute.org/#likeVodka'>" + "<relative:incorrect xmlns:relative='../cheating#away'>" + "</relative:incorrect>" + "</absolute:correct>" + "\n" + "";
// J+
DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
Document doc = null;
try (InputStream is = new ByteArrayInputStream(inputStr.getBytes())) {
doc = db.parse(is);
}
boolean weCatchedTheRelativeNS = false;
try {
Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
c14n.canonicalizeSubtree(doc);
} catch (CanonicalizationException cex) {
// if we reach this point - good.
LOG.debug("We catched the C14nEx, that's good: " + cex.getMessage());
weCatchedTheRelativeNS = true;
}
assertTrue("We did not catch the relative namespace", weCatchedTheRelativeNS);
}
Aggregations