use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class SignedEncryptedTest method secureAndVerify.
public void secureAndVerify(TransformerFactory transformerFactory, boolean useDocumentSerializer) throws Exception {
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = null;
try (InputStream is = new ByteArrayInputStream(SAMPLE_MSG.getBytes(StandardCharsets.UTF_8))) {
document = builder.parse(is);
}
// Set up the Key
KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
KeyPair kp = rsaKeygen.generateKeyPair();
PrivateKey priv = kp.getPrivate();
PublicKey pub = kp.getPublic();
XMLSignature sig = new XMLSignature(document, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
Element sigElement = sig.getElement();
document.getDocumentElement().appendChild(sigElement);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
Element element = (Element) xpath.evaluate("//*[local-name()='Body']", document, XPathConstants.NODE);
String id = UUID.randomUUID().toString();
element.setAttributeNS(null, "Id", id);
element.setIdAttributeNS(null, "Id", true);
Transforms transforms = new Transforms(document);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
sig.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
sig.addKeyInfo(pub);
sig.sign(priv);
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(256);
SecretKey secretKey = keygen.generateKey();
XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128);
cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
document = cipher.doFinal(document, element, true);
XMLCipher deCipher = XMLCipher.getInstance(XMLCipher.AES_128);
if (transformerFactory != null && deCipher.getSerializer() instanceof TransformSerializer) {
Field f = deCipher.getSerializer().getClass().getDeclaredField("transformerFactory");
f.setAccessible(true);
f.set(deCipher.getSerializer(), transformerFactory);
}
if (useDocumentSerializer) {
deCipher.setSerializer(new DocumentSerializer());
}
deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
deCipher.doFinal(document, element, true);
XMLSignature xmlSignatureVerifier = new XMLSignature(sigElement, "");
Assert.assertTrue(xmlSignatureVerifier.checkSignatureValue(pub));
}
use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class HMACSignatureAlgorithmTest method verify.
private void verify(Document document, Key key, List<String> localNames, boolean secureValidation) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
String expression = "//dsig:Signature[1]";
Element sigElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
Assert.assertNotNull(sigElement);
for (String name : localNames) {
expression = "//*[local-name()='" + name + "']";
Element signedElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
Assert.assertNotNull(signedElement);
signedElement.setIdAttributeNS(null, "Id", true);
}
XMLSignature signature = new XMLSignature(sigElement, "", secureValidation);
Assert.assertTrue(signature.checkSignatureValue(key));
}
use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class PKSignatureAlgorithmTest method sign.
private XMLSignature sign(String algorithm, Document document, List<String> localNames, Key signingKey) throws Exception {
String c14nMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
XMLSignature sig = new XMLSignature(document, "", algorithm, c14nMethod);
Element root = document.getDocumentElement();
root.appendChild(sig.getElement());
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
for (String localName : localNames) {
String expression = "//*[local-name()='" + localName + "']";
NodeList elementsToSign = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i = 0; i < elementsToSign.getLength(); i++) {
Element elementToSign = (Element) elementsToSign.item(i);
Assert.assertNotNull(elementToSign);
String id = UUID.randomUUID().toString();
elementToSign.setAttributeNS(null, "Id", id);
elementToSign.setIdAttributeNS(null, "Id", true);
Transforms transforms = new Transforms(document);
transforms.addTransform(c14nMethod);
String digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
sig.addDocument("#" + id, transforms, digestMethod);
}
}
sig.sign(signingKey);
String expression = "//ds:Signature[1]";
Element sigElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
Assert.assertNotNull(sigElement);
return sig;
}
use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class Canonicalizer20010315Test method test37byNodeList.
/**
* 3.7 Document Subsets
*
* @throws CanonicalizationException
* @throws FileNotFoundException
* @throws IOException
* @throws InvalidCanonicalizerException
* @throws ParserConfigurationException
* @throws SAXException
* @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-DocSubsets">the example from the spec</A>
* @throws TransformerException
* @throws XPathExpressionException
*/
@org.junit.Test
public void test37byNodeList() throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, XPathExpressionException {
// String descri = "3.7 Document Subsets. (uncommented), c14n by NodeList";
String fileIn = prefix + "in/37_input.xml";
String fileRef = prefix + "in/37_c14n.xml";
// String c14nURI = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
// boolean validating = true;
DocumentBuilder db = XMLUtils.createDocumentBuilder(false, false);
org.xml.sax.EntityResolver resolver = new TestVectorResolver();
db.setEntityResolver(resolver);
Document doc = db.parse(resolver.resolveEntity(null, fileIn));
String xpath = "(//. | //@* | //namespace::*)" + "[ " + "self::ietf:e1 or " + "(parent::ietf:e1 and not(self::text() or self::e2)) or " + "count(id(\"E3\")|ancestor-or-self::node()) = count(ancestor-or-self::node()) " + "]";
Map<String, String> namespace = new HashMap<>();
namespace.put("ietf", "http://www.ietf.org");
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
DSNamespaceContext namespaceContext = new DSNamespaceContext(namespace);
xPath.setNamespaceContext(namespaceContext);
NodeList nodes = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
byte[] c14nBytes = c14n.canonicalizeXPathNodeSet(nodes);
InputStream refStream = resolver.resolveEntity(null, fileRef).getByteStream();
byte[] refBytes = JavaUtils.getBytesFromStream(refStream);
assertEquals(new String(refBytes), new String(c14nBytes));
}
use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class Canonicalizer20010315Test method doTestXMLAttributes.
/**
* Method doTestXMLAttributes
*
* @param input
* @param definedOutput
* @param writeResultsToFile
*
* @throws CanonicalizationException
* @throws FileNotFoundException
* @throws IOException
* @throws InvalidCanonicalizerException
* @throws ParserConfigurationException
* @throws SAXException
* @throws TransformerException
* @throws XPathExpressionException
*/
private boolean doTestXMLAttributes(String input, String definedOutput) throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, XPathExpressionException {
DocumentBuilder db = XMLUtils.createDocumentBuilder(true);
db.setErrorHandler(new IgnoreAllErrorHandler());
Document doc = null;
try (InputStream is = new ByteArrayInputStream(input.getBytes())) {
doc = db.parse(is);
}
Canonicalizer c14nizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
// XMLUtils.circumventBug2650(doc);
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
xPath.setNamespaceContext(new DSNamespaceContext());
String xpath = "(//*[local-name()='included'] | //@*[parent::node()[local-name()='included']])";
NodeList nodes = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
byte[] result = c14nizer.canonicalizeXPathNodeSet(nodes);
byte[] defined = definedOutput.getBytes();
assertEquals(definedOutput, new String(result));
return java.security.MessageDigest.isEqual(defined, result);
}
Aggregations