use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class AbstractSignatureVerificationTest method signUsingDOM.
/**
* Sign the document using DOM
*/
protected XMLSignature signUsingDOM(String algorithm, Document document, List<String> localNames, Key signingKey, String c14nMethod, String digestMethod, List<ReferenceInfo> additionalReferences, String referenceC14NMethod, ResourceResolverSpi resourceResolverSpi) throws Exception {
XMLSignature sig = new XMLSignature(document, "", algorithm, c14nMethod);
if (resourceResolverSpi != null) {
sig.addResourceResolver(resourceResolverSpi);
}
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(referenceC14NMethod);
sig.addDocument("#" + id, transforms, digestMethod);
}
}
if (additionalReferences != null) {
for (int i = 0; i < additionalReferences.size(); i++) {
ReferenceInfo referenceInfo = additionalReferences.get(i);
if (referenceInfo.isBinary()) {
sig.addDocument(referenceInfo.getResource(), null, referenceInfo.getDigestMethod());
} else {
Transforms transforms = new Transforms(document);
for (int j = 0; j < referenceInfo.getC14NMethod().length; j++) {
String transform = referenceInfo.getC14NMethod()[j];
transforms.addTransform(transform);
}
sig.addDocument(referenceInfo.getResource(), transforms, referenceInfo.getDigestMethod());
}
}
}
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 KeyWrapEncryptionVerificationTest method encrypt.
private void encrypt(EncryptedKey encryptedKey, String algorithm, Document document, List<String> localNames, Key encryptingKey) throws Exception {
XMLCipher cipher = XMLCipher.getInstance(algorithm);
cipher.init(XMLCipher.ENCRYPT_MODE, encryptingKey);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
EncryptedData builder = cipher.getEncryptedData();
KeyInfo builderKeyInfo = builder.getKeyInfo();
if (builderKeyInfo == null) {
builderKeyInfo = new KeyInfo(document);
builder.setKeyInfo(builderKeyInfo);
}
builderKeyInfo.add(encryptedKey);
for (String localName : localNames) {
String expression = "//*[local-name()='" + localName + "']";
Element elementToEncrypt = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
Assert.assertNotNull(elementToEncrypt);
document = cipher.doFinal(document, elementToEncrypt, false);
}
NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
Assert.assertTrue(nodeList.getLength() > 0);
}
use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class SymmetricEncryptionVerificationTest method encryptUsingDOM.
/**
* Encrypt the document using DOM APIs and run some tests on the encrypted Document.
*/
private void encryptUsingDOM(String algorithm, SecretKey secretKey, String keyTransportAlgorithm, Key wrappingKey, boolean includeWrappingKeyInfo, Document document, List<String> localNames, boolean content) throws Exception {
XMLCipher cipher = XMLCipher.getInstance(algorithm);
cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
if (wrappingKey != null) {
XMLCipher newCipher = XMLCipher.getInstance(keyTransportAlgorithm);
newCipher.init(XMLCipher.WRAP_MODE, wrappingKey);
EncryptedKey encryptedKey = newCipher.encryptKey(document, secretKey);
if (includeWrappingKeyInfo && wrappingKey instanceof PublicKey) {
// Create a KeyInfo for the EncryptedKey
KeyInfo encryptedKeyKeyInfo = encryptedKey.getKeyInfo();
if (encryptedKeyKeyInfo == null) {
encryptedKeyKeyInfo = new KeyInfo(document);
encryptedKeyKeyInfo.getElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#");
encryptedKey.setKeyInfo(encryptedKeyKeyInfo);
}
encryptedKeyKeyInfo.add((PublicKey) wrappingKey);
}
EncryptedData builder = cipher.getEncryptedData();
KeyInfo builderKeyInfo = builder.getKeyInfo();
if (builderKeyInfo == null) {
builderKeyInfo = new KeyInfo(document);
builderKeyInfo.getElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#");
builder.setKeyInfo(builderKeyInfo);
}
builderKeyInfo.add(encryptedKey);
}
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
for (String localName : localNames) {
String expression = "//*[local-name()='" + localName + "']";
Element elementToEncrypt = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
Assert.assertNotNull(elementToEncrypt);
document = cipher.doFinal(document, elementToEncrypt, content);
}
NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
Assert.assertTrue(nodeList.getLength() > 0);
}
use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.
the class InteropTestBase method verify.
public boolean verify(String filename, ResourceResolverSpi resolver, boolean followManifests, boolean secureValidation) throws Exception {
File f = new File(filename);
javax.xml.parsers.DocumentBuilder db = XMLUtils.createDocumentBuilder(false, false);
org.w3c.dom.Document doc = db.parse(f);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
String expression = "//ds:Signature[1]";
Element sigElement = (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
XMLSignature signature = new XMLSignature(sigElement, f.toURI().toURL().toString(), secureValidation);
if (resolver != null) {
signature.addResourceResolver(resolver);
}
signature.setFollowNestedManifests(followManifests);
KeyInfo ki = signature.getKeyInfo();
boolean result = false;
if (ki != null) {
X509Certificate cert = ki.getX509Certificate();
if (cert != null) {
result = signature.checkSignatureValue(cert);
} else {
PublicKey pk = ki.getPublicKey();
if (pk != null) {
result = signature.checkSignatureValue(pk);
} else {
throw new RuntimeException("Did not find a public key, so I can't check the signature");
}
}
checkReferences(signature);
} else {
throw new RuntimeException("Did not find a KeyInfo");
}
if (!result) {
for (int i = 0; i < signature.getSignedInfo().getLength(); i++) {
boolean refVerify = signature.getSignedInfo().getVerificationResult(i);
if (refVerify) {
LOG.debug("Reference " + i + " was OK");
} else {
// JavaUtils.writeBytesToFilename(filename + i + ".apache.txt", signature.getSignedInfo().item(i).getContentsAfterTransformation().getBytes());
LOG.debug("Reference " + i + " was not OK");
}
}
checkReferences(signature);
// throw new RuntimeException("Falle:"+sb.toString());
}
return result;
}
use of org.apache.xml.security.test.dom.DSNamespaceContext 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;
}
Aggregations