use of org.apache.xml.security.signature.XMLSignatureInput in project santuario-java by apache.
the class ApacheCanonicalizer method transform.
public Data transform(Data data, XMLCryptoContext xc, OutputStream os) throws TransformException {
if (data == null) {
throw new NullPointerException("data must not be null");
}
if (os == null) {
throw new NullPointerException("output stream must not be null");
}
if (ownerDoc == null) {
throw new TransformException("transform must be marshalled");
}
if (apacheTransform == null) {
try {
apacheTransform = new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes());
apacheTransform.setElement(transformElem, xc.getBaseURI());
boolean secVal = Utils.secureValidation(xc);
apacheTransform.setSecureValidation(secVal);
LOG.debug("Created transform for algorithm: {}", getAlgorithm());
} catch (Exception ex) {
throw new TransformException("Couldn't find Transform for: " + getAlgorithm(), ex);
}
}
XMLSignatureInput in;
if (data instanceof ApacheData) {
LOG.debug("ApacheData = true");
in = ((ApacheData) data).getXMLSignatureInput();
} else if (data instanceof NodeSetData) {
LOG.debug("isNodeSet() = true");
if (data instanceof DOMSubTreeData) {
DOMSubTreeData subTree = (DOMSubTreeData) data;
in = new XMLSignatureInput(subTree.getRoot());
in.setExcludeComments(subTree.excludeComments());
} else {
@SuppressWarnings("unchecked") Set<Node> nodeSet = Utils.toNodeSet(((NodeSetData) data).iterator());
in = new XMLSignatureInput(nodeSet);
}
} else {
LOG.debug("isNodeSet() = false");
try {
in = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
} catch (Exception ex) {
throw new TransformException(ex);
}
}
boolean secVal = Utils.secureValidation(xc);
in.setSecureValidation(secVal);
try {
in = apacheTransform.performTransform(in, os);
if (!in.isNodeSet() && !in.isElement()) {
return null;
}
if (in.isOctetStream()) {
return new ApacheOctetStreamData(in);
} else {
return new ApacheNodeSetData(in);
}
} catch (Exception ex) {
throw new TransformException(ex);
}
}
use of org.apache.xml.security.signature.XMLSignatureInput in project santuario-java by apache.
the class DOMReference method transform.
private byte[] transform(Data dereferencedData, XMLCryptoContext context) throws XMLSignatureException {
if (md == null) {
try {
md = MessageDigest.getInstance(((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
}
md.reset();
DigesterOutputStream dos;
Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference");
if (cache != null && cache) {
this.derefData = copyDerefData(dereferencedData);
dos = new DigesterOutputStream(md, true);
} else {
dos = new DigesterOutputStream(md);
}
Data data = dereferencedData;
try (OutputStream os = new UnsyncBufferedOutputStream(dos)) {
for (int i = 0, size = transforms.size(); i < size; i++) {
DOMTransform transform = (DOMTransform) transforms.get(i);
if (i < size - 1) {
data = transform.transform(data, context);
} else {
data = transform.transform(data, context, os);
}
}
if (data != null) {
XMLSignatureInput xi;
// explicitly use C14N 1.1 when generating signature
// first check system property, then context property
boolean c14n11 = useC14N11;
String c14nalg = CanonicalizationMethod.INCLUSIVE;
if (context instanceof XMLSignContext) {
if (!c14n11) {
Boolean prop = (Boolean) context.getProperty("org.apache.xml.security.useC14N11");
c14n11 = prop != null && prop;
if (c14n11) {
c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
}
} else {
c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
}
}
if (data instanceof ApacheData) {
xi = ((ApacheData) data).getXMLSignatureInput();
} else if (data instanceof OctetStreamData) {
xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
} else if (data instanceof NodeSetData) {
TransformService spi = null;
if (provider == null) {
spi = TransformService.getInstance(c14nalg, "DOM");
} else {
try {
spi = TransformService.getInstance(c14nalg, "DOM", provider);
} catch (NoSuchAlgorithmException nsae) {
spi = TransformService.getInstance(c14nalg, "DOM");
}
}
data = spi.transform(data, context);
xi = new XMLSignatureInput(((OctetStreamData) data).getOctetStream());
} else {
throw new XMLSignatureException("unrecognized Data type");
}
boolean secVal = Utils.secureValidation(context);
xi.setSecureValidation(secVal);
if (context instanceof XMLSignContext && c14n11 && !xi.isOctetStream() && !xi.isOutputStreamSet()) {
TransformService spi = null;
if (provider == null) {
spi = TransformService.getInstance(c14nalg, "DOM");
} else {
try {
spi = TransformService.getInstance(c14nalg, "DOM", provider);
} catch (NoSuchAlgorithmException nsae) {
spi = TransformService.getInstance(c14nalg, "DOM");
}
}
DOMTransform t = new DOMTransform(spi);
Element transformsElem = null;
String dsPrefix = DOMUtils.getSignaturePrefix(context);
if (allTransforms.isEmpty()) {
transformsElem = DOMUtils.createElement(refElem.getOwnerDocument(), "Transforms", XMLSignature.XMLNS, dsPrefix);
refElem.insertBefore(transformsElem, DOMUtils.getFirstChildElement(refElem));
} else {
transformsElem = DOMUtils.getFirstChildElement(refElem);
}
XmlWriter xwriter = new XmlWriterToTree(Marshaller.getMarshallers(), transformsElem);
t.marshal(xwriter, dsPrefix, context);
allTransforms.add(t);
xi.updateOutputStream(os, true);
} else {
xi.updateOutputStream(os);
}
}
os.flush();
if (cache != null && cache) {
this.dis = dos.getInputStream();
}
return dos.getDigestValue();
} catch (NoSuchAlgorithmException e) {
throw new XMLSignatureException(e);
} catch (TransformException e) {
throw new XMLSignatureException(e);
} catch (MarshalException e) {
throw new XMLSignatureException(e);
} catch (IOException e) {
throw new XMLSignatureException(e);
} catch (org.apache.xml.security.c14n.CanonicalizationException e) {
throw new XMLSignatureException(e);
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
throw new XMLSignatureException(e);
}
}
}
}
use of org.apache.xml.security.signature.XMLSignatureInput in project santuario-java by apache.
the class XMLSignatureInputTest method testSetOctetStreamGetOctetStream.
@org.junit.Test
public void testSetOctetStreamGetOctetStream() throws IOException, CanonicalizationException, InvalidCanonicalizerException {
InputStream inputStream = new ByteArrayInputStream(_octetStreamTextInput.getBytes(java.nio.charset.StandardCharsets.UTF_8));
XMLSignatureInput input = new XMLSignatureInput(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream res = input.getOctetStream();
int off = 0;
while (res.available() > 0) {
byte[] array = new byte[1024];
int len = res.read(array);
baos.write(array, off, len);
off += len;
}
byte[] resBytes = baos.toByteArray();
String resString = new String(resBytes, java.nio.charset.StandardCharsets.UTF_8);
assertTrue(resString.equals(_octetStreamTextInput));
}
use of org.apache.xml.security.signature.XMLSignatureInput in project santuario-java by apache.
the class XPointerResourceResolver method engineResolveURI.
@Override
public XMLSignatureInput engineResolveURI(ResourceResolverContext context) throws ResourceResolverException {
String v = context.uriToResolve;
if (v.charAt(0) != '#') {
return null;
}
String xpURI;
try {
xpURI = URLDecoder.decode(v, "utf-8");
} catch (UnsupportedEncodingException e) {
LOG.warn("utf-8 not a valid encoding ", e);
return null;
}
String[] parts = xpURI.substring(1).split("\\s");
int i = 0;
Map<String, String> namespaces = new HashMap<>();
if (parts.length > 1) {
for (; i < parts.length - 1; ++i) {
if (!parts[i].endsWith(")") || !parts[i].startsWith(XNS_OPEN)) {
return null;
}
String mapping = parts[i].substring(XNS_OPEN.length(), parts[i].length() - 1);
int pos = mapping.indexOf('=');
if (pos <= 0 || pos >= mapping.length() - 1) {
throw new ResourceResolverException("malformed namespace part of XPointer expression", context.uriToResolve, context.baseUri);
}
namespaces.put(mapping.substring(0, pos), mapping.substring(pos + 1));
}
}
try {
Node node = null;
NodeList nodes = null;
// plain ID reference.
if (i == 0 && !parts[i].startsWith(XP_OPEN)) {
node = this.baseNode.getOwnerDocument().getElementById(parts[i]);
} else {
if (!parts[i].endsWith(")") || !parts[i].startsWith(XP_OPEN)) {
return null;
}
String xpathExpr = parts[i].substring(XP_OPEN.length(), parts[i].length() - 1);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
DSNamespaceContext namespaceContext = new DSNamespaceContext(namespaces);
xpath.setNamespaceContext(namespaceContext);
nodes = (NodeList) xpath.evaluate(xpathExpr, this.baseNode, XPathConstants.NODESET);
if (nodes.getLength() == 0) {
return null;
}
if (nodes.getLength() == 1) {
node = nodes.item(0);
}
}
XMLSignatureInput result = null;
if (node != null) {
result = new XMLSignatureInput(node);
} else if (nodes != null) {
Set<Node> nodeSet = new HashSet<>(nodes.getLength());
for (int j = 0; j < nodes.getLength(); ++j) {
nodeSet.add(nodes.item(j));
}
result = new XMLSignatureInput(nodeSet);
} else {
return null;
}
result.setMIMEType("text/xml");
result.setExcludeComments(true);
result.setSourceURI((context.baseUri != null) ? context.baseUri.concat(v) : v);
return result;
} catch (XPathExpressionException e) {
throw new ResourceResolverException(e, context.uriToResolve, context.baseUri, "Problem evaluating XPath expression");
}
}
use of org.apache.xml.security.signature.XMLSignatureInput in project santuario-java by apache.
the class TransformBase64DecodeTest method test3.
@org.junit.Test
public void test3() throws Exception {
// J-
String input = "" + "<Object xmlns:signature='http://www.w3.org/2000/09/xmldsig#'>\n" + "<signature:Base64>\n" + "VGhlIFVSSSBvZiB0aGU gdHJhbn<RealText>Nmb 3JtIGlzIG<test/>h0dHA6</RealText>Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n" + "ZHNpZyNiYXNlNjQ=\n" + "</signature:Base64>\n" + "</Object>\n";
// J+
DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
Document doc = null;
try (InputStream is = new ByteArrayInputStream(input.getBytes())) {
doc = db.parse(is);
}
// XMLUtils.circumventBug2650(doc);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
String expression = "//ds:Base64";
Node base64Node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
XMLSignatureInput xmlinput = new XMLSignatureInput(base64Node);
Document doc2 = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc2);
doc2.appendChild(t.getElement());
t.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
XMLSignatureInput out = t.performTransforms(xmlinput);
String result = new String(out.getBytes());
assertTrue("\"" + result + "\"", result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64"));
}
Aggregations