undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,513 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* This class does the configuration of the library. This includes creating
* the mapping of Canonicalization and Transform algorithms. Initialization is
* done by calling {@link Init#init} which should be done in any static block
* of the files of this library. We ensure that this call is only executed once.
*/
public class Init {
/**
* The namespace for CONF file
**/
public static final String CONF_NS = "http://www.xmlsecurity.org/NS/#configuration";
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(Init.class);
/**
* Field alreadyInitialized
*/
private static boolean alreadyInitialized = false;
/**
* Method isInitialized
*
* @return true if the library is already initialized.
*/
public static final synchronized boolean isInitialized() {
return Init.alreadyInitialized;
}
/**
* Method init
*/
public static synchronized void init() {
if (alreadyInitialized) {
return;
}
PrivilegedAction<InputStream> action = () -> {
String cfile = System.getProperty("com.sun.org.apache.xml.internal.security.resource.config");
if (cfile == null) {
return null;
}
return getResourceAsStream(cfile, Init.class);
};
try (@SuppressWarnings("removal")
InputStream is = AccessController.doPrivileged(action)) {
if (is == null) {
dynamicInit();
} else {
fileInit(is);
}
} catch (IOException ex) {
LOG.warn(ex.getMessage(), ex);
}
alreadyInitialized = true;
}
/**
* Dynamically initialise the library by registering the default algorithms/implementations
*/
@SuppressWarnings("removal")
private static void dynamicInit() {
//
// Load the Resource Bundle - the default is the English resource bundle.
// To load another resource bundle, call I18n.init(...) before calling this
// method.
//
I18n.init("en", "US");
LOG.debug("Registering default algorithms");
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>(){
@Override public Void run() throws XMLSecurityException {
//
// Bind the default prefixes
//
ElementProxy.registerDefaultPrefixes();
//
// Set the default Transforms
//
Transform.registerDefaultAlgorithms();
//
// Set the default signature algorithms
//
SignatureAlgorithm.registerDefaultAlgorithms();
//
// Set the default JCE algorithms
//
JCEMapper.registerDefaultAlgorithms();
//
// Set the default c14n algorithms
//
Canonicalizer.registerDefaultAlgorithms();
//
// Register the default resolvers
//
ResourceResolver.registerDefaultResolvers();
//
// Register the default key resolvers
//
KeyResolver.registerDefaultResolvers();
return null;
}
});
} catch (PrivilegedActionException ex) {
XMLSecurityException xse = (XMLSecurityException)ex.getException();
LOG.error(xse.getMessage(), xse);
xse.printStackTrace();
}
}
/**
* Initialise the library from a configuration file
*/
private static void fileInit(InputStream is) {
try {
/* read library configuration file */
Document doc = XMLUtils.read(is, true);
Node config = doc.getFirstChild();
for (; config != null; config = config.getNextSibling()) {
if ("Configuration".equals(config.getLocalName())) {
break;
}
}
if (config == null) {
LOG.error("Error in reading configuration file - Configuration element not found");
return;
}
for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) {
if (Node.ELEMENT_NODE != el.getNodeType()) {
continue;
}
String tag = el.getLocalName();
if ("ResourceBundles".equals(tag)) {
Element resource = (Element)el;
/* configure internationalization */
Attr langAttr = resource.getAttributeNodeNS(null, "defaultLanguageCode");
Attr countryAttr = resource.getAttributeNodeNS(null, "defaultCountryCode");
String languageCode =
(langAttr == null) ? null : langAttr.getNodeValue();
String countryCode =
(countryAttr == null) ? null : countryAttr.getNodeValue();
I18n.init(languageCode, countryCode);
}
if ("CanonicalizationMethods".equals(tag)) {
Element[] list =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod");
for (Element element : list) {
String uri = element.getAttributeNS(null, "URI");
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
try {
Canonicalizer.register(uri, javaClass);
LOG.debug("Canonicalizer.register({}, {})", uri, javaClass);
} catch (ClassNotFoundException e) {
Object[] exArgs = { uri, javaClass };
LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
}
}
}
if ("TransformAlgorithms".equals(tag)) {
Element[] tranElem =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm");
for (Element element : tranElem) {
String uri = element.getAttributeNS(null, "URI");
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
try {
Transform.register(uri, javaClass);
LOG.debug("Transform.register({}, {})", uri, javaClass);
} catch (ClassNotFoundException e) {
Object[] exArgs = { uri, javaClass };
LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
} catch (NoClassDefFoundError ex) {
LOG.warn("Not able to found dependencies for algorithm, I'll keep working.");
}
}
}
if ("JCEAlgorithmMappings".equals(tag)) {
Node algorithmsNode = ((Element)el).getElementsByTagName("Algorithms").item(0);
if (algorithmsNode != null) {
Element[] algorithms =
XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm");
for (Element element : algorithms) {
String id = element.getAttributeNS(null, "URI");
JCEMapper.register(id, new JCEMapper.Algorithm(element));
}
}
}
if ("SignatureAlgorithms".equals(tag)) {
Element[] sigElems =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm");
for (Element sigElem : sigElems) {
String uri = sigElem.getAttributeNS(null, "URI");
String javaClass =
sigElem.getAttributeNS(null, "JAVACLASS");
/** $todo$ handle registering */
try {
SignatureAlgorithm.register(uri, javaClass);
LOG.debug("SignatureAlgorithm.register({}, {})", uri, javaClass);
} catch (ClassNotFoundException e) {
Object[] exArgs = { uri, javaClass };
LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs));
}
}
}
if ("ResourceResolvers".equals(tag)) {
Element[] resolverElem =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
List<String> classNames = new ArrayList<>(resolverElem.length);
for (Element element : resolverElem) {
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
String description =
element.getAttributeNS(null, "DESCRIPTION");
if (description != null && description.length() > 0) {
LOG.debug("Register Resolver: {}: {}", javaClass, description);
} else {
LOG.debug("Register Resolver: {}: For unknown purposes", javaClass);
}
classNames.add(javaClass);
}
ResourceResolver.registerClassNames(classNames);
}
if ("KeyResolver".equals(tag)){
Element[] resolverElem =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver");
List<String> classNames = new ArrayList<>(resolverElem.length);
for (Element element : resolverElem) {
String javaClass =
element.getAttributeNS(null, "JAVACLASS");
String description =
element.getAttributeNS(null, "DESCRIPTION");
if (description != null && description.length() > 0) {
LOG.debug("Register Resolver: {}: {}", javaClass, description);
} else {
LOG.debug("Register Resolver: {}: For unknown purposes", javaClass);
}
classNames.add(javaClass);
}
KeyResolver.registerClassNames(classNames);
}
if ("PrefixMappings".equals(tag)){
LOG.debug("Now I try to bind prefixes:");
Element[] nl =
XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping");
for (Element element : nl) {
String namespace = element.getAttributeNS(null, "namespace");
String prefix = element.getAttributeNS(null, "prefix");
LOG.debug("Now I try to bind {} to {}", prefix, namespace);
ElementProxy.setDefaultPrefix(namespace, prefix);
}
}
}
} catch (Exception e) {
LOG.error("Bad: ", e);
}
}
/**
* Load a given resource. <p></p> This method will try to load the resource
* using the following methods (in order):
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>callingClass.getClassLoader()
* </ul>
*
* @param resourceName The name of the resource to load
* @param callingClass The Class object of the calling object
*/
public static URL getResource(String resourceName, Class<?> callingClass) {
if (resourceName == null) {
throw new NullPointerException();
}
URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
if (url == null && resourceName.charAt(0) == '/') {
//certain classloaders need it without the leading /
url =
Thread.currentThread().getContextClassLoader().getResource(
resourceName.substring(1)
);
}
ClassLoader cluClassloader = Init.class.getClassLoader();
if (cluClassloader == null) {
cluClassloader = ClassLoader.getSystemClassLoader();
}
if (url == null) {
url = cluClassloader.getResource(resourceName);
}
if (url == null && resourceName.charAt(0) == '/') {
//certain classloaders need it without the leading /
url = cluClassloader.getResource(resourceName.substring(1));
}
if (url == null) {
ClassLoader cl = callingClass.getClassLoader();
if (cl != null) {
url = cl.getResource(resourceName);
}
}
if (url == null) {
url = callingClass.getResource(resourceName);
}
if (url == null && resourceName.charAt(0) != '/') {
return getResource('/' + resourceName, callingClass);
}
return url;
}
/**
* Load a given resources. <p></p> This method will try to load the resources
* using the following methods (in order):
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>callingClass.getClassLoader()
* </ul>
*
* @param resourceName The name of the resource to load
* @param callingClass The Class object of the calling object
*/
private static List<URL> getResources(String resourceName, Class<?> callingClass) {
if (resourceName == null) {
throw new NullPointerException();
}
List<URL> ret = new ArrayList<>();
Enumeration<URL> urls = new Enumeration<URL>() {
@Override
public boolean hasMoreElements() {
return false;
}
@Override
public URL nextElement() {
return null;
}
};
try {
urls = Thread.currentThread().getContextClassLoader().getResources(resourceName);
} catch (IOException e) {
LOG.debug(e.getMessage(), e);
//ignore
}
if (!urls.hasMoreElements() && resourceName.charAt(0) == '/') {
//certain classloaders need it without the leading /
try {
urls =
Thread.currentThread().getContextClassLoader().getResources(
resourceName.substring(1)
);
} catch (IOException e) {
LOG.debug(e.getMessage(), e);
// ignore
}
}
ClassLoader cluClassloader = Init.class.getClassLoader();
if (cluClassloader == null) {
cluClassloader = ClassLoader.getSystemClassLoader();
}
if (!urls.hasMoreElements()) {
try {
urls = cluClassloader.getResources(resourceName);
} catch (IOException e) {
LOG.debug(e.getMessage(), e);
// ignore
}
}
if (!urls.hasMoreElements() && resourceName.charAt(0) == '/') {
//certain classloaders need it without the leading /
try {
urls = cluClassloader.getResources(resourceName.substring(1));
} catch (IOException e) {
LOG.debug(e.getMessage(), e);
// ignore
}
}
if (!urls.hasMoreElements()) {
ClassLoader cl = callingClass.getClassLoader();
if (cl != null) {
try {
urls = cl.getResources(resourceName);
} catch (IOException e) {
LOG.debug(e.getMessage(), e);
// ignore
}
}
}
if (!urls.hasMoreElements()) {
URL url = callingClass.getResource(resourceName);
if (url != null) {
ret.add(url);
}
}
while (urls.hasMoreElements()) {
ret.add(urls.nextElement());
}
if (ret.isEmpty() && resourceName.charAt(0) != '/') {
return getResources('/' + resourceName, callingClass);
}
return ret;
}
/**
* This is a convenience method to load a resource as a stream. <p></p> The
* algorithm used to find the resource is given in getResource()
*
* @param resourceName The name of the resource to load
* @param callingClass The Class object of the calling object
*/
private static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
URL url = getResource(resourceName, callingClass);
try {
return (url != null) ? url.openStream() : null;
} catch (IOException e) {
LOG.debug(e.getMessage(), e);
return null;
}
}
}

View file

@ -0,0 +1,76 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* The Algorithm class which stores the Algorithm URI as a string.
*/
public abstract class Algorithm extends SignatureElementProxy {
/**
*
* @param doc
* @param algorithmURI is the URI of the algorithm as String
*/
public Algorithm(Document doc, String algorithmURI) {
super(doc);
this.setAlgorithmURI(algorithmURI);
}
/**
* Constructor Algorithm
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public Algorithm(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Method getAlgorithmURI
*
* @return The URI of the algorithm
*/
public String getAlgorithmURI() {
return getLocalAttribute(Constants._ATT_ALGORITHM);
}
/**
* Sets the algorithm's URI as used in the signature.
*
* @param algorithmURI is the URI of the algorithm as String
*/
protected void setAlgorithmURI(String algorithmURI) {
if (algorithmURI != null) {
setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
}
}
}

View file

@ -0,0 +1,84 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
// modifiers changed to package-private. Make sure to integrate any future
// changes to utils.ClassLoaderUtils to this file.
final class ClassLoaderUtils {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
private ClassLoaderUtils() {
}
/**
* Load a class with a given name. <p></p> It will try to load the class in the
* following order:
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>Using the basic Class.forName()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>From the callingClass.getClassLoader()
* </ul>
*
* @param className The name of the class to load
* @param callingClass The Class object of the calling object
* @throws ClassNotFoundException If the class cannot be found anywhere.
*/
static Class<?> loadClass(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return cl.loadClass(className);
}
} catch (ClassNotFoundException e) {
LOG.debug(e.getMessage(), e);
//ignore
}
return loadClass2(className, callingClass);
}
private static Class<?> loadClass2(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
try {
if (ClassLoaderUtils.class.getClassLoader() != null) {
return ClassLoaderUtils.class.getClassLoader().loadClass(className);
}
} catch (ClassNotFoundException exc) {
if (callingClass != null && callingClass.getClassLoader() != null) {
return callingClass.getClassLoader().loadClass(className);
}
}
LOG.debug(ex.getMessage(), ex);
throw ex;
}
}
}

View file

@ -0,0 +1,452 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Element;
/**
* This class maps algorithm identifier URIs to JAVA JCE class names.
*/
public class JCEMapper {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(JCEMapper.class);
private static Map<String, Algorithm> algorithmsMap = new ConcurrentHashMap<>();
private static String globalProviderName;
private static final ThreadLocal<String> threadSpecificProviderName = new ThreadLocal<>();
/**
* Method register
*
* @param id
* @param algorithm
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the JCE algorithm
*/
public static void register(String id, Algorithm algorithm) {
JavaUtils.checkRegisterPermission();
algorithmsMap.put(id, algorithm);
}
/**
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
// Digest algorithms
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5,
new Algorithm("", "MD5", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160,
new Algorithm("", "RIPEMD160", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1,
new Algorithm("", "SHA-1", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA224,
new Algorithm("", "SHA-224", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256,
new Algorithm("", "SHA-256", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384,
new Algorithm("", "SHA-384", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512,
new Algorithm("", "SHA-512", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_WHIRLPOOL,
new Algorithm("", "WHIRLPOOL", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_224,
new Algorithm("", "SHA3-224", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_256,
new Algorithm("", "SHA3-256", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_384,
new Algorithm("", "SHA3-384", "MessageDigest")
);
algorithmsMap.put(
MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA3_512,
new Algorithm("", "SHA3-512", "MessageDigest")
);
// Signature algorithms
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA,
new Algorithm("DSA", "SHA1withDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256,
new Algorithm("DSA", "SHA256withDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
new Algorithm("RSA", "MD5withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
new Algorithm("RSA", "RIPEMD160withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
new Algorithm("RSA", "SHA1withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224,
new Algorithm("RSA", "SHA224withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,
new Algorithm("RSA", "SHA256withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384,
new Algorithm("RSA", "SHA384withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
new Algorithm("RSA", "SHA512withRSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1,
new Algorithm("RSA", "SHA1withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1,
new Algorithm("RSA", "SHA224withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1,
new Algorithm("RSA", "SHA256withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1,
new Algorithm("RSA", "SHA384withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1,
new Algorithm("RSA", "SHA512withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1,
new Algorithm("RSA", "SHA3-224withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1,
new Algorithm("RSA", "SHA3-256withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1,
new Algorithm("RSA", "SHA3-384withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1,
new Algorithm("RSA", "SHA3-512withRSAandMGF1", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_PSS,
new Algorithm("RSA", "RSASSA-PSS", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1,
new Algorithm("EC", "SHA1withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224,
new Algorithm("EC", "SHA224withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256,
new Algorithm("EC", "SHA256withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384,
new Algorithm("EC", "SHA384withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512,
new Algorithm("EC", "SHA512withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_224,
new Algorithm("EC", "SHA3-224withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_256,
new Algorithm("EC", "SHA3-256withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_384,
new Algorithm("EC", "SHA3-384withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_512,
new Algorithm("EC", "SHA3-512withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160,
new Algorithm("EC", "RIPEMD160withECDSA", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_EDDSA_ED25519,
new Algorithm("Ed25519", "Ed25519", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_SIGNATURE_EDDSA_ED448,
new Algorithm("Ed448", "Ed448", "Signature")
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
new Algorithm("", "HmacMD5", "Mac", 0, 0)
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160,
new Algorithm("", "HMACRIPEMD160", "Mac", 0, 0)
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
new Algorithm("", "HmacSHA1", "Mac", 0, 0)
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA224,
new Algorithm("", "HmacSHA224", "Mac", 0, 0)
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA256,
new Algorithm("", "HmacSHA256", "Mac", 0, 0)
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA384,
new Algorithm("", "HmacSHA384", "Mac", 0, 0)
);
algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA512,
new Algorithm("", "HmacSHA512", "Mac", 0, 0)
);
}
/**
* Method translateURItoJCEID
*
* @param algorithmURI
* @return the JCE standard name corresponding to the given URI
*/
public static String translateURItoJCEID(String algorithmURI) {
Algorithm algorithm = getAlgorithm(algorithmURI);
if (algorithm != null) {
return algorithm.jceName;
}
return null;
}
/**
* Method getAlgorithmClassFromURI
* @param algorithmURI
* @return the class name that implements this algorithm
*/
public static String getAlgorithmClassFromURI(String algorithmURI) {
Algorithm algorithm = getAlgorithm(algorithmURI);
if (algorithm != null) {
return algorithm.algorithmClass;
}
return null;
}
/**
* Returns the keylength in bits for a particular algorithm.
*
* @param algorithmURI
* @return The length of the key used in the algorithm
*/
public static int getKeyLengthFromURI(String algorithmURI) {
Algorithm algorithm = getAlgorithm(algorithmURI);
if (algorithm != null) {
return algorithm.keyLength;
}
return 0;
}
public static int getIVLengthFromURI(String algorithmURI) {
Algorithm algorithm = getAlgorithm(algorithmURI);
if (algorithm != null) {
return algorithm.ivLength;
}
return 0;
}
/**
* Method getJCEKeyAlgorithmFromURI
*
* @param algorithmURI
* @return The KeyAlgorithm for the given URI.
*/
public static String getJCEKeyAlgorithmFromURI(String algorithmURI) {
Algorithm algorithm = getAlgorithm(algorithmURI);
if (algorithm != null) {
return algorithm.requiredKey;
}
return null;
}
/**
* Method getJCEProviderFromURI
*
* @param algorithmURI
* @return The JCEProvider for the given URI.
*/
public static String getJCEProviderFromURI(String algorithmURI) {
Algorithm algorithm = getAlgorithm(algorithmURI);
if (algorithm != null) {
return algorithm.jceProvider;
}
return null;
}
/**
* Method getAlgorithm
*
* @param algorithmURI
* @return The Algorithm object for the given URI.
*/
private static Algorithm getAlgorithm(String algorithmURI) {
LOG.debug("Request for URI {}", algorithmURI);
if (algorithmURI != null) {
return algorithmsMap.get(algorithmURI);
}
return null;
}
/**
* Gets the default Provider for obtaining the security algorithms
* @return the default providerId.
*/
public static String getProviderId() {
if (threadSpecificProviderName.get() != null) {
return threadSpecificProviderName.get();
}
return globalProviderName;
}
/**
* Sets the default Provider for obtaining the security algorithms
* @param provider the default providerId.
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the JCE algorithm
*/
public static void setProviderId(String provider) {
JavaUtils.checkRegisterPermission();
globalProviderName = provider;
}
/**
* Sets the default Provider for this thread to obtain the security algorithms
* @param threadSpecificProviderName the default providerId.
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the JCE algorithm
*/
public static void setThreadSpecificProviderName(String threadSpecificProviderName) {
JavaUtils.checkRegisterPermission();
JCEMapper.threadSpecificProviderName.set(threadSpecificProviderName);
}
/**
* Represents the Algorithm xml element
*/
public static class Algorithm {
final String requiredKey;
final String jceName;
final String algorithmClass;
final int keyLength;
final int ivLength;
final String jceProvider;
/**
* Gets data from element
* @param el
*/
public Algorithm(Element el) {
requiredKey = el.getAttributeNS(null, "RequiredKey");
jceName = el.getAttributeNS(null, "JCEName");
algorithmClass = el.getAttributeNS(null, "AlgorithmClass");
jceProvider = el.getAttributeNS(null, "JCEProvider");
if (el.hasAttribute("KeyLength")) {
keyLength = Integer.parseInt(el.getAttributeNS(null, "KeyLength"));
} else {
keyLength = 0;
}
if (el.hasAttribute("IVLength")) {
ivLength = Integer.parseInt(el.getAttributeNS(null, "IVLength"));
} else {
ivLength = 0;
}
}
public Algorithm(String requiredKey, String jceName) {
this(requiredKey, jceName, null, 0, 0);
}
public Algorithm(String requiredKey, String jceName, String algorithmClass) {
this(requiredKey, jceName, algorithmClass, 0, 0);
}
public Algorithm(String requiredKey, String jceName, int keyLength) {
this(requiredKey, jceName, null, keyLength, 0);
}
public Algorithm(String requiredKey, String jceName, String algorithmClass, int keyLength, int ivLength) {
this(requiredKey, jceName, algorithmClass, keyLength, ivLength, null);
}
public Algorithm(String requiredKey, String jceName,
String algorithmClass, int keyLength, int ivLength, String jceProvider) {
this.requiredKey = requiredKey;
this.jceName = jceName;
this.algorithmClass = algorithmClass;
this.keyLength = keyLength;
this.ivLength = ivLength;
this.jceProvider = jceProvider;
}
}
}

View file

@ -0,0 +1,269 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
import org.w3c.dom.Document;
/**
* Digest Message wrapper and selector class.
*
* <pre>
* MessageDigestAlgorithm.getInstance()
* </pre>
*/
public final class MessageDigestAlgorithm extends Algorithm {
/** Message Digest - NOT RECOMMENDED MD5*/
public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 =
Constants.MoreAlgorithmsSpecNS + "md5";
/** Digest - Required SHA1*/
public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
/** Message Digest - OPTIONAL SHA224*/
public static final String ALGO_ID_DIGEST_SHA224 =
Constants.MoreAlgorithmsSpecNS + "sha224";
/** Message Digest - RECOMMENDED SHA256*/
public static final String ALGO_ID_DIGEST_SHA256 =
EncryptionConstants.EncryptionSpecNS + "sha256";
/** Message Digest - OPTIONAL SHA384*/
public static final String ALGO_ID_DIGEST_SHA384 =
Constants.MoreAlgorithmsSpecNS + "sha384";
/** Message Digest - OPTIONAL SHA512*/
public static final String ALGO_ID_DIGEST_SHA512 =
EncryptionConstants.EncryptionSpecNS + "sha512";
/** Message Digest - OPTIONAL RIPEMD-160*/
public static final String ALGO_ID_DIGEST_RIPEMD160 =
EncryptionConstants.EncryptionSpecNS + "ripemd160";
// Newer digest algorithms...all optional
public static final String ALGO_ID_DIGEST_WHIRLPOOL =
Constants.XML_DSIG_NS_MORE_07_05 + "whirlpool";
public static final String ALGO_ID_DIGEST_SHA3_224 =
Constants.XML_DSIG_NS_MORE_07_05 + "sha3-224";
public static final String ALGO_ID_DIGEST_SHA3_256 =
Constants.XML_DSIG_NS_MORE_07_05 + "sha3-256";
public static final String ALGO_ID_DIGEST_SHA3_384 =
Constants.XML_DSIG_NS_MORE_07_05 + "sha3-384";
public static final String ALGO_ID_DIGEST_SHA3_512 =
Constants.XML_DSIG_NS_MORE_07_05 + "sha3-512";
/** Field algorithm stores the actual {@link java.security.MessageDigest} */
private final MessageDigest algorithm;
/**
* Constructor for the brave who pass their own message digest algorithms and the
* corresponding URI.
* @param doc
* @param algorithmURI
*/
private MessageDigestAlgorithm(Document doc, String algorithmURI)
throws XMLSignatureException {
super(doc, algorithmURI);
algorithm = getDigestInstance(algorithmURI);
}
/**
* Factory method for constructing a message digest algorithm by name.
*
* @param doc
* @param algorithmURI
* @return The MessageDigestAlgorithm element to attach in document and to digest
* @throws XMLSignatureException
*/
public static MessageDigestAlgorithm getInstance(
Document doc, String algorithmURI
) throws XMLSignatureException {
return new MessageDigestAlgorithm(doc, algorithmURI);
}
public static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
if (algorithmID == null) {
Object[] exArgs = { algorithmURI };
throw new XMLSignatureException("algorithms.NoSuchMap", exArgs);
}
MessageDigest md;
String provider = JCEMapper.getProviderId();
try {
if (provider == null) {
md = MessageDigest.getInstance(algorithmID);
} else {
md = MessageDigest.getInstance(algorithmID, provider);
}
} catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
return md;
}
/**
* Returns the actual {@link java.security.MessageDigest} algorithm object
*
* @return the actual {@link java.security.MessageDigest} algorithm object
*/
public MessageDigest getAlgorithm() {
return algorithm;
}
/**
* Proxy method for {@link java.security.MessageDigest#isEqual}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @param digesta
* @param digestb
* @return the result of the {@link java.security.MessageDigest#isEqual} method
*/
public static boolean isEqual(byte[] digesta, byte[] digestb) {
return MessageDigest.isEqual(digesta, digestb);
}
/**
* Proxy method for {@link java.security.MessageDigest#digest()}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @return the result of the {@link java.security.MessageDigest#digest()} method
*/
public byte[] digest() {
return algorithm.digest();
}
/**
* Proxy method for {@link java.security.MessageDigest#digest(byte[])}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @param input
* @return the result of the {@link java.security.MessageDigest#digest(byte[])} method
*/
public byte[] digest(byte[] input) {
return algorithm.digest(input);
}
/**
* Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @param buf
* @param offset
* @param len
* @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method
* @throws java.security.DigestException
*/
public int digest(byte[] buf, int offset, int len) throws java.security.DigestException {
return algorithm.digest(buf, offset, len);
}
/**
* Proxy method for {@link java.security.MessageDigest#getAlgorithm}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @return the result of the {@link java.security.MessageDigest#getAlgorithm} method
*/
public String getJCEAlgorithmString() {
return algorithm.getAlgorithm();
}
/**
* Proxy method for {@link java.security.MessageDigest#getProvider}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @return the result of the {@link java.security.MessageDigest#getProvider} method
*/
public java.security.Provider getJCEProvider() {
return algorithm.getProvider();
}
/**
* Proxy method for {@link java.security.MessageDigest#getDigestLength}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @return the result of the {@link java.security.MessageDigest#getDigestLength} method
*/
public int getDigestLength() {
return algorithm.getDigestLength();
}
/**
* Proxy method for {@link java.security.MessageDigest#reset}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
*/
public void reset() {
algorithm.reset();
}
/**
* Proxy method for {@link java.security.MessageDigest#update(byte[])}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @param input
*/
public void update(byte[] input) {
algorithm.update(input);
}
/**
* Proxy method for {@link java.security.MessageDigest#update(byte)}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @param input
*/
public void update(byte input) {
algorithm.update(input);
}
/**
* Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)}
* which is executed on the internal {@link java.security.MessageDigest} object.
*
* @param buf
* @param offset
* @param len
*/
public void update(byte[] buf, int offset, int len) {
algorithm.update(buf, offset, len);
}
/** {@inheritDoc} */
@Override
public String getBaseNamespace() {
return Constants.SignatureSpecNS;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_DIGESTMETHOD;
}
}

View file

@ -0,0 +1,557 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.Key;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureDSA;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureEDDSA;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Allows selection of digital signature's algorithm, private keys, other
* security parameters, and algorithm's ID.
*
*/
public class SignatureAlgorithm extends Algorithm {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureAlgorithm.class);
/** All available algorithm classes are registered here */
private static Map<String, Class<? extends SignatureAlgorithmSpi>> algorithmHash =
new ConcurrentHashMap<>();
/** Field signatureAlgorithm */
private final SignatureAlgorithmSpi signatureAlgorithmSpi;
private final String algorithmURI;
/**
* Constructor SignatureAlgorithm
*
* @param doc
* @param algorithmURI
* @throws XMLSecurityException
*/
public SignatureAlgorithm(Document doc, String algorithmURI) throws XMLSecurityException {
this(doc, algorithmURI, null);
}
public SignatureAlgorithm(Document doc, String algorithmURI, Provider provider) throws XMLSecurityException {
this(doc, algorithmURI, provider, null);
}
public SignatureAlgorithm(Document doc, String algorithmURI, Provider provider, AlgorithmParameterSpec parameterSpec) throws XMLSecurityException {
super(doc, algorithmURI);
this.algorithmURI = algorithmURI;
signatureAlgorithmSpi = getSignatureAlgorithmSpi(algorithmURI, provider);
if (parameterSpec != null) {
signatureAlgorithmSpi.engineSetParameter(parameterSpec);
signatureAlgorithmSpi.engineAddContextToElement(getElement());
}
}
/**
* Constructor SignatureAlgorithm
*
* @param doc
* @param algorithmURI
* @param hmacOutputLength
* @throws XMLSecurityException
*/
public SignatureAlgorithm(
Document doc, String algorithmURI, int hmacOutputLength
) throws XMLSecurityException {
this(doc, algorithmURI, hmacOutputLength, null);
}
public SignatureAlgorithm(
Document doc, String algorithmURI, int hmacOutputLength, Provider provider
) throws XMLSecurityException {
super(doc, algorithmURI);
this.algorithmURI = algorithmURI;
signatureAlgorithmSpi = getSignatureAlgorithmSpi(algorithmURI, provider);
signatureAlgorithmSpi.engineSetHMACOutputLength(hmacOutputLength);
signatureAlgorithmSpi.engineAddContextToElement(getElement());
}
/**
* Constructor SignatureAlgorithm
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException {
this(element, baseURI, true, null);
}
public SignatureAlgorithm(Element element, String baseURI, Provider provider) throws XMLSecurityException {
this(element, baseURI, true, provider);
}
/**
* Constructor SignatureAlgorithm
*
* @param element
* @param baseURI
* @param secureValidation
* @throws XMLSecurityException
*/
public SignatureAlgorithm(
Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
this(element, baseURI, secureValidation, null);
}
public SignatureAlgorithm(
Element element, String baseURI, boolean secureValidation, Provider provider
) throws XMLSecurityException {
super(element, baseURI);
algorithmURI = this.getURI();
Attr attr = element.getAttributeNodeNS(null, "Id");
if (attr != null) {
element.setIdAttributeNode(attr, true);
}
if (secureValidation && (XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(algorithmURI)
|| XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(algorithmURI))) {
Object[] exArgs = { algorithmURI };
throw new XMLSecurityException("signature.signatureAlgorithm", exArgs);
}
signatureAlgorithmSpi = getSignatureAlgorithmSpi(algorithmURI, provider);
signatureAlgorithmSpi.engineGetContextFromElement(getElement());
}
/**
* Get a SignatureAlgorithmSpi object corresponding to the algorithmURI argument
*/
private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI, Provider provider)
throws XMLSignatureException {
try {
Class<? extends SignatureAlgorithmSpi> implementingClass = algorithmHash.get(algorithmURI);
LOG.debug("Create URI \"{}\" class \"{}\"", algorithmURI, implementingClass);
if (implementingClass == null) {
Object[] exArgs = { algorithmURI };
throw new XMLSignatureException("algorithms.NoSuchAlgorithmNoEx", exArgs);
}
if (provider != null) {
try {
Constructor<? extends SignatureAlgorithmSpi> constructor = implementingClass.getConstructor(Provider.class);
return constructor.newInstance(provider);
} catch (NoSuchMethodException e) {
LOG.warn("Class \"{}\" does not have a constructor with Provider", implementingClass);
}
}
return JavaUtils.newInstanceWithEmptyConstructor(implementingClass);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NullPointerException ex) {
Object[] exArgs = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs);
}
}
/**
* Proxy method for {@link java.security.Signature#sign()}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#sign()} method
* @throws XMLSignatureException
*/
public byte[] sign() throws XMLSignatureException {
return signatureAlgorithmSpi.engineSign();
}
/**
* Proxy method for {@link java.security.Signature#getAlgorithm}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#getAlgorithm} method
*/
public String getJCEAlgorithmString() {
return signatureAlgorithmSpi.engineGetJCEAlgorithmString();
}
/**
* Method getJCEProviderName
*
* @return The Provider of this Signature Algorithm
*/
public String getJCEProviderName() {
return signatureAlgorithmSpi.engineGetJCEProviderName();
}
/**
* Proxy method for {@link java.security.Signature#update(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
public void update(byte[] input) throws XMLSignatureException {
signatureAlgorithmSpi.engineUpdate(input);
}
/**
* Proxy method for {@link java.security.Signature#update(byte)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
public void update(byte input) throws XMLSignatureException {
signatureAlgorithmSpi.engineUpdate(input);
}
/**
* Proxy method for {@link java.security.Signature#update(byte[], int, int)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param buf
* @param offset
* @param len
* @throws XMLSignatureException
*/
public void update(byte[] buf, int offset, int len) throws XMLSignatureException {
signatureAlgorithmSpi.engineUpdate(buf, offset, len);
}
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @throws XMLSignatureException
*/
public void initSign(Key signingKey) throws XMLSignatureException {
signatureAlgorithmSpi.engineInitSign(signingKey);
}
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey,
* java.security.SecureRandom)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @param secureRandom
* @throws XMLSignatureException
*/
public void initSign(Key signingKey, SecureRandom secureRandom) throws XMLSignatureException {
signatureAlgorithmSpi.engineInitSign(signingKey, secureRandom);
}
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @param algorithmParameterSpec
* @throws XMLSignatureException
*/
public void initSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
signatureAlgorithmSpi.engineInitSign(signingKey, algorithmParameterSpec);
}
/**
* Proxy method for {@link java.security.Signature#setParameter(
* java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param params
* @throws XMLSignatureException
*/
public void setParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
signatureAlgorithmSpi.engineSetParameter(params);
}
/**
* Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param verificationKey
* @throws XMLSignatureException
*/
public void initVerify(Key verificationKey) throws XMLSignatureException {
signatureAlgorithmSpi.engineInitVerify(verificationKey);
}
/**
* Proxy method for {@link java.security.Signature#verify(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signature
* @return true if the signature is valid.
*
* @throws XMLSignatureException
*/
public boolean verify(byte[] signature) throws XMLSignatureException {
return signatureAlgorithmSpi.engineVerify(signature);
}
/**
* Returns the URI representation of Transformation algorithm
*
* @return the URI representation of Transformation algorithm
*/
public final String getURI() {
return getLocalAttribute(Constants._ATT_ALGORITHM);
}
/**
* Registers implementing class of the SignatureAlgorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of {@code SignatureAlgorithm}.
* @param implementingClass {@code implementingClass} the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the signature algorithm
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
JavaUtils.checkRegisterPermission();
LOG.debug("Try to register {} {}", algorithmURI, implementingClass);
// are we already registered?
Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
if (registeredClass != null) {
Object[] exArgs = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException(
"algorithm.alreadyRegistered", exArgs
);
}
try {
Class<? extends SignatureAlgorithmSpi> clazz =
(Class<? extends SignatureAlgorithmSpi>)
ClassLoaderUtils.loadClass(implementingClass, SignatureAlgorithm.class);
algorithmHash.put(algorithmURI, clazz);
} catch (NullPointerException ex) {
Object[] exArgs = { algorithmURI, ex.getMessage() };
throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs);
}
}
/**
* Registers implementing class of the SignatureAlgorithm with algorithmURI
*
* @param algorithmURI algorithmURI URI representation of {@code SignatureAlgorithm}.
* @param implementingClass {@code implementingClass} the implementing class of
* {@link SignatureAlgorithmSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered
* @throws XMLSignatureException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the signature algorithm
*/
public static void register(String algorithmURI, Class<? extends SignatureAlgorithmSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException,
XMLSignatureException {
JavaUtils.checkRegisterPermission();
LOG.debug("Try to register {} {}", algorithmURI, implementingClass);
// are we already registered?
Class<? extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI);
if (registeredClass != null) {
Object[] exArgs = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException(
"algorithm.alreadyRegistered", exArgs
);
}
algorithmHash.put(algorithmURI, implementingClass);
}
/**
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256, SignatureDSA.SHA256.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA1, IntegrityHmac.IntegrityHmacSHA1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
SignatureBaseRSA.SignatureRSAMD5.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
SignatureBaseRSA.SignatureRSARIPEMD160.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224, SignatureBaseRSA.SignatureRSASHA224.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, SignatureBaseRSA.SignatureRSASHA256.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384, SignatureBaseRSA.SignatureRSASHA384.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, SignatureBaseRSA.SignatureRSASHA512.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1, SignatureBaseRSA.SignatureRSASHA1MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1, SignatureBaseRSA.SignatureRSASHA224MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1, SignatureBaseRSA.SignatureRSASHA256MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1, SignatureBaseRSA.SignatureRSASHA384MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1, SignatureBaseRSA.SignatureRSASHA512MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_PSS, SignatureBaseRSA.SignatureRSASSAPSS.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1, SignatureBaseRSA.SignatureRSASHA3_224MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1, SignatureBaseRSA.SignatureRSASHA3_256MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1, SignatureBaseRSA.SignatureRSASHA3_384MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1, SignatureBaseRSA.SignatureRSASHA3_512MGF1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224, SignatureECDSA.SignatureECDSASHA224.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, SignatureECDSA.SignatureECDSASHA384.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_224, SignatureECDSA.SignatureECDSASHA3_224.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_256, SignatureECDSA.SignatureECDSASHA3_256.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_384, SignatureECDSA.SignatureECDSASHA3_384.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_512, SignatureECDSA.SignatureECDSASHA3_512.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160, SignatureECDSA.SignatureECDSARIPEMD160.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_EDDSA_ED25519, SignatureEDDSA.SignatureEd25519.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_EDDSA_ED448, SignatureEDDSA.SignatureEd448.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, IntegrityHmac.IntegrityHmacRIPEMD160.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA224, IntegrityHmac.IntegrityHmacSHA224.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA256, IntegrityHmac.IntegrityHmacSHA256.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA384, IntegrityHmac.IntegrityHmacSHA384.class
);
algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_SHA512, IntegrityHmac.IntegrityHmacSHA512.class
);
}
/**
* Method getBaseNamespace
*
* @return URI of this element
*/
@Override
public String getBaseNamespace() {
return Constants.SignatureSpecNS;
}
/**
* Method getBaseLocalName
*
* @return Local name
*/
@Override
public String getBaseLocalName() {
return Constants._TAG_SIGNATUREMETHOD;
}
}

View file

@ -0,0 +1,225 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import org.w3c.dom.Element;
public abstract class SignatureAlgorithmSpi {
/**
* Returns the URI representation of {@code Transformation algorithm}
*
* @return the URI representation of {@code Transformation algorithm}
*/
protected abstract String engineGetURI();
/**
* Proxy method for {@link java.security.Signature#getAlgorithm}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#getAlgorithm} method
*/
protected abstract String engineGetJCEAlgorithmString();
/**
* Method engineGetJCEProviderName
*
* @return the JCE ProviderName
*/
protected abstract String engineGetJCEProviderName();
/**
* Proxy method for {@link java.security.Signature#update(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
protected abstract void engineUpdate(byte[] input) throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#update(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
protected abstract void engineUpdate(byte input) throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#update(byte[], int, int)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param buf
* @param offset
* @param len
* @throws XMLSignatureException
*/
protected abstract void engineUpdate(byte[] buf, int offset, int len)
throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @throws XMLSignatureException if this method is called on a MAC
*/
protected abstract void engineInitSign(Key signingKey) throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey,
* java.security.SecureRandom)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signingKey
* @param secureRandom
* @throws XMLSignatureException if this method is called on a MAC
*/
protected abstract void engineInitSign(Key signingKey, SecureRandom secureRandom)
throws XMLSignatureException;
/**
* Proxy method for {@link javax.crypto.Mac}
* which is executed on the internal {@link javax.crypto.Mac#init(Key)} object.
*
* @param signingKey
* @param algorithmParameterSpec
* @throws XMLSignatureException if this method is called on a Signature
*/
protected abstract void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#sign()}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#sign()} method
* @throws XMLSignatureException
*/
protected abstract byte[] engineSign() throws XMLSignatureException;
/**
* Method engineInitVerify
*
* @param verificationKey
* @throws XMLSignatureException
*/
protected abstract void engineInitVerify(Key verificationKey) throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#verify(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signature
* @return true if the signature is correct
* @throws XMLSignatureException
*/
protected abstract boolean engineVerify(byte[] signature) throws XMLSignatureException;
/**
* Proxy method for {@link java.security.Signature#setParameter(
* java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param params
* @throws XMLSignatureException
*/
protected abstract void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException;
/**
* Method engineGetContextFromElement
*
* @param element
*/
protected void engineGetContextFromElement(Element element) throws XMLSignatureException {
}
protected void engineAddContextToElement(Element element) throws XMLSignatureException {
}
/**
* Method engineSetHMACOutputLength
*
* @param HMACOutputLength
* @throws XMLSignatureException
*/
protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException;
protected static void engineInitVerify(Key publicKey, Signature signatureAlgorithm) throws XMLSignatureException {
if (!(publicKey instanceof PublicKey)) {
String supplied = null;
if (publicKey != null) {
supplied = publicKey.getClass().getName();
}
String needed = PublicKey.class.getName();
Object[] exArgs = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException(ex);
}
}
protected static void engineInitSign(Key privateKey, SecureRandom secureRandom, Signature signatureAlgorithm)
throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) {
String supplied = null;
if (privateKey != null) {
supplied = privateKey.getClass().getName();
}
String needed = PrivateKey.class.getName();
Object[] exArgs = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
if (secureRandom == null) {
signatureAlgorithm.initSign((PrivateKey) privateKey);
} else {
signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
}
} catch (InvalidKeyException ex) {
throw new XMLSignatureException(ex);
}
}
}

View file

@ -0,0 +1,968 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.io.IOException;
import java.math.BigInteger;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECField;
import java.security.spec.ECFieldF2m;
import java.security.spec.ECFieldFp;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.EllipticCurve;
import java.util.ArrayList;
import java.util.List;
public final class ECDSAUtils {
private ECDSAUtils() {
// complete
}
/**
* Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
* <p></p>
* The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param asn1Bytes the ASN.1 encoded bytes
* @param rawLen the intended length of decoded bytes for an integer.
* If -1, choose one automatically.
* @return the decoded bytes
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/
public static byte[] convertASN1toXMLDSIG(byte[] asn1Bytes, int rawLen) throws IOException {
if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) {
throw new IOException("Invalid ASN.1 format of ECDSA signature");
}
int offset;
if (asn1Bytes[1] > 0) {
offset = 2;
} else if (asn1Bytes[1] == (byte) 0x81) {
offset = 3;
} else {
throw new IOException("Invalid ASN.1 format of ECDSA signature");
}
byte rLength = asn1Bytes[offset + 1];
int i;
for (i = rLength; i > 0 && asn1Bytes[offset + 2 + rLength - i] == 0; i--); //NOPMD
byte sLength = asn1Bytes[offset + 2 + rLength + 1];
int j;
for (j = sLength; j > 0 && asn1Bytes[offset + 2 + rLength + 2 + sLength - j] == 0; j--); //NOPMD
int maxLen = Math.max(i, j);
if (rawLen < 0) {
rawLen = maxLen;
} else if (rawLen < maxLen) {
throw new IOException("Invalid signature length");
}
if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset
|| (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
|| asn1Bytes[offset] != 2
|| asn1Bytes[offset + 2 + rLength] != 2) {
throw new IOException("Invalid ASN.1 format of ECDSA signature");
}
byte[] xmldsigBytes = new byte[2 * rawLen];
System.arraycopy(asn1Bytes, offset + 2 + rLength - i, xmldsigBytes, rawLen - i, i);
System.arraycopy(asn1Bytes, offset + 2 + rLength + 2 + sLength - j, xmldsigBytes,
2 * rawLen - j, j);
return xmldsigBytes;
}
/**
* Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
* <p></p>
* The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param xmldsigBytes
* @return the encoded ASN.1 bytes
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/
public static byte[] convertXMLDSIGtoASN1(byte[] xmldsigBytes) throws IOException {
int rawLen = xmldsigBytes.length / 2;
int i;
for (i = rawLen; i > 0 && xmldsigBytes[rawLen - i] == 0; i--); //NOPMD
int j = i;
if (xmldsigBytes[rawLen - i] < 0) {
j += 1;
}
int k;
for (k = rawLen; k > 0 && xmldsigBytes[2 * rawLen - k] == 0; k--); //NOPMD
int l = k;
if (xmldsigBytes[2 * rawLen - k] < 0) {
l += 1;
}
int len = 2 + j + 2 + l;
if (len > 255) {
throw new IOException("Invalid XMLDSIG format of ECDSA signature");
}
int offset;
byte[] asn1Bytes;
if (len < 128) {
asn1Bytes = new byte[2 + 2 + j + 2 + l];
offset = 1;
} else {
asn1Bytes = new byte[3 + 2 + j + 2 + l];
asn1Bytes[1] = (byte) 0x81;
offset = 2;
}
asn1Bytes[0] = 48;
asn1Bytes[offset++] = (byte) len;
asn1Bytes[offset++] = 2;
asn1Bytes[offset++] = (byte) j;
System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, offset + j - i, i);
offset += j;
asn1Bytes[offset++] = 2;
asn1Bytes[offset++] = (byte) l;
System.arraycopy(xmldsigBytes, 2 * rawLen - k, asn1Bytes, offset + l - k, k);
return asn1Bytes;
}
private static final List<ECCurveDefinition> ecCurveDefinitions = new ArrayList<>();
static {
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp112r1",
"1.3.132.0.6",
"db7c2abf62e35e668076bead208b",
"db7c2abf62e35e668076bead2088",
"659ef8ba043916eede8911702b22",
"09487239995a5ee76b55f9c2f098",
"a89ce5af8724c0a23e0e0ff77500",
"db7c2abf62e35e7628dfac6561c5",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp112r2",
"1.3.132.0.7",
"db7c2abf62e35e668076bead208b",
"6127c24c05f38a0aaaf65c0ef02c",
"51def1815db5ed74fcc34c85d709",
"4ba30ab5e892b4e1649dd0928643",
"adcd46f5882e3747def36e956e97",
"36df0aafd8b8d7597ca10520d04b",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp128r1",
"1.3.132.0.28",
"fffffffdffffffffffffffffffffffff",
"fffffffdfffffffffffffffffffffffc",
"e87579c11079f43dd824993c2cee5ed3",
"161ff7528b899b2d0c28607ca52c5b86",
"cf5ac8395bafeb13c02da292dded7a83",
"fffffffe0000000075a30d1b9038a115",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp128r2",
"1.3.132.0.29",
"fffffffdffffffffffffffffffffffff",
"d6031998d1b3bbfebf59cc9bbff9aee1",
"5eeefca380d02919dc2c6558bb6d8a5d",
"7b6aa5d85e572983e6fb32a7cdebc140",
"27b6916a894d3aee7106fe805fc34b44",
"3fffffff7fffffffbe0024720613b5a3",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp160k1",
"1.3.132.0.9",
"fffffffffffffffffffffffffffffffeffffac73",
"0000000000000000000000000000000000000000",
"0000000000000000000000000000000000000007",
"3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
"938cf935318fdced6bc28286531733c3f03c4fee",
"0100000000000000000001b8fa16dfab9aca16b6b3",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp160r1",
"1.3.132.0.8",
"ffffffffffffffffffffffffffffffff7fffffff",
"ffffffffffffffffffffffffffffffff7ffffffc",
"1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
"4a96b5688ef573284664698968c38bb913cbfc82",
"23a628553168947d59dcc912042351377ac5fb32",
"0100000000000000000001f4c8f927aed3ca752257",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp160r2",
"1.3.132.0.30",
"fffffffffffffffffffffffffffffffeffffac73",
"fffffffffffffffffffffffffffffffeffffac70",
"b4e134d3fb59eb8bab57274904664d5af50388ba",
"52dcb034293a117e1f4ff11b30f7199d3144ce6d",
"feaffef2e331f296e071fa0df9982cfea7d43f2e",
"0100000000000000000000351ee786a818f3a1a16b",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp192k1",
"1.3.132.0.31",
"fffffffffffffffffffffffffffffffffffffffeffffee37",
"000000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000003",
"db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
"9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d",
"fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp192r1 [NIST P-192, X9.62 prime192v1]",
"1.2.840.10045.3.1.1",
"fffffffffffffffffffffffffffffffeffffffffffffffff",
"fffffffffffffffffffffffffffffffefffffffffffffffc",
"64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
"188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
"07192b95ffc8da78631011ed6b24cdd573f977a11e794811",
"ffffffffffffffffffffffff99def836146bc9b1b4d22831",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp224k1",
"1.3.132.0.32",
"fffffffffffffffffffffffffffffffffffffffffffffffeffffe56d",
"00000000000000000000000000000000000000000000000000000000",
"00000000000000000000000000000000000000000000000000000005",
"a1455b334df099df30fc28a169a467e9e47075a90f7e650eb6b7a45c",
"7e089fed7fba344282cafbd6f7e319f7c0b0bd59e2ca4bdb556d61a5",
"010000000000000000000000000001dce8d2ec6184caf0a971769fb1f7",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp224r1 [NIST P-224]",
"1.3.132.0.33",
"ffffffffffffffffffffffffffffffff000000000000000000000001",
"fffffffffffffffffffffffffffffffefffffffffffffffffffffffe",
"b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4",
"b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21",
"bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34",
"ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp256k1",
"1.3.132.0.10",
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000007",
"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
"483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp256r1 [NIST P-256, X9.62 prime256v1]",
"1.2.840.10045.3.1.7",
"ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
"ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
"6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
"4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5",
"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp384r1 [NIST P-384]",
"1.3.132.0.34",
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff",
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc",
"b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef",
"aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7",
"3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",
"ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"secp521r1 [NIST P-521]",
"1.3.132.0.35",
"01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc",
"0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00",
"00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66",
"011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",
"01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 prime192v2",
"1.2.840.10045.3.1.2",
"fffffffffffffffffffffffffffffffeffffffffffffffff",
"fffffffffffffffffffffffffffffffefffffffffffffffc",
"cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953",
"eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a",
"6574d11d69b6ec7a672bb82a083df2f2b0847de970b2de15",
"fffffffffffffffffffffffe5fb1a724dc80418648d8dd31",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 prime192v3",
"1.2.840.10045.3.1.3",
"fffffffffffffffffffffffffffffffeffffffffffffffff",
"fffffffffffffffffffffffffffffffefffffffffffffffc",
"22123dc2395a05caa7423daeccc94760a7d462256bd56916",
"7d29778100c65a1da1783716588dce2b8b4aee8e228f1896",
"38a90f22637337334b49dcb66a6dc8f9978aca7648a943b0",
"ffffffffffffffffffffffff7a62d031c83f4294f640ec13",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 prime239v1",
"1.2.840.10045.3.1.4",
"7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff",
"7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc",
"6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a",
"0ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf",
"7debe8e4e90a5dae6e4054ca530ba04654b36818ce226b39fccb7b02f1ae",
"7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 prime239v2",
"1.2.840.10045.3.1.5",
"7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff",
"7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc",
"617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c",
"38af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7",
"5b0125e4dbea0ec7206da0fc01d9b081329fb555de6ef460237dff8be4ba",
"7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 prime239v3",
"1.2.840.10045.3.1.6",
"7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff",
"7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc",
"255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e",
"6768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a",
"1607e6898f390c06bc1d552bad226f3b6fcfe48b6e818499af18e3ed6cf3",
"7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect113r1",
"1.3.132.0.4",
"020000000000000000000000000201",
"003088250ca6e7c7fe649ce85820f7",
"00e8bee4d3e2260744188be0e9c723",
"009d73616f35f4ab1407d73562c10f",
"00a52830277958ee84d1315ed31886",
"0100000000000000d9ccec8a39e56f",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect113r2",
"1.3.132.0.5",
"020000000000000000000000000201",
"00689918dbec7e5a0dd6dfc0aa55c7",
"0095e9a9ec9b297bd4bf36e059184f",
"01a57a6a7b26ca5ef52fcdb8164797",
"00b3adc94ed1fe674c06e695baba1d",
"010000000000000108789b2496af93",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect131r1",
"1.3.132.0.22",
"080000000000000000000000000000010d",
"07a11b09a76b562144418ff3ff8c2570b8",
"0217c05610884b63b9c6c7291678f9d341",
"0081baf91fdf9833c40f9c181343638399",
"078c6e7ea38c001f73c8134b1b4ef9e150",
"0400000000000000023123953a9464b54d",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect131r2",
"1.3.132.0.23",
"080000000000000000000000000000010d",
"03e5a88919d7cafcbf415f07c2176573b2",
"04b8266a46c55657ac734ce38f018f2192",
"0356dcd8f2f95031ad652d23951bb366a8",
"0648f06d867940a5366d9e265de9eb240f",
"0400000000000000016954a233049ba98f",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect163k1 [NIST K-163]",
"1.3.132.0.1",
"0800000000000000000000000000000000000000c9",
"000000000000000000000000000000000000000001",
"000000000000000000000000000000000000000001",
"02fe13c0537bbc11acaa07d793de4e6d5e5c94eee8",
"0289070fb05d38ff58321f2e800536d538ccdaa3d9",
"04000000000000000000020108a2e0cc0d99f8a5ef",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect163r1",
"1.3.132.0.2",
"0800000000000000000000000000000000000000c9",
"07b6882caaefa84f9554ff8428bd88e246d2782ae2",
"0713612dcddcb40aab946bda29ca91f73af958afd9",
"0369979697ab43897789566789567f787a7876a654",
"00435edb42efafb2989d51fefce3c80988f41ff883",
"03ffffffffffffffffffff48aab689c29ca710279b",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect163r2 [NIST B-163]",
"1.3.132.0.15",
"0800000000000000000000000000000000000000c9",
"000000000000000000000000000000000000000001",
"020a601907b8c953ca1481eb10512f78744a3205fd",
"03f0eba16286a2d57ea0991168d4994637e8343e36",
"00d51fbc6c71a0094fa2cdd545b11c5c0c797324f1",
"040000000000000000000292fe77e70c12a4234c33",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect193r1",
"1.3.132.0.24",
"02000000000000000000000000000000000000000000008001",
"0017858feb7a98975169e171f77b4087de098ac8a911df7b01",
"00fdfb49bfe6c3a89facadaa7a1e5bbc7cc1c2e5d831478814",
"01f481bc5f0ff84a74ad6cdf6fdef4bf6179625372d8c0c5e1",
"0025e399f2903712ccf3ea9e3a1ad17fb0b3201b6af7ce1b05",
"01000000000000000000000000c7f34a778f443acc920eba49",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect193r2",
"1.3.132.0.25",
"02000000000000000000000000000000000000000000008001",
"0163f35a5137c2ce3ea6ed8667190b0bc43ecd69977702709b",
"00c9bb9e8927d4d64c377e2ab2856a5b16e3efb7f61d4316ae",
"00d9b67d192e0367c803f39e1a7e82ca14a651350aae617e8f",
"01ce94335607c304ac29e7defbd9ca01f596f927224cdecf6c",
"010000000000000000000000015aab561b005413ccd4ee99d5",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect233k1 [NIST K-233]",
"1.3.132.0.26",
"020000000000000000000000000000000000000004000000000000000001",
"000000000000000000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000000000000000001",
"017232ba853a7e731af129f22ff4149563a419c26bf50a4c9d6eefad6126",
"01db537dece819b7f70f555a67c427a8cd9bf18aeb9b56e0c11056fae6a3",
"008000000000000000000000000000069d5bb915bcd46efb1ad5f173abdf",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect233r1 [NIST B-233]",
"1.3.132.0.27",
"020000000000000000000000000000000000000004000000000000000001",
"000000000000000000000000000000000000000000000000000000000001",
"0066647ede6c332c7f8c0923bb58213b333b20e9ce4281fe115f7d8f90ad",
"00fac9dfcbac8313bb2139f1bb755fef65bc391f8b36f8f8eb7371fd558b",
"01006a08a41903350678e58528bebf8a0beff867a7ca36716f7e01f81052",
"01000000000000000000000000000013e974e72f8a6922031d2603cfe0d7",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect239k1",
"1.3.132.0.3",
"800000000000000000004000000000000000000000000000000000000001",
"000000000000000000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000000000000000001",
"29a0b6a887a983e9730988a68727a8b2d126c44cc2cc7b2a6555193035dc",
"76310804f12e549bdb011c103089e73510acb275fc312a5dc6b76553f0ca",
"2000000000000000000000000000005a79fec67cb6e91f1c1da800e478a5",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect283k1 [NIST K-283]",
"1.3.132.0.16",
"0800000000000000000000000000000000000000000000000000000000000000000010a1",
"000000000000000000000000000000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000000000000000000000000000001",
"0503213f78ca44883f1a3b8162f188e553cd265f23c1567a16876913b0c2ac2458492836",
"01ccda380f1c9e318d90f95d07e5426fe87e45c0e8184698e45962364e34116177dd2259",
"01ffffffffffffffffffffffffffffffffffe9ae2ed07577265dff7f94451e061e163c61",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect283r1 [NIST B-283]",
"1.3.132.0.17",
"0800000000000000000000000000000000000000000000000000000000000000000010a1",
"000000000000000000000000000000000000000000000000000000000000000000000001",
"027b680ac8b8596da5a4af8a19a0303fca97fd7645309fa2a581485af6263e313b79a2f5",
"05f939258db7dd90e1934f8c70b0dfec2eed25b8557eac9c80e2e198f8cdbecd86b12053",
"03676854fe24141cb98fe6d4b20d02b4516ff702350eddb0826779c813f0df45be8112f4",
"03ffffffffffffffffffffffffffffffffffef90399660fc938a90165b042a7cefadb307",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect409k1 [NIST K-409]",
"1.3.132.0.36",
"02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001",
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"0060f05f658f49c1ad3ab1890f7184210efd0987e307c84c27accfb8f9f67cc2c460189eb5aaaa62ee222eb1b35540cfe9023746",
"01e369050b7c4e42acba1dacbf04299c3460782f918ea427e6325165e9ea10e3da5f6c42e9c55215aa9ca27a5863ec48d8e0286b",
"007ffffffffffffffffffffffffffffffffffffffffffffffffffe5f83b2d4ea20400ec4557d5ed3e3e7ca5b4b5c83b8e01e5fcf",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect409r1 [NIST B-409]",
"1.3.132.0.37",
"02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001",
"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"0021a5c2c8ee9feb5c4b9a753b7b476b7fd6422ef1f3dd674761fa99d6ac27c8a9a197b272822f6cd57a55aa4f50ae317b13545f",
"015d4860d088ddb3496b0c6064756260441cde4af1771d4db01ffe5b34e59703dc255a868a1180515603aeab60794e54bb7996a7",
"0061b1cfab6be5f32bbfa78324ed106a7636b9c5a7bd198d0158aa4f5488d08f38514f1fdf4b4f40d2181b3681c364ba0273c706",
"010000000000000000000000000000000000000000000000000001e2aad6a612f33307be5fa47c3c9e052f838164cd37d9a21173",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect571k1 [NIST K-571]",
"1.3.132.0.38",
"080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425",
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"026eb7a859923fbc82189631f8103fe4ac9ca2970012d5d46024804801841ca44370958493b205e647da304db4ceb08cbbd1ba39494776fb988b47174dca88c7e2945283a01c8972",
"0349dc807f4fbf374f4aeade3bca95314dd58cec9f307a54ffc61efc006d8a2c9d4979c0ac44aea74fbebbb9f772aedcb620b01a7ba7af1b320430c8591984f601cd4c143ef1c7a3",
"020000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"sect571r1 [NIST B-571]",
"1.3.132.0.39",
"080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425",
"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
"02f40e7e2221f295de297117b7f3d62f5c6a97ffcb8ceff1cd6ba8ce4a9a18ad84ffabbd8efa59332be7ad6756a66e294afd185a78ff12aa520e4de739baca0c7ffeff7f2955727a",
"0303001d34b856296c16c0d40d3cd7750a93d1d2955fa80aa5f40fc8db7b2abdbde53950f4c0d293cdd711a35b67fb1499ae60038614f1394abfa3b4c850d927e1e7769c8eec2d19",
"037bf27342da639b6dccfffeb73d69d78c6c27a6009cbbca1980f8533921e8a684423e43bab08a576291af8f461bb2a8b3531d2f0485c19b16e2f1516e23dd3c1a4827af1b8ac15b",
"03ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe661ce18ff55987308059b186823851ec7dd9ca1161de93d5174d66e8382e9bb2fe84e47",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb191v1",
"1.2.840.10045.3.0.5",
"800000000000000000000000000000000000000000000201",
"2866537b676752636a68f56554e12640276b649ef7526267",
"2e45ef571f00786f67b0081b9495a3d95462f5de0aa185ec",
"36b3daf8a23206f9c4f299d7b21a9c369137f2c84ae1aa0d",
"765be73433b3f95e332932e70ea245ca2418ea0ef98018fb",
"40000000000000000000000004a20e90c39067c893bbb9a5",
2)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb191v2",
"1.2.840.10045.3.0.6",
"800000000000000000000000000000000000000000000201",
"401028774d7777c7b7666d1366ea432071274f89ff01e718",
"0620048d28bcbd03b6249c99182b7c8cd19700c362c46a01",
"3809b2b7cc1b28cc5a87926aad83fd28789e81e2c9e3bf10",
"17434386626d14f3dbf01760d9213a3e1cf37aec437d668a",
"20000000000000000000000050508cb89f652824e06b8173",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb191v3",
"1.2.840.10045.3.0.7",
"800000000000000000000000000000000000000000000201",
"6c01074756099122221056911c77d77e77a777e7e7e77fcb",
"71fe1af926cf847989efef8db459f66394d90f32ad3f15e8",
"375d4ce24fde434489de8746e71786015009e66e38a926dd",
"545a39176196575d985999366e6ad34ce0a77cd7127b06be",
"155555555555555555555555610c0b196812bfb6288a3ea3",
6)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb239v1",
"1.2.840.10045.3.0.11",
"800000000000000000000000000000000000000000000000001000000001",
"32010857077c5431123a46b808906756f543423e8d27877578125778ac76",
"790408f2eedaf392b012edefb3392f30f4327c0ca3f31fc383c422aa8c16",
"57927098fa932e7c0a96d3fd5b706ef7e5f5c156e16b7e7c86038552e91d",
"61d8ee5077c33fecf6f1a16b268de469c3c7744ea9a971649fc7a9616305",
"2000000000000000000000000000000f4d42ffe1492a4993f1cad666e447",
4)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb239v2",
"1.2.840.10045.3.0.12",
"800000000000000000000000000000000000000000000000001000000001",
"4230017757a767fae42398569b746325d45313af0766266479b75654e65f",
"5037ea654196cff0cd82b2c14a2fcf2e3ff8775285b545722f03eacdb74b",
"28f9d04e900069c8dc47a08534fe76d2b900b7d7ef31f5709f200c4ca205",
"5667334c45aff3b5a03bad9dd75e2c71a99362567d5453f7fa6e227ec833",
"1555555555555555555555555555553c6f2885259c31e3fcdf154624522d",
6)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb239v3",
"1.2.840.10045.3.0.13",
"800000000000000000000000000000000000000000000000001000000001",
"01238774666a67766d6676f778e676b66999176666e687666d8766c66a9f",
"6a941977ba9f6a435199acfc51067ed587f519c5ecb541b8e44111de1d40",
"70f6e9d04d289c4e89913ce3530bfde903977d42b146d539bf1bde4e9c92",
"2e5a0eaf6e5e1305b9004dce5c0ed7fe59a35608f33837c816d80b79f461",
"0cccccccccccccccccccccccccccccac4912d2d9df903ef9888b8a0e4cff",
0xA)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb359v1",
"1.2.840.10045.3.0.18",
"800000000000000000000000000000000000000000000000000000000000000000000000100000000000000001",
"5667676a654b20754f356ea92017d946567c46675556f19556a04616b567d223a5e05656fb549016a96656a557",
"2472e2d0197c49363f1fe7f5b6db075d52b6947d135d8ca445805d39bc345626089687742b6329e70680231988",
"3c258ef3047767e7ede0f1fdaa79daee3841366a132e163aced4ed2401df9c6bdcde98e8e707c07a2239b1b097",
"53d7e08529547048121e9c95f3791dd804963948f34fae7bf44ea82365dc7868fe57e4ae2de211305a407104bd",
"01af286bca1af286bca1af286bca1af286bca1af286bc9fb8f6b85c556892c20a7eb964fe7719e74f490758d3b",
0x4C)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"X9.62 c2tnb431r1",
"1.2.840.10045.3.0.20",
"800000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000001",
"1a827ef00dd6fc0e234caf046c6a5d8a85395b236cc4ad2cf32a0cadbdc9ddf620b0eb9906d0957f6c6feacd615468df104de296cd8f",
"10d9b4a3d9047d8b154359abfb1b7f5485b04ceb868237ddc9deda982a679a5a919b626d4e50a8dd731b107a9962381fb5d807bf2618",
"120fc05d3c67a99de161d2f4092622feca701be4f50f4758714e8a87bbf2a658ef8c21e7c5efe965361f6c2999c0c247b0dbd70ce6b7",
"20d0af8903a96f8d5fa2c255745d3c451b302c9346d9b7e485e7bce41f6b591f3e8f6addcbb0bc4c2f947a7de1a89b625d6a598b3760",
"0340340340340340340340340340340340340340340340340340340323c313fab50589703b5ec68d3587fec60d161cc149c1ad4a91",
0x2760)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"brainpoolP256r1 [RFC 5639]",
"1.3.36.3.3.2.8.1.1.7",
"a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377",
"7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9",
"26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6",
"8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262",
"547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997",
"a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"brainpoolP384r1 [RFC 5639]",
"1.3.36.3.3.2.8.1.1.11",
"8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53",
"7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826",
"04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11",
"1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e",
"8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315",
"8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565",
1)
);
ecCurveDefinitions.add(
new ECCurveDefinition(
"brainpoolP512r1 [RFC 5639]",
"1.3.36.3.3.2.8.1.1.13",
"aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3",
"7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca",
"3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723",
"81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822",
"7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892",
"aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069",
1)
);
}
public static String getOIDFromPublicKey(ECPublicKey ecPublicKey) {
ECParameterSpec ecParameterSpec = ecPublicKey.getParams();
BigInteger order = ecParameterSpec.getOrder();
BigInteger affineX = ecParameterSpec.getGenerator().getAffineX();
BigInteger affineY = ecParameterSpec.getGenerator().getAffineY();
BigInteger a = ecParameterSpec.getCurve().getA();
BigInteger b = ecParameterSpec.getCurve().getB();
int h = ecParameterSpec.getCofactor();
ECField ecField = ecParameterSpec.getCurve().getField();
BigInteger field;
if (ecField instanceof ECFieldFp) {
ECFieldFp ecFieldFp = (ECFieldFp) ecField;
field = ecFieldFp.getP();
} else {
ECFieldF2m ecFieldF2m = (ECFieldF2m) ecField;
field = ecFieldF2m.getReductionPolynomial();
}
for (ECCurveDefinition ecCurveDefinition : ecCurveDefinitions) {
String oid = ecCurveDefinition.equals(field, a, b, affineX, affineY, order, h);
if (oid != null) {
return oid;
}
}
return null;
}
public static ECCurveDefinition getECCurveDefinition(String oid) {
for (ECCurveDefinition ecCurveDefinition : ecCurveDefinitions) {
if (ecCurveDefinition.getOid().equals(oid)) {
return ecCurveDefinition;
}
}
return null;
}
public static class ECCurveDefinition {
private final String name;
private final String oid;
private final String field;
private final String a;
private final String b;
private final String x;
private final String y;
private final String n;
private final int h;
public ECCurveDefinition(String name, String oid, String field, String a, String b, String x, String y, String n, int h) {
this.name = name;
this.oid = oid;
this.field = field;
this.a = a;
this.b = b;
this.x = x;
this.y = y;
this.n = n;
this.h = h;
}
/**
* returns the ec oid if parameter are equal to this definition
*/
public String equals(BigInteger field, BigInteger a, BigInteger b, BigInteger x, BigInteger y, BigInteger n, int h) {
if (this.field.equals(field.toString(16))
&& this.a.equals(a.toString(16))
&& this.b.equals(b.toString(16))
&& this.x.equals(x.toString(16))
&& this.y.equals(y.toString(16))
&& this.n.equals(n.toString(16))
&& this.h == h) {
return this.oid;
}
return null;
}
public String getName() {
return name;
}
public String getOid() {
return oid;
}
public String getField() {
return field;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
public String getX() {
return x;
}
public String getY() {
return y;
}
public String getN() {
return n;
}
public int getH() {
return h;
}
}
public static byte[] encodePoint(ECPoint ecPoint, EllipticCurve ellipticCurve) {
int size = (ellipticCurve.getField().getFieldSize() + 7) / 8;
byte[] affineXBytes = stripLeadingZeros(ecPoint.getAffineX().toByteArray());
byte[] affineYBytes = stripLeadingZeros(ecPoint.getAffineY().toByteArray());
byte[] encodedBytes = new byte[size * 2 + 1];
encodedBytes[0] = 0x04; //uncompressed
System.arraycopy(affineXBytes, 0, encodedBytes, size - affineXBytes.length + 1, affineXBytes.length);
System.arraycopy(affineYBytes, 0, encodedBytes, encodedBytes.length - affineYBytes.length, affineYBytes.length);
return encodedBytes;
}
public static ECPoint decodePoint(byte[] encodedBytes, EllipticCurve elliptiCcurve) {
if (encodedBytes[0] != 0x04) {
throw new IllegalArgumentException("Only uncompressed format is supported");
}
int size = (elliptiCcurve.getField().getFieldSize() + 7) / 8;
byte[] affineXBytes = new byte[size];
byte[] affineYBytes = new byte[size];
System.arraycopy(encodedBytes, 1, affineXBytes, 0, size);
System.arraycopy(encodedBytes, size + 1, affineYBytes, 0, size);
return new ECPoint(new BigInteger(1, affineXBytes), new BigInteger(1, affineYBytes));
}
public static byte[] stripLeadingZeros(byte[] bytes) {
int i;
for (i = 0; i < bytes.length - 1; i++) {
if (bytes[i] != 0) {
break;
}
}
if (i == 0) {
return bytes;
} else {
byte[] stripped = new byte[bytes.length - i];
System.arraycopy(bytes, i, stripped, 0, stripped.length);
return stripped;
}
}
}

View file

@ -0,0 +1,614 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(IntegrityHmac.class);
/** Field macAlgorithm */
private final Mac macAlgorithm;
/** Field hmacOutputLength */
private HMACOutputLength hmacOutputLength;
/**
* Returns the output length of the hash/digest.
*/
abstract int getDigestLength();
/**
* Method IntegrityHmac
*
* @throws XMLSignatureException
*/
public IntegrityHmac() throws XMLSignatureException {
this(null);
}
public IntegrityHmac(Provider provider) throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
LOG.debug("Created IntegrityHmacSHA1 using {}", algorithmID);
try {
this.macAlgorithm = (provider == null) ? Mac.getInstance(algorithmID) : Mac.getInstance(algorithmID, provider);
} catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
}
/**
* Proxy method for {@link java.security.Signature#setParameter(
* java.security.spec.AlgorithmParameterSpec)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param params
* @throws XMLSignatureException
*/
@Override
protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
throw new XMLSignatureException("empty", new Object[]{"Incorrect method call"});
}
/**
* Proxy method for {@link java.security.Signature#verify(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param signature
* @return true if the signature is correct
* @throws XMLSignatureException
*/
@Override
protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
try {
if (hmacOutputLength != null && hmacOutputLength.length < getDigestLength()) {
LOG.debug("HMACOutputLength must not be less than {}", getDigestLength());
Object[] exArgs = { String.valueOf(getDigestLength()) };
throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
} else {
byte[] completeResult = this.macAlgorithm.doFinal();
return MessageDigestAlgorithm.isEqual(completeResult, signature);
}
} catch (IllegalStateException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param secretKey
* @throws XMLSignatureException
*/
@Override
protected void engineInitVerify(Key secretKey) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) {
String supplied = null;
if (secretKey != null) {
supplied = secretKey.getClass().getName();
}
String needed = SecretKey.class.getName();
Object[] exArgs = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
this.macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Proxy method for {@link java.security.Signature#sign()}
* which is executed on the internal {@link java.security.Signature} object.
*
* @return the result of the {@link java.security.Signature#sign()} method
* @throws XMLSignatureException
*/
@Override
protected byte[] engineSign() throws XMLSignatureException {
try {
if (hmacOutputLength != null && hmacOutputLength.length < getDigestLength()) {
LOG.debug("HMACOutputLength must not be less than {}", getDigestLength());
Object[] exArgs = { String.valueOf(getDigestLength()) };
throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
} else {
return this.macAlgorithm.doFinal();
}
} catch (IllegalStateException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method engineInitSign
*
* @param secretKey
* @throws XMLSignatureException
*/
@Override
protected void engineInitSign(Key secretKey) throws XMLSignatureException {
engineInitSign(secretKey, (AlgorithmParameterSpec)null);
}
/**
* Method engineInitSign
*
* @param secretKey
* @param algorithmParameterSpec
* @throws XMLSignatureException
*/
@Override
protected void engineInitSign(
Key secretKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) {
String supplied = null;
if (secretKey != null) {
supplied = secretKey.getClass().getName();
}
String needed = SecretKey.class.getName();
Object[] exArgs = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
if (algorithmParameterSpec == null) {
this.macAlgorithm.init(secretKey);
} else {
this.macAlgorithm.init(secretKey, algorithmParameterSpec);
}
} catch (InvalidKeyException | InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method engineInitSign
*
* @param secretKey
* @param secureRandom
* @throws XMLSignatureException
*/
@Override
protected void engineInitSign(Key secretKey, SecureRandom secureRandom)
throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
}
/**
* Proxy method for {@link java.security.Signature#update(byte[])}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
@Override
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this.macAlgorithm.update(input);
} catch (IllegalStateException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Proxy method for {@link java.security.Signature#update(byte)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param input
* @throws XMLSignatureException
*/
@Override
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
this.macAlgorithm.update(input);
} catch (IllegalStateException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Proxy method for {@link java.security.Signature#update(byte[], int, int)}
* which is executed on the internal {@link java.security.Signature} object.
*
* @param buf
* @param offset
* @param len
* @throws XMLSignatureException
*/
@Override
protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException {
try {
this.macAlgorithm.update(buf, offset, len);
} catch (IllegalStateException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method engineGetJCEAlgorithmString
* {@inheritDoc}
*
*/
@Override
protected String engineGetJCEAlgorithmString() {
return this.macAlgorithm.getAlgorithm();
}
/**
* Method engineGetJCEAlgorithmString
*
* {@inheritDoc}
*/
@Override
protected String engineGetJCEProviderName() {
return this.macAlgorithm.getProvider().getName();
}
/**
* Method engineSetHMACOutputLength
*
* @param length
* @throws XMLSignatureException
*/
@Override
protected void engineSetHMACOutputLength(int length) throws XMLSignatureException {
hmacOutputLength = new HMACOutputLength(length);
}
/**
* Method engineGetContextFromElement
*
* @param element
* @throws XMLSignatureException
*/
@Override
protected void engineGetContextFromElement(Element element) throws XMLSignatureException {
if (element == null) {
throw new IllegalArgumentException("element null");
}
Node n = XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0);
if (n != null) {
String hmacLength = XMLUtils.getFullTextChildrenFromNode(n);
if (hmacLength != null && hmacLength.length() != 0) {
this.hmacOutputLength = new HMACOutputLength(Integer.parseInt(hmacLength));
}
}
}
/**
* Method engineAddContextToElement
*
* @param element
*/
@Override
protected void engineAddContextToElement(Element element) throws XMLSignatureException {
if (element == null) {
throw new IllegalArgumentException("null element");
}
if (hmacOutputLength != null) {
Document doc = element.getOwnerDocument();
Element HMElem =
XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
Text HMText =
doc.createTextNode("" + hmacOutputLength.length);
HMElem.appendChild(HMText);
XMLUtils.addReturnToElement(element);
element.appendChild(HMElem);
XMLUtils.addReturnToElement(element);
}
}
/**
* Class IntegrityHmacSHA1
*/
public static class IntegrityHmacSHA1 extends IntegrityHmac {
/**
* Constructor IntegrityHmacSHA1
*
* @throws XMLSignatureException
*/
public IntegrityHmacSHA1() throws XMLSignatureException {
super();
}
public IntegrityHmacSHA1(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
* {@inheritDoc}
*
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
}
@Override
int getDigestLength() {
return 160;
}
}
/**
* Class IntegrityHmacSHA224
*/
public static class IntegrityHmacSHA224 extends IntegrityHmac {
/**
* Constructor IntegrityHmacSHA224
*
* @throws XMLSignatureException
*/
public IntegrityHmacSHA224() throws XMLSignatureException {
super();
}
public IntegrityHmacSHA224(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
*
* {@inheritDoc}
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_SHA224;
}
@Override
int getDigestLength() {
return 224;
}
}
/**
* Class IntegrityHmacSHA256
*/
public static class IntegrityHmacSHA256 extends IntegrityHmac {
/**
* Constructor IntegrityHmacSHA256
*
* @throws XMLSignatureException
*/
public IntegrityHmacSHA256() throws XMLSignatureException {
super();
}
public IntegrityHmacSHA256(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
*
* {@inheritDoc}
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
}
@Override
int getDigestLength() {
return 256;
}
}
/**
* Class IntegrityHmacSHA384
*/
public static class IntegrityHmacSHA384 extends IntegrityHmac {
/**
* Constructor IntegrityHmacSHA384
*
* @throws XMLSignatureException
*/
public IntegrityHmacSHA384() throws XMLSignatureException {
super();
}
public IntegrityHmacSHA384(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
* {@inheritDoc}
*
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
}
@Override
int getDigestLength() {
return 384;
}
}
/**
* Class IntegrityHmacSHA512
*/
public static class IntegrityHmacSHA512 extends IntegrityHmac {
/**
* Constructor IntegrityHmacSHA512
*
* @throws XMLSignatureException
*/
public IntegrityHmacSHA512() throws XMLSignatureException {
super();
}
public IntegrityHmacSHA512(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
* {@inheritDoc}
*
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
}
@Override
int getDigestLength() {
return 512;
}
}
/**
* Class IntegrityHmacRIPEMD160
*/
public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
/**
* Constructor IntegrityHmacRIPEMD160
*
* @throws XMLSignatureException
*/
public IntegrityHmacRIPEMD160() throws XMLSignatureException {
super();
}
public IntegrityHmacRIPEMD160(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
*
* {@inheritDoc}
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
}
@Override
int getDigestLength() {
return 160;
}
}
/**
* Class IntegrityHmacMD5
*/
public static class IntegrityHmacMD5 extends IntegrityHmac {
/**
* Constructor IntegrityHmacMD5
*
* @throws XMLSignatureException
*/
public IntegrityHmacMD5() throws XMLSignatureException {
super();
}
public IntegrityHmacMD5(Provider provider) throws XMLSignatureException {
super(provider);
}
/**
* Method engineGetURI
*
* {@inheritDoc}
*/
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
}
@Override
int getDigestLength() {
return 128;
}
}
private static class HMACOutputLength {
private static final int MIN_LENGTH = 128;
private static final int MAX_LENGTH = 2048;
private final int length;
public HMACOutputLength(int length) throws XMLSignatureException {
this.length = length;
// Test some invariants
if (length < MIN_LENGTH) {
LOG.debug("HMACOutputLength must not be less than {}", MIN_LENGTH);
Object[] exArgs = { String.valueOf(MIN_LENGTH) };
throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs);
}
if (length > MAX_LENGTH) {
LOG.debug("HMACOutputLength must not be more than {}", MAX_LENGTH);
Object[] exArgs = { String.valueOf(MAX_LENGTH) };
throw new XMLSignatureException("algorithms.HMACOutputLengthMax", exArgs);
}
}
}
}

View file

@ -0,0 +1,870 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import javax.xml.crypto.dsig.DigestMethod;
public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureBaseRSA.class);
/** Field algorithm */
private final Signature signatureAlgorithm;
/**
* Constructor SignatureRSA
*
* @throws XMLSignatureException
*/
public SignatureBaseRSA() throws XMLSignatureException {
this(null);
}
public SignatureBaseRSA(Provider provider) throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
this.signatureAlgorithm = getSignature(provider, algorithmID);
LOG.debug("Created SignatureRSA using {0}", algorithmID);
}
Signature getSignature(Provider provider, String algorithmID)
throws XMLSignatureException {
try {
if (provider == null) {
String providerId = JCEMapper.getProviderId();
if (providerId == null) {
return Signature.getInstance(algorithmID);
} else {
return Signature.getInstance(algorithmID, providerId);
}
} else {
return Signature.getInstance(algorithmID, provider);
}
} catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
Object[] exArgs = {algorithmID, ex.getLocalizedMessage()};
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
}
/** {@inheritDoc} */
@Override
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
try {
return this.signatureAlgorithm.verify(signature);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
engineInitVerify(publicKey, this.signatureAlgorithm);
}
/** {@inheritDoc} */
@Override
protected byte[] engineSign() throws XMLSignatureException {
try {
return this.signatureAlgorithm.sign();
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException {
engineInitSign(privateKey, secureRandom, this.signatureAlgorithm);
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
engineInitSign(privateKey, (SecureRandom)null);
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected String engineGetJCEAlgorithmString() {
return this.signatureAlgorithm.getAlgorithm();
}
/** {@inheritDoc} */
@Override
protected String engineGetJCEProviderName() {
return this.signatureAlgorithm.getProvider().getName();
}
/** {@inheritDoc} */
@Override
protected void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException {
throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
}
/**
* Class SignatureRSASHA1
*/
public static class SignatureRSASHA1 extends SignatureBaseRSA {
/**
* Constructor SignatureRSASHA1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA1() throws XMLSignatureException {
super();
}
public SignatureRSASHA1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
}
}
/**
* Class SignatureRSASHA224
*/
public static class SignatureRSASHA224 extends SignatureBaseRSA {
/**
* Constructor SignatureRSASHA224
*
* @throws XMLSignatureException
*/
public SignatureRSASHA224() throws XMLSignatureException {
super();
}
public SignatureRSASHA224(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224;
}
}
/**
* Class SignatureRSASHA256
*/
public static class SignatureRSASHA256 extends SignatureBaseRSA {
/**
* Constructor SignatureRSASHA256
*
* @throws XMLSignatureException
*/
public SignatureRSASHA256() throws XMLSignatureException {
super();
}
public SignatureRSASHA256(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
}
}
/**
* Class SignatureRSASHA384
*/
public static class SignatureRSASHA384 extends SignatureBaseRSA {
/**
* Constructor SignatureRSASHA384
*
* @throws XMLSignatureException
*/
public SignatureRSASHA384() throws XMLSignatureException {
super();
}
public SignatureRSASHA384(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384;
}
}
/**
* Class SignatureRSASHA512
*/
public static class SignatureRSASHA512 extends SignatureBaseRSA {
/**
* Constructor SignatureRSASHA512
*
* @throws XMLSignatureException
*/
public SignatureRSASHA512() throws XMLSignatureException {
super();
}
public SignatureRSASHA512(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512;
}
}
/**
* Class SignatureRSARIPEMD160
*/
public static class SignatureRSARIPEMD160 extends SignatureBaseRSA {
/**
* Constructor SignatureRSARIPEMD160
*
* @throws XMLSignatureException
*/
public SignatureRSARIPEMD160() throws XMLSignatureException {
super();
}
public SignatureRSARIPEMD160(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160;
}
}
/**
* Class SignatureRSAMD5
*/
public static class SignatureRSAMD5 extends SignatureBaseRSA {
/**
* Constructor SignatureRSAMD5
*
* @throws XMLSignatureException
*/
public SignatureRSAMD5() throws XMLSignatureException {
super();
}
public SignatureRSAMD5(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5;
}
}
public abstract static class SignatureBaseRSAPSS extends SignatureBaseRSA {
public SignatureBaseRSAPSS() throws XMLSignatureException {
super();
}
public SignatureBaseRSAPSS(Provider provider) throws XMLSignatureException {
super(provider);
}
@Override
Signature getSignature(Provider provider, String algorithmID)
throws XMLSignatureException {
try {
Signature sig;
if (provider == null) {
String providerId = JCEMapper.getProviderId();
if (providerId == null) {
sig = Signature.getInstance("RSASSA-PSS");
} else {
sig = Signature.getInstance("RSASSA-PSS", providerId);
}
} else {
sig = Signature.getInstance("RSASSA-PSS", provider);
}
try {
sig.setParameter(getPSSParameterSpec());
} catch (InvalidAlgorithmParameterException e) {
throw new NoSuchAlgorithmException("Should not happen", e);
}
return sig;
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
return super.getSignature(provider, algorithmID);
}
}
abstract PSSParameterSpec getPSSParameterSpec();
}
/**
* Class SignatureRSASHA1MGF1
*/
public static class SignatureRSASHA1MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA1_MGF1_PARAMS
= new PSSParameterSpec("SHA-1", "MGF1", MGF1ParameterSpec.SHA1,
20, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA1MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA1MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA1MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA1_MGF1_PARAMS;
}
}
/**
* Class SignatureRSASHA224MGF1
*/
public static class SignatureRSASHA224MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA224_MGF1_PARAMS
= new PSSParameterSpec("SHA-224", "MGF1", MGF1ParameterSpec.SHA224,
28, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA224MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA224MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA224MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA224_MGF1_PARAMS;
}
}
/**
* Class SignatureRSASHA256MGF1
*/
public static class SignatureRSASHA256MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA256_MGF1_PARAMS
= new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
32, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA256MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA256MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA256MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA256_MGF1_PARAMS;
}
}
/**
* Class SignatureRSASHA384MGF1
*/
public static class SignatureRSASHA384MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA384_MGF1_PARAMS
= new PSSParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384,
48, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA384MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA384MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA384MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA384_MGF1_PARAMS;
}
}
/**
* Class SignatureRSASHA512MGF1
*/
public static class SignatureRSASHA512MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA512_MGF1_PARAMS
= new PSSParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512,
64, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA512MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA512MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA512MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA512_MGF1_PARAMS;
}
}
/**
* Class SignatureRSA3_SHA224MGF1
*/
public static class SignatureRSASHA3_224MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA3_224_MGF1_PARAMS
= new PSSParameterSpec("SHA3-224", "MGF1",
new MGF1ParameterSpec("SHA3-224"),
28, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA3_224MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA3_224MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA3_224MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA3_224_MGF1_PARAMS;
}
}
/**
* Class SignatureRSA3_SHA256MGF1
*/
public static class SignatureRSASHA3_256MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA3_256_MGF1_PARAMS
= new PSSParameterSpec("SHA3-256", "MGF1",
new MGF1ParameterSpec("SHA3-256"),
32, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA3_256MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA3_256MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA3_256MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA3_256_MGF1_PARAMS;
}
}
/**
* Class SignatureRSA3_SHA384MGF1
*/
public static class SignatureRSASHA3_384MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA3_384_MGF1_PARAMS
= new PSSParameterSpec("SHA3-384", "MGF1",
new MGF1ParameterSpec("SHA3-384"),
48, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA3_384MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA3_384MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA3_384MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA3_384_MGF1_PARAMS;
}
}
/**
* Class SignatureRSASHA3_512MGF1
*/
public static class SignatureRSASHA3_512MGF1 extends SignatureBaseRSAPSS {
private static final PSSParameterSpec SHA3_512_MGF1_PARAMS
= new PSSParameterSpec("SHA3-512", "MGF1",
new MGF1ParameterSpec("SHA3-512"),
64, PSSParameterSpec.TRAILER_FIELD_BC);
/**
* Constructor SignatureRSASHA3_512MGF1
*
* @throws XMLSignatureException
*/
public SignatureRSASHA3_512MGF1() throws XMLSignatureException {
super();
}
public SignatureRSASHA3_512MGF1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1;
}
@Override
public PSSParameterSpec getPSSParameterSpec() {
return SHA3_512_MGF1_PARAMS;
}
}
public static class SignatureRSASSAPSS extends SignatureBaseRSA {
private PSSParameterSpec pssParameterSpec;
public enum DigestAlgorithm {
SHA224("SHA-224", DigestMethod.SHA224, 28),
SHA256("SHA-256", DigestMethod.SHA256, 32),
SHA384("SHA-384", DigestMethod.SHA384, 48),
SHA512("SHA-512", DigestMethod.SHA512, 64),
SHA3_224("SHA3-224", DigestMethod.SHA3_224, 28),
SHA3_256("SHA3-256", DigestMethod.SHA3_256, 32),
SHA3_384("SHA3-384", DigestMethod.SHA3_384, 48),
SHA3_512("SHA3-512", DigestMethod.SHA3_512, 64);
private final String xmlDigestAlgorithm;
private final String digestAlgorithm;
private final int saltLength;
DigestAlgorithm(String digestAlgorithm, String xmlDigestAlgorithm, int saltLength) {
this.digestAlgorithm = digestAlgorithm;
this.xmlDigestAlgorithm = xmlDigestAlgorithm;
this.saltLength = saltLength;
}
public String getXmlDigestAlgorithm() {
return xmlDigestAlgorithm;
}
public String getDigestAlgorithm() {
return digestAlgorithm;
}
public int getSaltLength() {
return saltLength;
}
public static DigestAlgorithm fromXmlDigestAlgorithm(String xmlDigestAlgorithm) throws XMLSignatureException {
for (DigestAlgorithm value : DigestAlgorithm.values()) {
if(value.getXmlDigestAlgorithm().equals(xmlDigestAlgorithm)) {
return value;
}
}
throw new XMLSignatureException();
}
public static DigestAlgorithm fromDigestAlgorithm(String digestAlgorithm) throws XMLSignatureException {
for (DigestAlgorithm value : DigestAlgorithm.values()) {
if(value.getDigestAlgorithm().equals(digestAlgorithm)) {
return value;
}
}
throw new XMLSignatureException();
}
}
public SignatureRSASSAPSS() throws XMLSignatureException {
super();
}
public SignatureRSASSAPSS(Provider provider) throws XMLSignatureException {
super(provider);
}
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_RSA_PSS;
}
@Override
protected void engineAddContextToElement(Element element) throws XMLSignatureException {
if (element == null) {
throw new IllegalArgumentException("null element");
}
Document doc = element.getOwnerDocument();
Element rsaPssParamsElement = doc.createElementNS(Constants.XML_DSIG_NS_MORE_07_05, "pss" + ":" + Constants._TAG_RSAPSSPARAMS);
rsaPssParamsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + "pss", Constants.XML_DSIG_NS_MORE_07_05);
Element digestMethodElement = XMLUtils.createElementInSignatureSpace(rsaPssParamsElement.getOwnerDocument(), Constants._TAG_DIGESTMETHOD);
digestMethodElement.setAttributeNS(null, Constants._ATT_ALGORITHM, DigestAlgorithm.fromDigestAlgorithm(pssParameterSpec.getDigestAlgorithm()).getXmlDigestAlgorithm());
XMLUtils.addReturnToElement(rsaPssParamsElement);
rsaPssParamsElement.appendChild(digestMethodElement);
XMLUtils.addReturnToElement(rsaPssParamsElement);
Element saltLengthElement = rsaPssParamsElement.getOwnerDocument().createElementNS(Constants.XML_DSIG_NS_MORE_07_05, "pss" + ":" + Constants._TAG_SALTLENGTH);
Text saltLengthText = rsaPssParamsElement.getOwnerDocument().createTextNode(String.valueOf(pssParameterSpec.getSaltLength()));
saltLengthElement.appendChild(saltLengthText);
rsaPssParamsElement.appendChild(saltLengthElement);
XMLUtils.addReturnToElement(rsaPssParamsElement);
Element trailerFieldElement = rsaPssParamsElement.getOwnerDocument().createElementNS(Constants.XML_DSIG_NS_MORE_07_05, "pss" + ":" + Constants._TAG_TRAILERFIELD);
Text trailerFieldText = rsaPssParamsElement.getOwnerDocument().createTextNode(String.valueOf(pssParameterSpec.getTrailerField()));
trailerFieldElement.appendChild(trailerFieldText);
rsaPssParamsElement.appendChild(trailerFieldElement);
XMLUtils.addReturnToElement(rsaPssParamsElement);
XMLUtils.addReturnToElement(element);
element.appendChild(rsaPssParamsElement);
XMLUtils.addReturnToElement(element);
}
@Override
protected void engineGetContextFromElement(Element element) throws XMLSignatureException {
if (pssParameterSpec == null) {
super.engineGetContextFromElement(element);
Element rsaPssParams = XMLUtils.selectNode(element.getFirstChild(), Constants.XML_DSIG_NS_MORE_07_05, Constants._TAG_RSAPSSPARAMS, 0);
if (rsaPssParams == null) {
throw new XMLSignatureException("algorithms.MissingRSAPSSParams");
}
Element saltLengthNode = XMLUtils.selectNode(rsaPssParams.getFirstChild(), Constants.XML_DSIG_NS_MORE_07_05, Constants._TAG_SALTLENGTH, 0);
Element trailerFieldNode = XMLUtils.selectNode(rsaPssParams.getFirstChild(), Constants.XML_DSIG_NS_MORE_07_05, Constants._TAG_TRAILERFIELD, 0);
int trailerField = 1;
if (trailerFieldNode != null) {
try {
trailerField = Integer.parseInt(trailerFieldNode.getTextContent());
} catch (NumberFormatException ex) {
throw new XMLSignatureException("empty", new Object[] {"Invalid trailer field value supplied"});
}
}
String xmlAlgorithm = XMLUtils.selectDsNode(rsaPssParams.getFirstChild(), Constants._TAG_DIGESTMETHOD, 0).getAttribute(Constants._ATT_ALGORITHM);
DigestAlgorithm digestAlgorithm = DigestAlgorithm.fromXmlDigestAlgorithm(xmlAlgorithm);
String digestAlgorithmName = digestAlgorithm.getDigestAlgorithm();
int saltLength = digestAlgorithm.getSaltLength();
if (saltLengthNode != null) {
try {
saltLength = Integer.parseInt(saltLengthNode.getTextContent());
} catch (NumberFormatException ex) {
throw new XMLSignatureException("empty", new Object[] {"Invalid salt length value supplied"});
}
}
engineSetParameter(new PSSParameterSpec(digestAlgorithmName, "MGF1", new MGF1ParameterSpec(digestAlgorithmName), saltLength, trailerField));
}
}
@Override
protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException {
pssParameterSpec = (PSSParameterSpec) params;
super.engineSetParameter(params);
}
}
}

View file

@ -0,0 +1,270 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.DSAKey;
import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
public class SignatureDSA extends SignatureAlgorithmSpi {
public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureDSA.class);
/** Field algorithm */
private final Signature signatureAlgorithm;
/** size of Q */
private int size;
/**
* Method engineGetURI
*
* {@inheritDoc}
*/
@Override
protected String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_DSA;
}
/**
* Constructor SignatureDSA
*
* @throws XMLSignatureException
*/
public SignatureDSA() throws XMLSignatureException {
this(null);
}
public SignatureDSA(Provider provider) throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(engineGetURI());
LOG.debug("Created SignatureDSA using {}", algorithmID);
try {
if (provider == null) {
String providerId = JCEMapper.getProviderId();
if (providerId == null) {
this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else {
this.signatureAlgorithm = Signature.getInstance(algorithmID, providerId);
}
} else {
this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
}
} catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
Object[] exArgs = {algorithmID, ex.getLocalizedMessage()};
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
protected boolean engineVerify(byte[] signature)
throws XMLSignatureException {
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Called DSA.verify() on " + XMLUtils.encodeToString(signature));
}
byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature, size / 8);
return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException | IOException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
engineInitVerify(publicKey, this.signatureAlgorithm);
size = ((DSAKey)publicKey).getParams().getQ().bitLength();
}
/**
* {@inheritDoc}
*/
@Override
protected byte[] engineSign() throws XMLSignatureException {
try {
byte[] jcebytes = this.signatureAlgorithm.sign();
return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size / 8);
} catch (IOException | SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException {
engineInitSign(privateKey, secureRandom, this.signatureAlgorithm);
size = ((DSAKey)privateKey).getParams().getQ().bitLength();
}
/**
* {@inheritDoc}
*/
@Override
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
engineInitSign(privateKey, (SecureRandom)null);
}
/**
* {@inheritDoc}
*/
@Override
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method engineGetJCEAlgorithmString
*
* {@inheritDoc}
*/
@Override
protected String engineGetJCEAlgorithmString() {
return this.signatureAlgorithm.getAlgorithm();
}
/**
* Method engineGetJCEProviderName
*
* {@inheritDoc}
*/
@Override
protected String engineGetJCEProviderName() {
return this.signatureAlgorithm.getProvider().getName();
}
/**
* Method engineSetHMACOutputLength
*
* @param HMACOutputLength
* @throws XMLSignatureException
*/
@Override
protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/**
* Method engineInitSign
*
* @param signingKey
* @param algorithmParameterSpec
* @throws XMLSignatureException
*/
@Override
protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA");
}
public static class SHA256 extends SignatureDSA {
public SHA256() throws XMLSignatureException {
super();
}
public SHA256(Provider provider) throws XMLSignatureException {
super(provider);
}
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256;
}
}
}

View file

@ -0,0 +1,503 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
/**
*
*/
public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureECDSA.class);
private final Signature signatureAlgorithm;
/** Length for each integer in signature */
private int signIntLen = -1;
/**
* Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
*
* The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param asn1Bytes
* @param rawLen
* @return the decode bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/
public static byte[] convertASN1toXMLDSIG(byte[] asn1Bytes, int rawLen) throws IOException {
return ECDSAUtils.convertASN1toXMLDSIG(asn1Bytes, rawLen);
}
/**
* Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
*
* The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param xmldsigBytes
* @return the encoded ASN.1 bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/
public static byte[] convertXMLDSIGtoASN1(byte[] xmldsigBytes) throws IOException {
return ECDSAUtils.convertXMLDSIGtoASN1(xmldsigBytes);
}
/**
* Constructor SignatureRSA
*
* @throws XMLSignatureException
*/
public SignatureECDSA() throws XMLSignatureException {
this(null);
}
public SignatureECDSA(Provider provider) throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
LOG.debug("Created SignatureECDSA using {}", algorithmID);
try {
if (provider == null) {
String providerId = JCEMapper.getProviderId();
if (providerId == null) {
this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else {
this.signatureAlgorithm = Signature.getInstance(algorithmID, providerId);
}
} else {
this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
}
} catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
}
/** {@inheritDoc} */
@Override
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
try {
byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
if (LOG.isDebugEnabled()) {
LOG.debug("Called ECDSA.verify() on " + XMLUtils.encodeToString(signature));
}
return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException | IOException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
engineInitVerify(publicKey, signatureAlgorithm);
}
/** {@inheritDoc} */
@Override
protected byte[] engineSign() throws XMLSignatureException {
try {
byte[] jcebytes = this.signatureAlgorithm.sign();
return SignatureECDSA.convertASN1toXMLDSIG(jcebytes, signIntLen);
} catch (SignatureException | IOException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException {
if (privateKey instanceof ECPrivateKey) {
ECPrivateKey ecKey = (ECPrivateKey) privateKey;
signIntLen = (ecKey.getParams().getCurve().getField().getFieldSize() + 7) / 8;
// If not ECPrivateKey, signIntLen remains -1
}
engineInitSign(privateKey, secureRandom, this.signatureAlgorithm);
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
engineInitSign(privateKey, (SecureRandom)null);
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected String engineGetJCEAlgorithmString() {
return this.signatureAlgorithm.getAlgorithm();
}
/** {@inheritDoc} */
@Override
protected String engineGetJCEProviderName() {
return this.signatureAlgorithm.getProvider().getName();
}
/** {@inheritDoc} */
@Override
protected void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException {
throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
}
/**
* Class SignatureECDSASHA1
*
*/
public static class SignatureECDSASHA1 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA1
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA1() throws XMLSignatureException {
super();
}
public SignatureECDSASHA1(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
}
}
/**
* Class SignatureECDSASHA224
*/
public static class SignatureECDSASHA224 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA224
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA224() throws XMLSignatureException {
super();
}
public SignatureECDSASHA224(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224;
}
}
/**
* Class SignatureECDSASHA256
*
*/
public static class SignatureECDSASHA256 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA256
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA256() throws XMLSignatureException {
super();
}
public SignatureECDSASHA256(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256;
}
}
/**
* Class SignatureECDSASHA384
*
*/
public static class SignatureECDSASHA384 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA384
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA384() throws XMLSignatureException {
super();
}
public SignatureECDSASHA384(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384;
}
}
/**
* Class SignatureECDSASHA512
*
*/
public static class SignatureECDSASHA512 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA512
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA512() throws XMLSignatureException {
super();
}
public SignatureECDSASHA512(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512;
}
}
/**
* Class SignatureECDSASHA3-224
*
*/
public static class SignatureECDSASHA3_224 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA3-224
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA3_224() throws XMLSignatureException {
super();
}
public SignatureECDSASHA3_224(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_224;
}
}
/**
* Class SignatureECDSASHA3-256
*
*/
public static class SignatureECDSASHA3_256 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA3-256
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA3_256() throws XMLSignatureException {
super();
}
public SignatureECDSASHA3_256(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_256;
}
}
/**
* Class SignatureECDSASHA3-384
*
*/
public static class SignatureECDSASHA3_384 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA3-384
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA3_384() throws XMLSignatureException {
super();
}
public SignatureECDSASHA3_384(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_384;
}
}
/**
* Class SignatureECDSASHA3-512
*
*/
public static class SignatureECDSASHA3_512 extends SignatureECDSA {
/**
* Constructor SignatureECDSASHA3-512
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA3_512() throws XMLSignatureException {
super();
}
public SignatureECDSASHA3_512(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA3_512;
}
}
/**
* Class SignatureECDSARIPEMD160
*/
public static class SignatureECDSARIPEMD160 extends SignatureECDSA {
/**
* Constructor SignatureECDSARIPEMD160
*
* @throws XMLSignatureException
*/
public SignatureECDSARIPEMD160() throws XMLSignatureException {
super();
}
public SignatureECDSARIPEMD160(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160;
}
}
}

View file

@ -0,0 +1,247 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.security.InvalidAlgorithmParameterException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
/**
*
*/
public abstract class SignatureEDDSA extends SignatureAlgorithmSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureEDDSA.class);
private final Signature signatureAlgorithm;
/**
* Constructor SignatureEDDSA
*
* @throws XMLSignatureException
*/
public SignatureEDDSA() throws XMLSignatureException {
this(null);
}
public SignatureEDDSA(Provider provider) throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
LOG.debug("Created SignatureEDDSA using {}", algorithmID);
try {
if (provider == null) {
String providerId = JCEMapper.getProviderId();
if (providerId == null) {
this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else {
this.signatureAlgorithm = Signature.getInstance(algorithmID, providerId);
}
} else {
this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
}
} catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
}
/** {@inheritDoc} */
@Override
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Called SignatureEDDSA.verify() on " + XMLUtils.encodeToString(signature));
}
return this.signatureAlgorithm.verify(signature);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
engineInitVerify(publicKey, signatureAlgorithm);
}
/** {@inheritDoc} */
@Override
protected byte[] engineSign() throws XMLSignatureException {
try {
return this.signatureAlgorithm.sign();
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException {
engineInitSign(privateKey, secureRandom, this.signatureAlgorithm);
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
engineInitSign(privateKey, (SecureRandom)null);
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException {
try {
this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException(ex);
}
}
/** {@inheritDoc} */
@Override
protected String engineGetJCEAlgorithmString() {
return this.signatureAlgorithm.getAlgorithm();
}
/** {@inheritDoc} */
@Override
protected String engineGetJCEProviderName() {
return this.signatureAlgorithm.getProvider().getName();
}
/** {@inheritDoc} */
@Override
protected void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException {
throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/** {@inheritDoc} */
@Override
protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
) throws XMLSignatureException {
throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnEdDSA");
}
/**
* Class SignatureEd25519
*
*/
public static class SignatureEd25519 extends SignatureEDDSA {
/**
* Constructor SignatureEd25519
*
* @throws XMLSignatureException
*/
public SignatureEd25519() throws XMLSignatureException {
super();
}
public SignatureEd25519(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_EDDSA_ED25519;
}
}
/**
* Class SignatureEd448
*/
public static class SignatureEd448 extends SignatureEDDSA {
/**
* Constructor SignatureEd448
*
* @throws XMLSignatureException
*/
public SignatureEd448() throws XMLSignatureException {
super();
}
public SignatureEd448(Provider provider) throws XMLSignatureException {
super(provider);
}
/** {@inheritDoc} */
@Override
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_EDDSA_ED448;
}
}
}

View file

@ -0,0 +1,101 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
/**
* Class CanonicalizationException
*
*/
public class CanonicalizationException extends XMLSecurityException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor CanonicalizationException
*
*/
public CanonicalizationException() {
super();
}
public CanonicalizationException(Exception ex) {
super(ex);
}
/**
* Constructor CanonicalizationException
*
* @param msgID
*/
public CanonicalizationException(String msgID) {
super(msgID);
}
/**
* Constructor CanonicalizationException
*
* @param msgID
* @param exArgs
*/
public CanonicalizationException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor CanonicalizationException
*
* @param originalException
* @param msgID
*/
public CanonicalizationException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public CanonicalizationException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor CanonicalizationException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public CanonicalizationException(
Exception originalException, String msgID, Object[] exArgs
) {
super(originalException, msgID, exArgs);
}
@Deprecated
public CanonicalizationException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,297 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclOmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Node;
/**
*
*/
public final class Canonicalizer {
/** The output encoding of canonicalized data */
public static final String ENCODING = StandardCharsets.UTF_8.name();
/**
* XPath Expression for selecting every node and continuous comments joined
* in only one node
*/
public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE =
"(.//. | .//@* | .//namespace::*)";
/**
* The URL defined in XML-SEC Rec for inclusive c14n <b>without</b> comments.
*/
public static final String ALGO_ID_C14N_OMIT_COMMENTS =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
/**
* The URL defined in XML-SEC Rec for inclusive c14n <b>with</b> comments.
*/
public static final String ALGO_ID_C14N_WITH_COMMENTS =
ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments";
/**
* The URL defined in XML-SEC Rec for exclusive c14n <b>without</b> comments.
*/
public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS =
"http://www.w3.org/2001/10/xml-exc-c14n#";
/**
* The URL defined in XML-SEC Rec for exclusive c14n <b>with</b> comments.
*/
public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS =
ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments";
/**
* The URI for inclusive c14n 1.1 <b>without</b> comments.
*/
public static final String ALGO_ID_C14N11_OMIT_COMMENTS =
"http://www.w3.org/2006/12/xml-c14n11";
/**
* The URI for inclusive c14n 1.1 <b>with</b> comments.
*/
public static final String ALGO_ID_C14N11_WITH_COMMENTS =
ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments";
/**
* Non-standard algorithm to serialize the physical representation for XML Encryption
*/
public static final String ALGO_ID_C14N_PHYSICAL =
"http://santuario.apache.org/c14n/physical";
private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash =
new ConcurrentHashMap<>();
private final CanonicalizerSpi canonicalizerSpi;
/**
* Constructor Canonicalizer
*
* @param algorithmURI
* @throws InvalidCanonicalizerException
*/
private Canonicalizer(String algorithmURI) throws InvalidCanonicalizerException {
try {
Class<? extends CanonicalizerSpi> implementingClass =
canonicalizerHash.get(algorithmURI);
canonicalizerSpi = JavaUtils.newInstanceWithEmptyConstructor(implementingClass);
} catch (Exception e) {
Object[] exArgs = { algorithmURI };
throw new InvalidCanonicalizerException(
e, "signature.Canonicalizer.UnknownCanonicalizer", exArgs
);
}
}
/**
* Method getInstance
*
* @param algorithmURI
* @return a Canonicalizer instance ready for the job
* @throws InvalidCanonicalizerException
*/
public static Canonicalizer getInstance(String algorithmURI)
throws InvalidCanonicalizerException {
return new Canonicalizer(algorithmURI);
}
/**
* Method register
*
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the canonicalizer
*/
@SuppressWarnings("unchecked")
public static void register(String algorithmURI, String implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
JavaUtils.checkRegisterPermission();
// check whether URI is already registered
Class<? extends CanonicalizerSpi> registeredClass =
canonicalizerHash.get(algorithmURI);
if (registeredClass != null) {
Object[] exArgs = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
}
canonicalizerHash.put(
algorithmURI, (Class<? extends CanonicalizerSpi>)
ClassLoaderUtils.loadClass(implementingClass, Canonicalizer.class)
);
}
/**
* Method register
*
* @param algorithmURI
* @param implementingClass
* @throws AlgorithmAlreadyRegisteredException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the canonicalizer
*/
public static void register(String algorithmURI, Class<? extends CanonicalizerSpi> implementingClass)
throws AlgorithmAlreadyRegisteredException, ClassNotFoundException {
JavaUtils.checkRegisterPermission();
// check whether URI is already registered
Class<? extends CanonicalizerSpi> registeredClass = canonicalizerHash.get(algorithmURI);
if (registeredClass != null) {
Object[] exArgs = { algorithmURI, registeredClass };
throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs);
}
canonicalizerHash.put(algorithmURI, implementingClass);
}
/**
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS,
Canonicalizer20010315OmitComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS,
Canonicalizer20010315WithComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS,
Canonicalizer20010315ExclOmitComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS,
Canonicalizer20010315ExclWithComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS,
Canonicalizer11_OmitComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS,
Canonicalizer11_WithComments.class
);
canonicalizerHash.put(
Canonicalizer.ALGO_ID_C14N_PHYSICAL,
CanonicalizerPhysical.class
);
}
/**
* This method tries to canonicalize the given bytes. It's possible to even
* canonicalize non-wellformed sequences if they are well-formed after being
* wrapped with a {@code &gt;a&lt;...&gt;/a&lt;}.
*
* @param inputBytes
* @param writer OutputStream to write the canonicalization result
* @param secureValidation Whether secure validation is enabled
* @throws CanonicalizationException
* @throws java.io.IOException
* @throws XMLParserException
*/
public void canonicalize(byte[] inputBytes, OutputStream writer, boolean secureValidation)
throws XMLParserException, java.io.IOException, CanonicalizationException {
canonicalizerSpi.engineCanonicalize(inputBytes, writer, secureValidation);
}
/**
* Canonicalizes the subtree rooted by {@code node}.
*
* @param node The node to canonicalize
* @param writer OutputStream to write the canonicalization result
*
* @throws CanonicalizationException
*/
public void canonicalizeSubtree(Node node, OutputStream writer) throws CanonicalizationException {
canonicalizerSpi.engineCanonicalizeSubTree(node, writer);
}
/**
* Canonicalizes the subtree rooted by {@code node}.
*
* @param node
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public void canonicalizeSubtree(Node node, String inclusiveNamespaces, OutputStream writer)
throws CanonicalizationException {
canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, writer);
}
/**
* Canonicalizes the subtree rooted by {@code node}.
*
* @param node
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public void canonicalizeSubtree(Node node, String inclusiveNamespaces,
boolean propagateDefaultNamespace, OutputStream writer)
throws CanonicalizationException {
canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, propagateDefaultNamespace, writer);
}
/**
* Canonicalizes an XPath node set.
*
* @param xpathNodeSet
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public void canonicalizeXPathNodeSet(Set<Node> xpathNodeSet, OutputStream writer)
throws CanonicalizationException {
canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, writer);
}
/**
* Canonicalizes an XPath node set.
*
* @param xpathNodeSet
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public void canonicalizeXPathNodeSet(
Set<Node> xpathNodeSet, String inclusiveNamespaces, OutputStream writer
) throws CanonicalizationException {
canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces, writer);
}
}

View file

@ -0,0 +1,124 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Base class which all Canonicalization algorithms extend.
*
*/
public abstract class CanonicalizerSpi {
/**
* Method canonicalize
*
* @param inputBytes
* @param writer OutputStream to write the canonicalization result
* @param secureValidation Whether secure validation is enabled
*
* @throws XMLParserException
* @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException
*/
public void engineCanonicalize(byte[] inputBytes, OutputStream writer, boolean secureValidation)
throws XMLParserException, java.io.IOException, CanonicalizationException {
Document document = null;
try (java.io.InputStream bais = new ByteArrayInputStream(inputBytes)) {
document = XMLUtils.read(bais, secureValidation);
}
this.engineCanonicalizeSubTree(document, writer);
}
/**
* Returns the URI of this engine.
* @return the URI
*/
public abstract String engineGetURI();
/**
* C14n a nodeset
*
* @param xpathNodeSet
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public abstract void engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, OutputStream writer)
throws CanonicalizationException;
/**
* C14n a nodeset
*
* @param xpathNodeSet
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public abstract void engineCanonicalizeXPathNodeSet(
Set<Node> xpathNodeSet, String inclusiveNamespaces, OutputStream writer
) throws CanonicalizationException;
/**
* C14n a node tree.
*
* @param rootNode
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public abstract void engineCanonicalizeSubTree(Node rootNode, OutputStream writer)
throws CanonicalizationException;
/**
* C14n a node tree.
*
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public abstract void engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces, OutputStream writer)
throws CanonicalizationException;
/**
* C14n a node tree.
*
* @param rootNode
* @param inclusiveNamespaces
* @param propagateDefaultNamespace If true the default namespace will be propagated to the c14n-ized root element
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public abstract void engineCanonicalizeSubTree(
Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer)
throws CanonicalizationException;
}

View file

@ -0,0 +1,84 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
// modifiers changed to package-private. Make sure to integrate any future
// changes to utils.ClassLoaderUtils to this file.
final class ClassLoaderUtils {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
private ClassLoaderUtils() {
}
/**
* Load a class with a given name. <p></p> It will try to load the class in the
* following order:
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>Using the basic Class.forName()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>From the callingClass.getClassLoader()
* </ul>
*
* @param className The name of the class to load
* @param callingClass The Class object of the calling object
* @throws ClassNotFoundException If the class cannot be found anywhere.
*/
static Class<?> loadClass(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return cl.loadClass(className);
}
} catch (ClassNotFoundException e) {
LOG.debug(e.getMessage(), e);
//ignore
}
return loadClass2(className, callingClass);
}
private static Class<?> loadClass2(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
try {
if (ClassLoaderUtils.class.getClassLoader() != null) {
return ClassLoaderUtils.class.getClassLoader().loadClass(className);
}
} catch (ClassNotFoundException exc) {
if (callingClass != null && callingClass.getClassLoader() != null) {
return callingClass.getClassLoader().loadClass(className);
}
}
LOG.debug(ex.getMessage(), ex);
throw ex;
}
}
}

View file

@ -0,0 +1,93 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
public class InvalidCanonicalizerException extends XMLSecurityException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor InvalidCanonicalizerException
*
*/
public InvalidCanonicalizerException() {
super();
}
/**
* Constructor InvalidCanonicalizerException
*
* @param msgID
*/
public InvalidCanonicalizerException(String msgID) {
super(msgID);
}
/**
* Constructor InvalidCanonicalizerException
*
* @param msgID
* @param exArgs
*/
public InvalidCanonicalizerException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor InvalidCanonicalizerException
*
* @param originalException
* @param msgID
*/
public InvalidCanonicalizerException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public InvalidCanonicalizerException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor InvalidCanonicalizerException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public InvalidCanonicalizerException(
Exception originalException, String msgID, Object[] exArgs
) {
super(originalException, msgID, exArgs);
}
@Deprecated
public InvalidCanonicalizerException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,123 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.helper;
import java.io.Serializable;
import java.util.Comparator;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import org.w3c.dom.Attr;
/**
* Compares two attributes based on the C14n specification.
*
* <UL>
* <LI>Namespace nodes have a lesser document order position than attribute
* nodes.
* <LI> An element's namespace nodes are sorted lexicographically by
* local name (the default namespace node, if one exists, has no
* local name and is therefore lexicographically least).
* <LI> An element's attribute nodes are sorted lexicographically with
* namespace URI as the primary key and local name as the secondary
* key (an empty namespace URI is lexicographically least).
* </UL>
*
*/
public class AttrCompare implements Comparator<Attr>, Serializable {
private static final long serialVersionUID = -7113259629930576230L;
private static final int ATTR0_BEFORE_ATTR1 = -1;
private static final int ATTR1_BEFORE_ATTR0 = 1;
private static final String XMLNS = Constants.NamespaceSpecNS;
/**
* Compares two attributes based on the C14n specification.
*
* <UL>
* <LI>Namespace nodes have a lesser document order position than
* attribute nodes.
* <LI> An element's namespace nodes are sorted lexicographically by
* local name (the default namespace node, if one exists, has no
* local name and is therefore lexicographically least).
* <LI> An element's attribute nodes are sorted lexicographically with
* namespace URI as the primary key and local name as the secondary
* key (an empty namespace URI is lexicographically least).
* </UL>
*
* @param attr0
* @param attr1
* @return returns a negative integer, zero, or a positive integer as
* obj0 is less than, equal to, or greater than obj1
*
*/
@Override
public int compare(Attr attr0, Attr attr1) {
String namespaceURI0 = attr0.getNamespaceURI();
String namespaceURI1 = attr1.getNamespaceURI();
boolean isNamespaceAttr0 = XMLNS.equals(namespaceURI0);
boolean isNamespaceAttr1 = XMLNS.equals(namespaceURI1);
if (isNamespaceAttr0) {
if (isNamespaceAttr1) {
// both are namespaces
String localname0 = attr0.getLocalName();
String localname1 = attr1.getLocalName();
if ("xmlns".equals(localname0)) {
localname0 = "";
}
if ("xmlns".equals(localname1)) {
localname1 = "";
}
return localname0.compareTo(localname1);
}
// attr0 is a namespace, attr1 is not
return ATTR0_BEFORE_ATTR1;
} else if (isNamespaceAttr1) {
// attr1 is a namespace, attr0 is not
return ATTR1_BEFORE_ATTR0;
}
// none is a namespace
if (namespaceURI0 == null) {
if (namespaceURI1 == null) {
String name0 = attr0.getName();
String name1 = attr1.getName();
return name0.compareTo(name1);
}
return ATTR0_BEFORE_ATTR1;
} else if (namespaceURI1 == null) {
return ATTR1_BEFORE_ATTR0;
}
int a = namespaceURI0.compareTo(namespaceURI1);
if (a != 0) {
return a;
}
return attr0.getLocalName().compareTo(attr1.getLocalName());
}
}

View file

@ -0,0 +1,84 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.helper;
import org.w3c.dom.Attr;
/**
* Temporary swapped static functions from the normalizer Section
*
*/
public final class C14nHelper {
/**
* Constructor C14nHelper
*/
private C14nHelper() {
// don't allow instantiation
}
/**
* Method namespaceIsRelative
*
* @param namespace
* @return true if the given namespace is relative.
*/
public static boolean namespaceIsRelative(Attr namespace) {
return !namespaceIsAbsolute(namespace);
}
/**
* Method namespaceIsRelative
*
* @param namespaceValue
* @return true if the given namespace is relative.
*/
public static boolean namespaceIsRelative(String namespaceValue) {
return !namespaceIsAbsolute(namespaceValue);
}
/**
* Method namespaceIsAbsolute
*
* @param namespace
* @return true if the given namespace is absolute.
*/
public static boolean namespaceIsAbsolute(Attr namespace) {
return namespaceIsAbsolute(namespace.getValue());
}
/**
* Method namespaceIsAbsolute
*
* @param namespaceValue
* @return true if the given namespace is absolute.
*/
public static boolean namespaceIsAbsolute(String namespaceValue) {
// assume empty namespaces are absolute
if (namespaceValue.length() == 0) {
return true;
}
return namespaceValue.indexOf(':') > 0;
}
}

View file

@ -0,0 +1,40 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
*/
public class Canonicalizer11_OmitComments extends Canonicalizer20010315 {
public Canonicalizer11_OmitComments() {
super(false, true);
}
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS;
}
}

View file

@ -0,0 +1,40 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
*/
public class Canonicalizer11_WithComments extends Canonicalizer20010315 {
public Canonicalizer11_WithComments() {
super(true, true);
}
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS;
}
}

View file

@ -0,0 +1,355 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* Implements <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical
* XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
*
*/
public abstract class Canonicalizer20010315 extends CanonicalizerBase {
private boolean firstCall = true;
private final XmlAttrStack xmlattrStack;
private final boolean c14n11;
/**
* Constructor Canonicalizer20010315
*
* @param includeComments
*/
public Canonicalizer20010315(boolean includeComments) {
this(includeComments, false);
}
/**
* Constructor Canonicalizer20010315
*
* @param includeComments
* @param c14n11 Whether this is a Canonical XML 1.1 implementation or not
*/
public Canonicalizer20010315(boolean includeComments, boolean c14n11) {
super(includeComments);
xmlattrStack = new XmlAttrStack(c14n11);
this.c14n11 = c14n11;
}
/**
* Always throws a CanonicalizationException because this is inclusive c14n.
*
* @param xpathNodeSet
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException always
*/
@Override
public void engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces, OutputStream writer)
throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
* Always throws a CanonicalizationException because this is inclusive c14n.
*
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces, OutputStream writer)
throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
* Always throws a CanonicalizationException because this is inclusive c14n.
*
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(
Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer)
throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
* Output the Attr[]s for the given element.
* <br>
* The code of this method is a copy of
* {@link #outputAttributes(Element, NameSpaceSymbTable, Map, OutputStream)},
* whereas it takes into account that subtree-c14n is -- well -- subtree-based.
* So if the element in question isRoot of c14n, it's parent is not in the
* node set, as well as all other ancestors.
*
* @param element
* @param ns
* @param cache
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException, DOMException, IOException
*/
@Override
protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException {
if (!element.hasAttributes() && !firstCall) {
return;
}
// result will contain the attrs which have to be output
SortedSet<Attr> result = new TreeSet<>(COMPARE);
if (element.hasAttributes()) {
NamedNodeMap attrs = element.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
String NUri = attribute.getNamespaceURI();
String NName = attribute.getLocalName();
String NValue = attribute.getValue();
if (!XMLNS_URI.equals(NUri)) {
//It's not a namespace attr node. Add to the result and continue.
result.add(attribute);
} else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
//The default mapping for xml must not be output.
Node n = ns.addMappingAndRender(NName, NValue, attribute);
if (n != null) {
//Render the ns definition
result.add((Attr)n);
if (C14nHelper.namespaceIsRelative(attribute)) {
Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() };
throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs
);
}
}
}
}
}
if (firstCall) {
//It is the first node of the subtree
//Obtain all the namespaces defined in the parents, and added to the output.
ns.getUnrenderedNodes(result);
//output the attributes in the xml namespace.
xmlattrStack.getXmlnsAttr(result);
firstCall = false;
}
//we output all Attrs which are available
for (Attr attr : result) {
outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
}
}
/**
* Output the Attr[]s for the given element.
* <br>
* IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
* been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
* org.w3c.dom.Document)}.
*
* @param element
* @param ns
* @param cache
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException, DOMException, IOException
*/
@Override
protected void outputAttributes(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException {
// result will contain the attrs which have to be output
xmlattrStack.push(ns.getLevel());
boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
SortedSet<Attr> result = new TreeSet<>(COMPARE);
if (element.hasAttributes()) {
NamedNodeMap attrs = element.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
String NUri = attribute.getNamespaceURI();
String NName = attribute.getLocalName();
String NValue = attribute.getValue();
if (!XMLNS_URI.equals(NUri)) {
//A non namespace definition node.
if (XML_LANG_URI.equals(NUri)) {
if (c14n11 && "id".equals(NName)) {
if (isRealVisible) {
// treat xml:id like any other attribute
// (emit it, but don't inherit it)
result.add(attribute);
}
} else {
xmlattrStack.addXmlnsAttr(attribute);
}
} else if (isRealVisible) {
//The node is visible add the attribute to the list of output attributes.
result.add(attribute);
}
} else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
/* except omit namespace node with local name xml, which defines
* the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace.
*/
//add the prefix binding to the ns symb table.
if (isVisible(attribute)) {
if (isRealVisible || !ns.removeMappingIfRender(NName)) {
//The xpath select this node output it if needed.
Node n = ns.addMappingAndRender(NName, NValue, attribute);
if (n != null) {
result.add((Attr)n);
if (C14nHelper.namespaceIsRelative(attribute)) {
Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() };
throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs
);
}
}
}
} else {
if (isRealVisible && !XMLNS.equals(NName)) {
ns.removeMapping(NName);
} else {
ns.addMapping(NName, NValue, attribute);
}
}
}
}
}
if (isRealVisible) {
//The element is visible, handle the xmlns definition
Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
Node n = null;
if (xmlns == null) {
//No xmlns def just get the already defined.
n = ns.getMapping(XMLNS);
} else if (!isVisible(xmlns)) {
//There is a definition but the xmlns is not selected by the xpath.
//then xmlns=""
n = ns.addMappingAndRender(
XMLNS, "", getNullNode(xmlns.getOwnerDocument()));
}
//output the xmlns def if needed.
if (n != null) {
result.add((Attr)n);
}
//Float all xml:* attributes of the unselected parent elements to this one.
xmlattrStack.getXmlnsAttr(result);
ns.getUnrenderedNodes(result);
}
//we output all Attrs which are available
for (Attr attr : result) {
outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
}
}
@Override
protected void circumventBugIfNeeded(XMLSignatureInput input)
throws XMLParserException, IOException {
if (!input.isNeedsToBeExpanded()) {
return;
}
Document doc = null;
if (input.getSubNode() != null) {
doc = XMLUtils.getOwnerDocument(input.getSubNode());
} else {
doc = XMLUtils.getOwnerDocument(input.getNodeSet());
}
XMLUtils.circumventBug2650(doc);
}
@Override
protected void handleParent(Element e, NameSpaceSymbTable ns) {
if (!e.hasAttributes() && e.getNamespaceURI() == null) {
return;
}
xmlattrStack.push(-1);
NamedNodeMap attrs = e.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
String NName = attribute.getLocalName();
String NValue = attribute.getNodeValue();
if (XMLNS_URI.equals(attribute.getNamespaceURI())) {
if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
ns.addMapping(NName, NValue, attribute);
}
} else if (XML_LANG_URI.equals(attribute.getNamespaceURI())
&& (!c14n11 || !"id".equals(NName))) {
xmlattrStack.addXmlnsAttr(attribute);
}
}
if (e.getNamespaceURI() != null) {
String NName = e.getPrefix();
String NValue = e.getNamespaceURI();
String Name;
if (NName == null || NName.isEmpty()) {
NName = "xmlns";
Name = "xmlns";
} else {
Name = "xmlns:" + NName;
}
Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
n.setValue(NValue);
ns.addMapping(NName, NValue, n);
}
}
}

View file

@ -0,0 +1,357 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* Implements &quot; <A
* HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
* Canonicalization, Version 1.0 </A>&quot; <p></p>
* Credits: During restructuring of the Canonicalizer framework, Ren??
* Kollmorgen from Software AG submitted an implementation of ExclC14n which
* fitted into the old architecture and which based heavily on my old (and slow)
* implementation of "Canonical XML". A big "thank you" to Ren?? for this.
* <p></p>
* <i>THIS </i> implementation is a complete rewrite of the algorithm.
*
* @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">
* Exclusive XML Canonicalization, Version 1.0</a>
*/
public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
/**
* This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
* the inclusive namespaces.
*/
private SortedSet<String> inclusiveNSSet = Collections.emptySortedSet();
private boolean propagateDefaultNamespace = false;
/**
* Constructor Canonicalizer20010315Excl
*
* @param includeComments
*/
public Canonicalizer20010315Excl(boolean includeComments) {
super(includeComments);
}
/**
* Method engineCanonicalizeSubTree
* {@inheritDoc}
* @param rootNode
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(Node rootNode, OutputStream writer)
throws CanonicalizationException {
engineCanonicalizeSubTree(rootNode, "", null, writer);
}
/**
* Method engineCanonicalizeSubTree
* {@inheritDoc}
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(
Node rootNode, String inclusiveNamespaces, OutputStream writer
) throws CanonicalizationException {
engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null, writer);
}
/**
* Method engineCanonicalizeSubTree
* {@inheritDoc}
* @param rootNode
* @param inclusiveNamespaces
* @param propagateDefaultNamespace If true the default namespace will be propagated to the c14n-ized root element
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(
Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer
) throws CanonicalizationException {
this.propagateDefaultNamespace = propagateDefaultNamespace;
engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null, writer);
}
/**
* Method engineCanonicalizeSubTree
* @param rootNode
* @param inclusiveNamespaces
* @param excl A element to exclude from the c14n process.
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
public void engineCanonicalizeSubTree(
Node rootNode, String inclusiveNamespaces, Node excl, OutputStream writer
) throws CanonicalizationException{
inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
super.engineCanonicalizeSubTree(rootNode, excl, writer);
}
/**
*
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @param secureValidation Whether secure validation is enabled
* @throws CanonicalizationException
*/
public void engineCanonicalize(
XMLSignatureInput rootNode, String inclusiveNamespaces, OutputStream writer, boolean secureValidation
) throws CanonicalizationException {
inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
super.engineCanonicalize(rootNode, writer, secureValidation);
}
/**
* Method engineCanonicalizeXPathNodeSet
* {@inheritDoc}
* @param xpathNodeSet
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeXPathNodeSet(
Set<Node> xpathNodeSet, String inclusiveNamespaces, OutputStream writer
) throws CanonicalizationException {
inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
super.engineCanonicalizeXPathNodeSet(xpathNodeSet, writer);
}
@Override
protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException {
// result will contain the attrs which have to be output
SortedSet<Attr> result = new TreeSet<>(COMPARE);
// The prefix visibly utilized (in the attribute or in the name) in
// the element
SortedSet<String> visiblyUtilized = new TreeSet<>();
if (!inclusiveNSSet.isEmpty()) {
visiblyUtilized.addAll(inclusiveNSSet);
}
if (element.hasAttributes()) {
NamedNodeMap attrs = element.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
String NName = attribute.getLocalName();
String NNodeValue = attribute.getNodeValue();
if (!XMLNS_URI.equals(attribute.getNamespaceURI())) {
// Not a namespace definition.
// The Element is output element, add the prefix (if used) to
// visiblyUtilized
String prefix = attribute.getPrefix();
if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) {
visiblyUtilized.add(prefix);
}
// Add to the result.
result.add(attribute);
} else if (!(XML.equals(NName) && XML_LANG_URI.equals(NNodeValue))
&& ns.addMapping(NName, NNodeValue, attribute)
&& C14nHelper.namespaceIsRelative(NNodeValue)) {
// The default mapping for xml must not be output.
// New definition check if it is relative.
Object[] exArgs = {element.getTagName(), NName, attribute.getNodeValue()};
throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs
);
}
}
}
if (propagateDefaultNamespace && ns.getLevel() == 1 &&
inclusiveNSSet.contains(XMLNS) &&
ns.getMappingWithoutRendered(XMLNS) == null) {
ns.removeMapping(XMLNS);
ns.addMapping(
XMLNS, "", getNullNode(element.getOwnerDocument()));
}
String prefix = null;
if (element.getNamespaceURI() != null
&& !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
prefix = element.getPrefix();
} else {
prefix = XMLNS;
}
visiblyUtilized.add(prefix);
for (String s : visiblyUtilized) {
Attr key = ns.getMapping(s);
if (key != null) {
result.add(key);
}
}
//we output all Attrs which are available
for (Attr attr : result) {
outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
}
}
@Override
protected void outputAttributes(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException {
// result will contain the attrs which have to be output
SortedSet<Attr> result = new TreeSet<>(COMPARE);
// The prefix visibly utilized (in the attribute or in the name) in
// the element
Set<String> visiblyUtilized = null;
// It's the output selected.
boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1;
if (isOutputElement) {
visiblyUtilized = new TreeSet<>();
if (!inclusiveNSSet.isEmpty()) {
visiblyUtilized.addAll(inclusiveNSSet);
}
}
if (element.hasAttributes()) {
NamedNodeMap attrs = element.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
String NName = attribute.getLocalName();
String NNodeValue = attribute.getNodeValue();
if (!XMLNS_URI.equals(attribute.getNamespaceURI())) {
if (isVisible(attribute) && isOutputElement) {
// The Element is output element, add the prefix (if used)
// to visibyUtilized
String prefix = attribute.getPrefix();
if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) {
visiblyUtilized.add(prefix);
}
// Add to the result.
result.add(attribute);
}
} else if (isOutputElement && !isVisible(attribute) && !XMLNS.equals(NName)) {
ns.removeMappingIfNotRender(NName);
} else {
if (!isOutputElement && isVisible(attribute)
&& inclusiveNSSet.contains(NName)
&& !ns.removeMappingIfRender(NName)) {
Node n = ns.addMappingAndRender(NName, NNodeValue, attribute);
if (n != null) {
result.add((Attr)n);
if (C14nHelper.namespaceIsRelative(attribute)) {
Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() };
throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs
);
}
}
}
if (ns.addMapping(NName, NNodeValue, attribute)
&& C14nHelper.namespaceIsRelative(NNodeValue)) {
// New definition check if it is relative
Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() };
throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs
);
}
}
}
}
if (isOutputElement) {
// The element is visible, handle the xmlns definition
Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
if (xmlns != null && !isVisible(xmlns)) {
// There is a definition but the xmlns is not selected by the
// xpath. then xmlns=""
ns.addMapping(XMLNS, "", getNullNode(xmlns.getOwnerDocument()));
}
String prefix = null;
if (element.getNamespaceURI() != null
&& !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
prefix = element.getPrefix();
} else {
prefix = XMLNS;
}
visiblyUtilized.add(prefix);
for (String s : visiblyUtilized) {
Attr key = ns.getMapping(s);
if (key != null) {
result.add(key);
}
}
}
//we output all Attrs which are available
for (Attr attr : result) {
outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
}
}
@Override
protected void circumventBugIfNeeded(XMLSignatureInput input)
throws XMLParserException, IOException {
if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty()) {
return;
}
Document doc = null;
if (input.getSubNode() != null) {
doc = XMLUtils.getOwnerDocument(input.getSubNode());
} else {
doc = XMLUtils.getOwnerDocument(input.getNodeSet());
}
XMLUtils.circumventBug2650(doc);
}
}

View file

@ -0,0 +1,42 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl {
/**
*
*/
public Canonicalizer20010315ExclOmitComments() {
super(false);
}
/** {@inheritDoc} */
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
}
}

View file

@ -0,0 +1,46 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
* Class Canonicalizer20010315ExclWithComments
*/
public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl {
/**
* Constructor Canonicalizer20010315ExclWithComments
*
*/
public Canonicalizer20010315ExclWithComments() {
super(true);
}
/** {@inheritDoc} */
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
}
}

View file

@ -0,0 +1,45 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
*/
public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 {
/**
* Constructor Canonicalizer20010315WithXPathOmitComments
*
*/
public Canonicalizer20010315OmitComments() {
super(false);
}
/** {@inheritDoc} */
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
}
}

View file

@ -0,0 +1,44 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
*/
public class Canonicalizer20010315WithComments extends Canonicalizer20010315 {
/**
* Constructor Canonicalizer20010315WithXPathWithComments
*/
public Canonicalizer20010315WithComments() {
super(true);
}
/** {@inheritDoc} */
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
}
}

View file

@ -0,0 +1,835 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizerSpi;
import com.sun.org.apache.xml.internal.security.c14n.helper.AttrCompare;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.signature.NodeFilter;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
/**
* Abstract base class for canonicalization algorithms.
* Please note that these implementations are NOT thread safe - please see the following JIRA for more information:
* https://issues.apache.org/jira/browse/SANTUARIO-463
*/
public abstract class CanonicalizerBase extends CanonicalizerSpi {
public static final String XML = "xml";
public static final String XMLNS = "xmlns";
public static final String XMLNS_URI = Constants.NamespaceSpecNS;
public static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
protected static final AttrCompare COMPARE = new AttrCompare(); // thread-safe
protected static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
protected static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
protected static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
// Make sure you clone the following mutable arrays before passing to
// potentially untrusted objects such as OutputStreams.
private static final byte[] END_PI = {'?','>'};
private static final byte[] BEGIN_PI = {'<','?'};
private static final byte[] END_COMM = {'-','-','>'};
private static final byte[] BEGIN_COMM = {'<','!','-','-'};
private static final byte[] XA = {'&','#','x','A',';'};
private static final byte[] X9 = {'&','#','x','9',';'};
private static final byte[] QUOT = {'&','q','u','o','t',';'};
private static final byte[] XD = {'&','#','x','D',';'};
private static final byte[] GT = {'&','g','t',';'};
private static final byte[] LT = {'&','l','t',';'};
private static final byte[] END_TAG = {'<','/'};
private static final byte[] AMP = {'&','a','m','p',';'};
private static final byte[] EQUALS_STR = {'=','\"'};
private boolean includeComments;
private List<NodeFilter> nodeFilter;
private Set<Node> xpathNodeSet;
/**
* The null xmlns definition.
*/
private Attr nullNode;
/**
* Constructor CanonicalizerBase
*
* @param includeComments
*/
protected CanonicalizerBase(boolean includeComments) {
this.includeComments = includeComments;
}
/**
* Method engineCanonicalizeSubTree
* {@inheritDoc}
* @param rootNode
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(Node rootNode, OutputStream writer)
throws CanonicalizationException {
engineCanonicalizeSubTree(rootNode, (Node)null, writer);
}
/**
* Method engineCanonicalizeXPathNodeSet
* {@inheritDoc}
* @param xpathNodeSet
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, OutputStream writer)
throws CanonicalizationException {
this.xpathNodeSet = xpathNodeSet;
engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet), writer);
}
/**
* Canonicalizes a Subtree node.
* @param input the root of the subtree to canicalize
* @param writer OutputStream to write the canonicalization result
* @param secureValidation Whether secure validation is enabled
*
* @throws CanonicalizationException
*/
public void engineCanonicalize(XMLSignatureInput input, OutputStream writer, boolean secureValidation) throws CanonicalizationException {
try {
if (input.isExcludeComments()) {
includeComments = false;
}
if (input.isOctetStream()) {
engineCanonicalize(input.getBytes(), writer, secureValidation);
} else if (input.isElement()) {
engineCanonicalizeSubTree(input.getSubNode(), input.getExcludeNode(), writer);
} else if (input.isNodeSet()) {
nodeFilter = input.getNodeFilters();
circumventBugIfNeeded(input);
if (input.getSubNode() != null) {
engineCanonicalizeXPathNodeSetInternal(input.getSubNode(), writer);
} else {
engineCanonicalizeXPathNodeSet(input.getNodeSet(), writer);
}
}
} catch (XMLParserException | IOException ex) {
throw new CanonicalizationException(ex);
}
}
/**
* Canonicalizes a Subtree node.
*
* @param rootNode
* the root of the subtree to canonicalize
* @param excludeNode
* a node to be excluded from the canonicalize operation
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
protected void engineCanonicalizeSubTree(Node rootNode, Node excludeNode, OutputStream writer)
throws CanonicalizationException {
try {
NameSpaceSymbTable ns = new NameSpaceSymbTable();
int nodeLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
if (rootNode != null && Node.ELEMENT_NODE == rootNode.getNodeType()) {
//Fills the nssymbtable with the definitions of the parent of the root subnode
getParentNameSpaces((Element)rootNode, ns);
nodeLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
}
this.canonicalizeSubTree(rootNode, ns, rootNode, nodeLevel, excludeNode, writer);
writer.flush();
} catch (UnsupportedEncodingException ex) {
throw new CanonicalizationException(ex);
} catch (IOException ex) {
throw new CanonicalizationException(ex);
}
}
/**
* Method canonicalizeSubTree, this function is a recursive one.
*
* @param currentNode
* @param ns
* @param endnode
* @param documentLevel
* @param excludeNode
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
* @throws IOException
*/
private void canonicalizeSubTree(
Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel,
Node excludeNode, OutputStream writer
) throws CanonicalizationException, IOException {
if (currentNode == null || isVisibleInt(currentNode) == -1) {
return;
}
Node sibling = null;
Node parentNode = null;
Map<String, byte[]> cache = new HashMap<>();
do { //NOPMD
switch (currentNode.getNodeType()) {
case Node.ENTITY_NODE :
case Node.NOTATION_NODE :
case Node.ATTRIBUTE_NODE :
// illegal node type during traversal
throw new CanonicalizationException("empty",
new Object[]{"illegal node type during traversal"});
case Node.DOCUMENT_FRAGMENT_NODE :
case Node.DOCUMENT_NODE :
ns.outputNodePush();
sibling = currentNode.getFirstChild();
break;
case Node.COMMENT_NODE :
if (includeComments) {
outputCommentToWriter((Comment) currentNode, writer, documentLevel);
}
break;
case Node.PROCESSING_INSTRUCTION_NODE :
outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
break;
case Node.TEXT_NODE :
case Node.CDATA_SECTION_NODE :
outputTextToWriter(currentNode.getNodeValue(), writer);
break;
case Node.ELEMENT_NODE :
documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
if (currentNode == excludeNode) {
break;
}
Element currentElement = (Element)currentNode;
//Add a level to the nssymbtable. So latter can be pop-back.
ns.outputNodePush();
writer.write('<');
String name = currentElement.getTagName();
UtfHelpper.writeByte(name, writer, cache);
outputAttributesSubtree(currentElement, ns, cache, writer);
writer.write('>');
sibling = currentNode.getFirstChild();
if (sibling == null) {
writer.write(END_TAG.clone());
UtfHelpper.writeStringToUtf8(name, writer);
writer.write('>');
//We finished with this level, pop to the previous definitions.
ns.outputNodePop();
if (parentNode != null) {
sibling = currentNode.getNextSibling();
}
} else {
parentNode = currentElement;
}
break;
case Node.DOCUMENT_TYPE_NODE :
default :
break;
}
while (sibling == null && parentNode != null) {
writer.write(END_TAG.clone());
UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache);
writer.write('>');
//We finished with this level, pop to the previous definitions.
ns.outputNodePop();
if (parentNode == endnode) {
return;
}
sibling = parentNode.getNextSibling();
parentNode = parentNode.getParentNode();
if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) {
documentLevel = NODE_AFTER_DOCUMENT_ELEMENT;
parentNode = null;
}
}
if (sibling == null) {
return;
}
currentNode = sibling;
sibling = currentNode.getNextSibling();
} while(true);
}
private void engineCanonicalizeXPathNodeSetInternal(Node doc, OutputStream writer)
throws CanonicalizationException {
try {
this.canonicalizeXPathNodeSet(doc, doc, writer);
writer.flush();
} catch (IOException ex) {
throw new CanonicalizationException(ex);
}
}
/**
* Canonicalizes all the nodes included in the currentNode and contained in the
* xpathNodeSet field.
*
* @param currentNode
* @param endnode
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
* @throws IOException
*/
private void canonicalizeXPathNodeSet(Node currentNode, Node endnode, OutputStream writer)
throws CanonicalizationException, IOException {
if (isVisibleInt(currentNode) == -1) {
return;
}
boolean currentNodeIsVisible = false;
NameSpaceSymbTable ns = new NameSpaceSymbTable();
if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
getParentNameSpaces((Element)currentNode, ns);
}
if (currentNode == null) {
return;
}
Node sibling = null;
Node parentNode = null;
int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
Map<String, byte[]> cache = new HashMap<>();
do { //NOPMD
switch (currentNode.getNodeType()) {
case Node.ENTITY_NODE :
case Node.NOTATION_NODE :
case Node.ATTRIBUTE_NODE :
// illegal node type during traversal
throw new CanonicalizationException("empty",
new Object[]{"illegal node type during traversal"});
case Node.DOCUMENT_FRAGMENT_NODE :
case Node.DOCUMENT_NODE :
ns.outputNodePush();
sibling = currentNode.getFirstChild();
break;
case Node.COMMENT_NODE :
if (includeComments && isVisibleDO(currentNode, ns.getLevel()) == 1) {
outputCommentToWriter((Comment) currentNode, writer, documentLevel);
}
break;
case Node.PROCESSING_INSTRUCTION_NODE :
if (isVisible(currentNode)) {
outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
}
break;
case Node.TEXT_NODE :
case Node.CDATA_SECTION_NODE :
if (isVisible(currentNode)) {
outputTextToWriter(currentNode.getNodeValue(), writer);
for (Node nextSibling = currentNode.getNextSibling();
nextSibling != null && (nextSibling.getNodeType() == Node.TEXT_NODE
|| nextSibling.getNodeType() == Node.CDATA_SECTION_NODE);
nextSibling = nextSibling.getNextSibling()) {
outputTextToWriter(nextSibling.getNodeValue(), writer);
currentNode = nextSibling;
sibling = currentNode.getNextSibling();
}
}
break;
case Node.ELEMENT_NODE :
documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
Element currentElement = (Element) currentNode;
//Add a level to the nssymbtable. So latter can be pop-back.
String name = null;
int i = isVisibleDO(currentNode, ns.getLevel());
if (i == -1) {
sibling = currentNode.getNextSibling();
break;
}
currentNodeIsVisible = i == 1;
if (currentNodeIsVisible) {
ns.outputNodePush();
writer.write('<');
name = currentElement.getTagName();
UtfHelpper.writeByte(name, writer, cache);
} else {
ns.push();
}
outputAttributes(currentElement, ns, cache, writer);
if (currentNodeIsVisible) {
writer.write('>');
}
sibling = currentNode.getFirstChild();
if (sibling == null) {
if (currentNodeIsVisible) {
writer.write(END_TAG.clone());
UtfHelpper.writeByte(name, writer, cache);
writer.write('>');
//We finished with this level, pop to the previous definitions.
ns.outputNodePop();
} else {
ns.pop();
}
if (parentNode != null) {
sibling = currentNode.getNextSibling();
}
} else {
parentNode = currentElement;
}
break;
case Node.DOCUMENT_TYPE_NODE :
default :
break;
}
while (sibling == null && parentNode != null) {
if (isVisible(parentNode)) {
writer.write(END_TAG.clone());
UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache);
writer.write('>');
//We finished with this level, pop to the previous definitions.
ns.outputNodePop();
} else {
ns.pop();
}
if (parentNode == endnode) {
return;
}
sibling = parentNode.getNextSibling();
parentNode = parentNode.getParentNode();
if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) {
parentNode = null;
documentLevel = NODE_AFTER_DOCUMENT_ELEMENT;
}
}
if (sibling == null) {
return;
}
currentNode = sibling;
sibling = currentNode.getNextSibling();
} while(true);
}
protected int isVisibleDO(Node currentNode, int level) throws CanonicalizationException {
if (nodeFilter != null) {
for (NodeFilter filter : nodeFilter) {
try {
int i = filter.isNodeIncludeDO(currentNode, level);
if (i != 1) {
return i;
}
} catch (Exception e) {
throw new CanonicalizationException(e);
}
}
}
if (this.xpathNodeSet != null && !this.xpathNodeSet.contains(currentNode)) {
return 0;
}
return 1;
}
protected int isVisibleInt(Node currentNode) throws CanonicalizationException {
if (nodeFilter != null) {
for (NodeFilter filter : nodeFilter) {
try {
int i = filter.isNodeInclude(currentNode);
if (i != 1) {
return i;
}
} catch (Exception e) {
throw new CanonicalizationException(e);
}
}
}
if (this.xpathNodeSet != null && !this.xpathNodeSet.contains(currentNode)) {
return 0;
}
return 1;
}
protected boolean isVisible(Node currentNode) throws CanonicalizationException {
if (nodeFilter != null) {
for (NodeFilter filter : nodeFilter) {
try {
if (filter.isNodeInclude(currentNode) != 1) {
return false;
}
} catch (Exception e) {
throw new CanonicalizationException(e);
}
}
}
return this.xpathNodeSet == null || this.xpathNodeSet.contains(currentNode);
}
protected void handleParent(Element e, NameSpaceSymbTable ns) {
if (!e.hasAttributes() && e.getNamespaceURI() == null) {
return;
}
NamedNodeMap attrs = e.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
String NName = attribute.getLocalName();
String NValue = attribute.getNodeValue();
if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())
&& (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue))) {
ns.addMapping(NName, NValue, attribute);
}
}
if (e.getNamespaceURI() != null) {
String NName = e.getPrefix();
String NValue = e.getNamespaceURI();
String Name;
if (NName == null || NName.isEmpty()) {
NName = XMLNS;
Name = XMLNS;
} else {
Name = XMLNS + ":" + NName;
}
Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
n.setValue(NValue);
ns.addMapping(NName, NValue, n);
}
}
/**
* Adds to ns the definitions from the parent elements of el
* @param el
* @param ns
*/
private void getParentNameSpaces(Element el, NameSpaceSymbTable ns) {
Node n1 = el.getParentNode();
if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) {
return;
}
//Obtain all the parents of the element
List<Element> parents = new ArrayList<>();
Node parent = n1;
while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
parents.add((Element)parent);
parent = parent.getParentNode();
}
//Visit them in reverse order.
ListIterator<Element> it = parents.listIterator(parents.size());
while (it.hasPrevious()) {
Element ele = it.previous();
handleParent(ele, ns);
}
parents.clear();
Attr nsprefix = ns.getMappingWithoutRendered(XMLNS);
if (nsprefix != null && nsprefix.getValue().length() == 0) {
ns.addMappingAndRender(
XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
}
}
/**
* Output the attributes for this node in XPathNodeSet c14n.
*
* @param element
* @param ns
* @param cache
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException, DOMException, IOException
*/
abstract void outputAttributes(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException;
/**
* Output the attributes for this node in a Subtree c14n.
*
* @param element
* @param ns
* @param cache
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException, DOMException, IOException
*/
abstract void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException;
abstract void circumventBugIfNeeded(XMLSignatureInput input)
throws XMLParserException, IOException;
/**
* Outputs an Attribute to the internal Writer.
*
* The string value of the node is modified by replacing
* <UL>
* <LI>all ampersands with {@code &amp;amp;}</LI>
* <LI>all open angle brackets with {@code &amp;lt;}</LI>
* <LI>all quotation mark characters with {@code &amp;quot;}</LI>
* <LI>and the whitespace characters {@code #x9}, #xA, and #xD, with character
* references. The character references are written in uppercase
* hexadecimal with no leading zeroes (for example, {@code #xD} is represented
* by the character reference {@code &amp;#xD;})</LI>
* </UL>
*
* @param name
* @param value
* @param writer
* @throws IOException
*/
protected static final void outputAttrToWriter(
final String name, final String value,
final OutputStream writer, final Map<String, byte[]> cache
) throws IOException {
writer.write(' ');
UtfHelpper.writeByte(name, writer, cache);
writer.write(EQUALS_STR.clone());
byte[] toWrite;
final int length = value.length();
int i = 0;
while (i < length) {
int c = value.codePointAt(i);
i += Character.charCount(c);
switch (c) {
case '&' :
toWrite = AMP.clone();
break;
case '<' :
toWrite = LT.clone();
break;
case '"' :
toWrite = QUOT.clone();
break;
case 0x09 : // '\t'
toWrite = X9.clone();
break;
case 0x0A : // '\n'
toWrite = XA.clone();
break;
case 0x0D : // '\r'
toWrite = XD.clone();
break;
default :
if (c < 0x80) {
writer.write(c);
} else {
UtfHelpper.writeCodePointToUtf8(c, writer);
}
continue;
}
writer.write(toWrite);
}
writer.write('\"');
}
/**
* Outputs a PI to the internal Writer.
*
* @param currentPI
* @param writer where to write the things
* @throws IOException
*/
protected void outputPItoWriter(
ProcessingInstruction currentPI, OutputStream writer, int position
) throws IOException {
if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
writer.write('\n');
}
writer.write(BEGIN_PI.clone());
final String target = currentPI.getTarget();
int length = target.length();
for (int i = 0; i < length; ) {
int c = target.codePointAt(i);
i += Character.charCount(c);
if (c == 0x0D) {
writer.write(XD.clone());
} else {
if (c < 0x80) {
writer.write(c);
} else {
UtfHelpper.writeCodePointToUtf8(c, writer);
}
}
}
final String data = currentPI.getData();
length = data.length();
if (length > 0) {
writer.write(' ');
for (int i = 0; i < length; ) {
int c = data.codePointAt(i);
i += Character.charCount(c);
if (c == 0x0D) {
writer.write(XD.clone());
} else {
UtfHelpper.writeCodePointToUtf8(c, writer);
}
}
}
writer.write(END_PI.clone());
if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
writer.write('\n');
}
}
/**
* Method outputCommentToWriter
*
* @param currentComment
* @param writer writer where to write the things
* @throws IOException
*/
protected void outputCommentToWriter(
Comment currentComment, OutputStream writer, int position
) throws IOException {
if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
writer.write('\n');
}
writer.write(BEGIN_COMM.clone());
final String data = currentComment.getData();
final int length = data.length();
for (int i = 0; i < length; ) {
int c = data.codePointAt(i);
i += Character.charCount(c);
if (c == 0x0D) {
writer.write(XD.clone());
} else {
if (c < 0x80) {
writer.write(c);
} else {
UtfHelpper.writeCodePointToUtf8(c, writer);
}
}
}
writer.write(END_COMM.clone());
if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
writer.write('\n');
}
}
/**
* Outputs a Text of CDATA section to the internal Writer.
*
* @param text
* @param writer writer where to write the things
* @throws IOException
*/
private static final void outputTextToWriter(
final String text, final OutputStream writer
) throws IOException {
final int length = text.length();
byte[] toWrite;
for (int i = 0; i < length; ) {
int c = text.codePointAt(i);
i += Character.charCount(c);
switch (c) {
case '&' :
toWrite = AMP.clone();
break;
case '<' :
toWrite = LT.clone();
break;
case '>' :
toWrite = GT.clone();
break;
case 0xD :
toWrite = XD.clone();
break;
default :
if (c < 0x80) {
writer.write(c);
} else {
UtfHelpper.writeCodePointToUtf8(c, writer);
}
continue;
}
writer.write(toWrite);
}
}
// The null xmlns definition.
protected Attr getNullNode(Document ownerDocument) {
if (nullNode == null) {
try {
nullNode = ownerDocument.createAttributeNS(
Constants.NamespaceSpecNS, XMLNS);
nullNode.setValue("");
} catch (Exception e) {
throw new RuntimeException("Unable to create nullNode: " + e);
}
}
return nullNode;
}
}

View file

@ -0,0 +1,190 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
/**
* Serializes the physical representation of the subtree. All the attributes
* present in the subtree are emitted. The attributes are sorted within an element,
* with the namespace declarations appearing before the regular attributes.
* This algorithm is not a true canonicalization since equivalent subtrees
* may produce different output. It is therefore unsuitable for digital signatures.
* This same property makes it ideal for XML Encryption Syntax and Processing,
* because the decrypted XML content will share the same physical representation
* as the original XML content that was encrypted.
*/
public class CanonicalizerPhysical extends CanonicalizerBase {
/**
* Constructor Canonicalizer20010315
*/
public CanonicalizerPhysical() {
super(true);
}
/**
* Always throws a CanonicalizationException.
*
* @param xpathNodeSet
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException always
*/
@Override
public void engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces, OutputStream writer)
throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
* Always throws a CanonicalizationException.
*
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces, OutputStream writer)
throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
* Always throws a CanonicalizationException.
*
* @param rootNode
* @param inclusiveNamespaces
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException
*/
@Override
public void engineCanonicalizeSubTree(
Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer)
throws CanonicalizationException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
* Output the Attr[]s for the given element.
* <br>
* The code of this method is a copy of
* {@link #outputAttributes(Element, NameSpaceSymbTable, Map, OutputStream)},
* whereas it takes into account that subtree-c14n is -- well -- subtree-based.
* So if the element in question isRoot of c14n, it's parent is not in the
* node set, as well as all other ancestors.
*
* @param element
* @param ns
* @param cache
* @param writer OutputStream to write the canonicalization result
* @throws CanonicalizationException, DOMException, IOException
*/
@Override
protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException {
if (element.hasAttributes()) {
// result will contain all the attrs declared directly on that element
SortedSet<Attr> result = new TreeSet<>(COMPARE);
NamedNodeMap attrs = element.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr attribute = (Attr) attrs.item(i);
result.add(attribute);
}
//we output all Attrs which are available
for (Attr attr : result) {
outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
}
}
}
@Override
protected void outputAttributes(Element element, NameSpaceSymbTable ns,
Map<String, byte[]> cache, OutputStream writer)
throws CanonicalizationException, DOMException, IOException {
/** $todo$ well, should we throw UnsupportedOperationException ? */
throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
@Override
protected void circumventBugIfNeeded(XMLSignatureInput input)
throws XMLParserException, IOException {
// nothing to do
}
@Override
protected void handleParent(Element e, NameSpaceSymbTable ns) {
// nothing to do
}
/** {@inheritDoc} */
@Override
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N_PHYSICAL;
}
@Override
protected void outputPItoWriter(ProcessingInstruction currentPI,
OutputStream writer, int position) throws IOException {
// Processing Instructions before or after the document element are not treated specially
super.outputPItoWriter(currentPI, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT);
}
@Override
protected void outputCommentToWriter(Comment currentComment,
OutputStream writer, int position) throws IOException {
// Comments before or after the document element are not treated specially
super.outputCommentToWriter(currentComment, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT);
}
}

View file

@ -0,0 +1,410 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
/**
* A stack based Symbol Table.
*<br>For speed reasons all the symbols are introduced in the same map,
* and at the same time in a list so it can be removed when the frame is pop back.
*/
public class NameSpaceSymbTable {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(NameSpaceSymbTable.class);
private static final String XMLNS = "xmlns";
private static final SymbMap initialMap = new SymbMap();
static {
NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS);
ne.lastrendered = "";
initialMap.put(XMLNS, ne);
}
/**The map between prefix-> entry table. */
private SymbMap symb;
/**The stacks for removing the definitions when doing pop.*/
private final List<SymbMap> level = new ArrayList<>();
private boolean cloned = true;
/**
* Default constructor
**/
public NameSpaceSymbTable() {
//Insert the default binding for xmlns.
try {
symb = initialMap.clone();
} catch (CloneNotSupportedException e) {
LOG.error("Error cloning the initial map");
}
}
/**
* Get all the unrendered nodes in the name space.
* For Inclusive rendering
* @param result the list where to fill the unrendered xmlns definitions.
**/
public void getUnrenderedNodes(Collection<Attr> result) {
for (NameSpaceSymbEntry nsEntry : symb.entrySet()) {
//put them rendered?
if (!nsEntry.rendered && nsEntry.n != null) {
nsEntry = nsEntry.clone();
needsClone();
symb.put(nsEntry.prefix, nsEntry);
nsEntry.lastrendered = nsEntry.uri;
nsEntry.rendered = true;
result.add(nsEntry.n);
}
}
}
/**
* Push a frame for visible namespace.
* For Inclusive rendering.
**/
public void outputNodePush() {
push();
}
/**
* Pop a frame for visible namespace.
**/
public void outputNodePop() {
pop();
}
/**
* Push a frame for a node.
* Inclusive or Exclusive.
**/
public void push() {
//Put the number of namespace definitions in the stack.
level.add(null);
cloned = false;
}
/**
* Pop a frame.
* Inclusive or Exclusive.
**/
public void pop() {
int size = level.size() - 1;
Object ob = level.remove(size);
if (ob != null) {
symb = (SymbMap)ob;
if (size == 0) {
cloned = false;
} else {
cloned = level.get(size - 1) != symb;
}
} else {
cloned = false;
}
}
final void needsClone() {
if (!cloned) {
level.set(level.size() - 1, symb);
try {
symb = symb.clone();
} catch (CloneNotSupportedException e) {
LOG.error("Error cloning the symbol map");
}
cloned = true;
}
}
/**
* Gets the attribute node that defines the binding for the prefix.
* @param prefix the prefix to obtain the attribute.
* @return null if there is no need to render the prefix. Otherwise the node of
* definition.
**/
public Attr getMapping(String prefix) {
NameSpaceSymbEntry entry = symb.get(prefix);
if (entry == null) {
//There is no definition for the prefix(a bug?).
return null;
}
if (entry.rendered) {
//No need to render an entry already rendered.
return null;
}
// Mark this entry as render.
entry = entry.clone();
needsClone();
symb.put(prefix, entry);
entry.rendered = true;
entry.lastrendered = entry.uri;
// Return the node for outputting.
return entry.n;
}
/**
* Gets a definition without mark it as render.
* For render in exclusive c14n the namespaces in the include prefixes.
* @param prefix The prefix whose definition is needed.
* @return the attr to render, null if there is no need to render
**/
public Attr getMappingWithoutRendered(String prefix) {
NameSpaceSymbEntry entry = symb.get(prefix);
if (entry == null) {
return null;
}
if (entry.rendered) {
return null;
}
return entry.n;
}
/**
* Adds the mapping for a prefix.
* @param prefix the prefix of definition
* @param uri the Uri of the definition
* @param n the attribute that have the definition
* @return true if there is already defined.
**/
public boolean addMapping(String prefix, String uri, Attr n) {
NameSpaceSymbEntry ob = symb.get(prefix);
if (ob != null && uri.equals(ob.uri)) {
//If we have it previously defined. Don't keep working.
return false;
}
//Creates and entry in the table for this new definition.
NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix);
needsClone();
symb.put(prefix, ne);
if (ob != null) {
//We have a previous definition store it for the pop.
//Check if a previous definition(not the inmidiatly one) has been rendered.
ne.lastrendered = ob.lastrendered;
if (ob.lastrendered != null && ob.lastrendered.equals(uri)) {
//Yes it is. Mark as rendered.
ne.rendered = true;
}
}
return true;
}
/**
* Adds a definition and mark it as render.
* For inclusive c14n.
* @param prefix the prefix of definition
* @param uri the Uri of the definition
* @param n the attribute that have the definition
* @return the attr to render, null if there is no need to render
**/
public Node addMappingAndRender(String prefix, String uri, Attr n) {
NameSpaceSymbEntry ob = symb.get(prefix);
if (ob != null && uri.equals(ob.uri)) {
if (!ob.rendered) {
ob = ob.clone();
needsClone();
symb.put(prefix, ob);
ob.lastrendered = uri;
ob.rendered = true;
return ob.n;
}
return null;
}
NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, true, prefix);
ne.lastrendered = uri;
needsClone();
symb.put(prefix, ne);
if (ob != null && ob.lastrendered != null && ob.lastrendered.equals(uri)) {
ne.rendered = true;
return null;
}
return ne.n;
}
public int getLevel() {
return level.size();
}
public void removeMapping(String prefix) {
NameSpaceSymbEntry ob = symb.get(prefix);
if (ob != null) {
needsClone();
symb.put(prefix, null);
}
}
public void removeMappingIfNotRender(String prefix) {
NameSpaceSymbEntry ob = symb.get(prefix);
if (ob != null && !ob.rendered) {
needsClone();
symb.put(prefix, null);
}
}
public boolean removeMappingIfRender(String prefix) {
NameSpaceSymbEntry ob = symb.get(prefix);
if (ob != null && ob.rendered) {
needsClone();
symb.put(prefix, null);
}
return false;
}
}
/**
* The internal structure of NameSpaceSymbTable.
**/
class NameSpaceSymbEntry implements Cloneable {
final String prefix;
/**The URI that the prefix defines */
final String uri;
/**The attribute to include.*/
final Attr n;
/**The last output in the URI for this prefix (This for speed reason).*/
String lastrendered = null;
/**This prefix-URI has been already render or not.*/
boolean rendered = false;
NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) {
this.uri = name;
this.rendered = rendered;
this.n = n;
this.prefix = prefix;
}
/** {@inheritDoc} */
@Override
public NameSpaceSymbEntry clone() { //NOPMD
try {
return (NameSpaceSymbEntry)super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
class SymbMap implements Cloneable {
int free = 23;
NameSpaceSymbEntry[] entries;
String[] keys;
SymbMap() {
entries = new NameSpaceSymbEntry[free];
keys = new String[free];
}
void put(String key, NameSpaceSymbEntry value) {
int index = index(key);
Object oldKey = keys[index];
keys[index] = key;
entries[index] = value;
if ((oldKey == null || !oldKey.equals(key)) && --free == 0) {
free = entries.length;
int newCapacity = free << 2;
rehash(newCapacity);
}
}
List<NameSpaceSymbEntry> entrySet() {
List<NameSpaceSymbEntry> a = new ArrayList<>();
for (NameSpaceSymbEntry nsEntry : entries) {
if (nsEntry != null && !nsEntry.uri.isEmpty()) {
a.add(nsEntry);
}
}
return a;
}
protected int index(Object obj) {
Object[] set = keys;
int length = set.length;
//abs of index
int index = (obj.hashCode() & 0x7fffffff) % length;
Object cur = set[index];
if (cur == null || cur.equals(obj)) {
return index;
}
length--;
do {
index = index == length ? 0 : ++index;
cur = set[index];
} while (cur != null && !cur.equals(obj));
return index;
}
/**
* rehashes the map to the new capacity.
*
* @param newCapacity an {@code int} value
*/
protected void rehash(int newCapacity) {
int oldCapacity = keys.length;
String[] oldKeys = keys;
NameSpaceSymbEntry oldVals[] = entries;
keys = new String[newCapacity];
entries = new NameSpaceSymbEntry[newCapacity];
for (int i = oldCapacity; i-- > 0;) {
if (oldKeys[i] != null) {
String o = oldKeys[i];
int index = index(o);
keys[index] = o;
entries[index] = oldVals[i];
}
}
}
NameSpaceSymbEntry get(String key) {
return entries[index(key)];
}
@Override
public SymbMap clone() throws CloneNotSupportedException {
SymbMap copy = (SymbMap) super.clone();
copy.entries = new NameSpaceSymbEntry[entries.length];
System.arraycopy(entries, 0, copy.entries, 0, entries.length);
copy.keys = new String[keys.length];
System.arraycopy(keys, 0, copy.keys, 0, keys.length);
return copy;
}
}

View file

@ -0,0 +1,266 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
public final class UtfHelpper {
/**
* Revert to the old behavior (version 2 or before), i.e. surrogate pairs characters becomes
* '??' in output. Set system property com.sun.org.apache.xml.internal.security.c14n.oldUtf8=true if you want
* to verify signatures generated by version 2 or before that contains 32 bit chars in the
* XML document.
*/
@SuppressWarnings("removal")
private static final boolean OLD_UTF8 =
AccessController.doPrivileged((PrivilegedAction<Boolean>)
() -> Boolean.getBoolean("com.sun.org.apache.xml.internal.security.c14n.oldUtf8"));
private UtfHelpper() {
// complete
}
public static void writeByte(
final String str,
final OutputStream out,
Map<String, byte[]> cache
) throws IOException {
byte[] result = cache.get(str);
if (result == null) {
result = getStringInUtf8(str);
cache.put(str, result);
}
out.write(result);
}
public static void writeCodePointToUtf8(final int c, final OutputStream out) throws IOException {
if (!Character.isValidCodePoint(c) || c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
// valid code point: c >= 0x0000 && c <= 0x10FFFF
out.write(0x3f);
return;
}
if (OLD_UTF8 && c >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// version 2 or before output 2 question mark characters for 32 bit chars
out.write(0x3f);
out.write(0x3f);
return;
}
if (c < 0x80) {
// 0x00000000 - 0x0000007F
// 0xxxxxxx
out.write(c);
return;
}
byte extraByte = 0;
if (c < 0x800) {
// 0x00000080 - 0x000007FF
// 110xxxxx 10xxxxxx
extraByte = 1;
} else if (c < 0x10000) {
// 0x00000800 - 0x0000FFFF
// 1110xxxx 10xxxxxx 10xxxxxx
extraByte = 2;
} else if (c < 0x200000) {
// 0x00010000 - 0x001FFFFF
// 11110xxx 10xxxxx 10xxxxxx 10xxxxxx
extraByte = 3;
} else if (c < 0x4000000) {
// 0x00200000 - 0x03FFFFFF
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
// already outside valid Character range, just for completeness
extraByte = 4;
} else if (c <= 0x7FFFFFFF) {
// 0x04000000 - 0x7FFFFFFF
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
// already outside valid Character range, just for completeness
extraByte = 5;
} else {
// 0x80000000 - 0xFFFFFFFF
// case not possible as java has no unsigned int
out.write(0x3f);
return;
}
byte write;
int shift = 6 * extraByte;
write = (byte)((0xFE << (6 - extraByte)) | (c >>> shift));
out.write(write);
for (int i = extraByte - 1; i >= 0; i--) {
shift -= 6;
write = (byte)(0x80 | ((c >>> shift) & 0x3F));
out.write(write);
}
}
public static void writeStringToUtf8(
final String str, final OutputStream out
) throws IOException {
final int length = str.length();
int i = 0;
int c;
while (i < length) {
c = str.codePointAt(i);
i += Character.charCount(c);
if (!Character.isValidCodePoint(c) || c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
// valid code point: c >= 0x0000 && c <= 0x10FFFF
out.write(0x3f);
continue;
}
if (OLD_UTF8 && c >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// version 2 or before output 2 question mark characters for 32 bit chars
out.write(0x3f);
out.write(0x3f);
continue;
}
if (c < 0x80) {
out.write(c);
continue;
}
byte extraByte = 0;
if (c < 0x800) {
// 0x00000080 - 0x000007FF
// 110xxxxx 10xxxxxx
extraByte = 1;
} else if (c < 0x10000) {
// 0x00000800 - 0x0000FFFF
// 1110xxxx 10xxxxxx 10xxxxxx
extraByte = 2;
} else if (c < 0x200000) {
// 0x00010000 - 0x001FFFFF
// 11110xxx 10xxxxx 10xxxxxx 10xxxxxx
extraByte = 3;
} else if (c < 0x4000000) {
// 0x00200000 - 0x03FFFFFF
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
// already outside valid Character range, just for completeness
extraByte = 4;
} else if (c <= 0x7FFFFFFF) {
// 0x04000000 - 0x7FFFFFFF
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
// already outside valid Character range, just for completeness
extraByte = 5;
} else {
// 0x80000000 - 0xFFFFFFFF
// case not possible as java has no unsigned int
out.write(0x3f);
continue;
}
byte write;
int shift = 6 * extraByte;
write = (byte)((0xFE << (6 - extraByte)) | (c >>> shift));
out.write(write);
for (int j = extraByte - 1; j >= 0; j--) {
shift -= 6;
write = (byte)(0x80 | ((c >>> shift) & 0x3F));
out.write(write);
}
}
}
public static byte[] getStringInUtf8(final String str) {
final int length = str.length();
boolean expanded = false;
byte[] result = new byte[length];
int i = 0;
int out = 0;
int c;
while (i < length) {
c = str.codePointAt(i);
i += Character.charCount(c);
if (!Character.isValidCodePoint(c) || c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) {
// valid code point: c >= 0x0000 && c <= 0x10FFFF
result[out++] = (byte)0x3f;
continue;
}
if (OLD_UTF8 && c >= Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// version 2 or before output 2 question mark characters for 32 bit chars
result[out++] = (byte)0x3f;
result[out++] = (byte)0x3f;
continue;
}
if (c < 0x80) {
result[out++] = (byte)c;
continue;
}
if (!expanded) {
byte[] newResult = new byte[6*length];
System.arraycopy(result, 0, newResult, 0, out);
result = newResult;
expanded = true;
}
byte extraByte = 0;
if (c < 0x800) {
// 0x00000080 - 0x000007FF
// 110xxxxx 10xxxxxx
extraByte = 1;
} else if (c < 0x10000) {
// 0x00000800 - 0x0000FFFF
// 1110xxxx 10xxxxxx 10xxxxxx
extraByte = 2;
} else if (c < 0x200000) {
// 0x00010000 - 0x001FFFFF
// 11110xxx 10xxxxx 10xxxxxx 10xxxxxx
extraByte = 3;
} else if (c < 0x4000000) {
// 0x00200000 - 0x03FFFFFF
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
// already outside valid Character range, just for completeness
extraByte = 4;
} else if (c <= 0x7FFFFFFF) {
// 0x04000000 - 0x7FFFFFFF
// 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
// already outside valid Character range, just for completeness
extraByte = 5;
} else {
// 0x80000000 - 0xFFFFFFFF
// case not possible as java has no unsigned int
result[out++] = 0x3f;
continue;
}
byte write;
int shift = 6 * extraByte;
write = (byte)((0xFE << (6 - extraByte)) | (c >>> shift));
result[out++] = write;
for (int j = extraByte - 1; j >= 0; j--) {
shift -= 6;
write = (byte)(0x80 | ((c >>> shift) & 0x3F));
result[out++] = write;
}
}
if (expanded) {
byte[] newResult = new byte[out];
System.arraycopy(result, 0, newResult, 0, out);
result = newResult;
}
return result;
}
}

View file

@ -0,0 +1,407 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Attr;
/**
* An XmlAttrStack that is shared between the Canonical XML 1.0 and 1.1 implementations.
*/
class XmlAttrStack {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(XmlAttrStack.class);
private static class XmlsStackElement {
int level;
boolean rendered = false;
final List<Attr> nodes = new ArrayList<>();
}
private int currentLevel = 0;
private int lastlevel = 0;
private XmlsStackElement cur;
private final List<XmlsStackElement> levels = new ArrayList<>();
private final boolean c14n11;
public XmlAttrStack(boolean c14n11) {
this.c14n11 = c14n11;
}
void push(int level) {
currentLevel = level;
if (currentLevel == -1) {
return;
}
cur = null;
while (lastlevel >= currentLevel) {
levels.remove(levels.size() - 1);
int newSize = levels.size();
if (newSize == 0) {
lastlevel = 0;
return;
}
lastlevel = levels.get(newSize - 1).level;
}
}
void addXmlnsAttr(Attr n) {
if (cur == null) {
cur = new XmlsStackElement();
cur.level = currentLevel;
levels.add(cur);
lastlevel = currentLevel;
}
cur.nodes.add(n);
}
void getXmlnsAttr(Collection<Attr> col) {
int size = levels.size() - 1;
if (cur == null) {
cur = new XmlsStackElement();
cur.level = currentLevel;
lastlevel = currentLevel;
levels.add(cur);
}
boolean parentRendered = false;
XmlsStackElement e = null;
if (size == -1) {
parentRendered = true;
} else {
e = levels.get(size);
if (e.rendered && e.level + 1 == currentLevel) {
parentRendered = true;
}
}
if (parentRendered) {
col.addAll(cur.nodes);
cur.rendered = true;
return;
}
Map<String, Attr> loa = new HashMap<>();
if (c14n11) {
List<Attr> baseAttrs = new ArrayList<>();
boolean successiveOmitted = true;
for (; size >= 0; size--) {
e = levels.get(size);
if (e.rendered) {
successiveOmitted = false;
}
Iterator<Attr> it = e.nodes.iterator();
while (it.hasNext() && successiveOmitted) {
Attr n = it.next();
if ("base".equals(n.getLocalName()) && !e.rendered) {
baseAttrs.add(n);
} else if (!loa.containsKey(n.getName())) {
loa.put(n.getName(), n);
}
}
}
if (!baseAttrs.isEmpty()) {
String base = null;
Attr baseAttr = null;
for (Attr n : col) {
if ("base".equals(n.getLocalName())) {
base = n.getValue();
baseAttr = n;
break;
}
}
for (Attr n : baseAttrs) {
if (base == null) {
base = n.getValue();
baseAttr = n;
} else {
try {
base = joinURI(n.getValue(), base);
} catch (URISyntaxException ue) {
LOG.debug(ue.getMessage(), ue);
}
}
}
if (base != null && base.length() != 0) {
baseAttr.setValue(base);
col.add(baseAttr);
}
}
} else {
for (; size >= 0; size--) {
e = levels.get(size);
for (Attr n : e.nodes) {
if (!loa.containsKey(n.getName())) {
loa.put(n.getName(), n);
}
}
}
}
cur.rendered = true;
col.addAll(loa.values());
}
private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
String bscheme = null;
String bauthority = null;
String bpath = "";
String bquery = null;
// pre-parse the baseURI
if (baseURI != null) {
if (baseURI.endsWith("..")) {
baseURI = baseURI + "/";
}
URI base = new URI(baseURI);
bscheme = base.getScheme();
bauthority = base.getAuthority();
bpath = base.getPath();
bquery = base.getQuery();
}
URI r = new URI(relativeURI);
String rscheme = r.getScheme();
String rauthority = r.getAuthority();
String rpath = r.getPath();
String rquery = r.getQuery();
String tscheme, tauthority, tpath, tquery;
if (rscheme != null && rscheme.equals(bscheme)) {
rscheme = null;
}
if (rscheme != null) {
tscheme = rscheme;
tauthority = rauthority;
tpath = removeDotSegments(rpath);
tquery = rquery;
} else {
if (rauthority != null) {
tauthority = rauthority;
tpath = removeDotSegments(rpath);
tquery = rquery;
} else {
if (rpath.length() == 0) {
tpath = bpath;
if (rquery != null) {
tquery = rquery;
} else {
tquery = bquery;
}
} else {
if (rpath.charAt(0) == '/') {
tpath = removeDotSegments(rpath);
} else {
if (bauthority != null && bpath.length() == 0) {
tpath = "/" + rpath;
} else {
int last = bpath.lastIndexOf('/');
if (last == -1) {
tpath = rpath;
} else {
tpath = bpath.substring(0, last+1) + rpath;
}
}
tpath = removeDotSegments(tpath);
}
tquery = rquery;
}
tauthority = bauthority;
}
tscheme = bscheme;
}
return new URI(tscheme, tauthority, tpath, tquery, null).toString();
}
private static String removeDotSegments(String path) {
LOG.debug("STEP OUTPUT BUFFER\t\tINPUT BUFFER");
// 1. The input buffer is initialized with the now-appended path
// components then replace occurrences of "//" in the input buffer
// with "/" until no more occurrences of "//" are in the input buffer.
String input = path;
while (input.indexOf("//") > -1) {
input = input.replaceAll("//", "/");
}
// Initialize the output buffer with the empty string.
StringBuilder output = new StringBuilder();
// If the input buffer starts with a root slash "/" then move this
// character to the output buffer.
if (input.charAt(0) == '/') {
output.append('/');
input = input.substring(1);
}
printStep("1 ", output.toString(), input);
// While the input buffer is not empty, loop as follows
while (input.length() != 0) {
// 2A. If the input buffer begins with a prefix of "./",
// then remove that prefix from the input buffer
// else if the input buffer begins with a prefix of "../", then
// if also the output does not contain the root slash "/" only,
// then move this prefix to the end of the output buffer else
// remove that prefix
if (input.startsWith("./")) {
input = input.substring(2);
printStep("2A", output.toString(), input);
} else if (input.startsWith("../")) {
input = input.substring(3);
if (!"/".equals(output.toString())) {
output.append("../");
}
printStep("2A", output.toString(), input);
// 2B. if the input buffer begins with a prefix of "/./" or "/.",
// where "." is a complete path segment, then replace that prefix
// with "/" in the input buffer; otherwise,
} else if (input.startsWith("/./")) {
input = input.substring(2);
printStep("2B", output.toString(), input);
} else if ("/.".equals(input)) {
// FIXME: what is complete path segment?
input = input.replaceFirst("/.", "/");
printStep("2B", output.toString(), input);
// 2C. if the input buffer begins with a prefix of "/../" or "/..",
// where ".." is a complete path segment, then replace that prefix
// with "/" in the input buffer and if also the output buffer is
// empty, last segment in the output buffer equals "../" or "..",
// where ".." is a complete path segment, then append ".." or "/.."
// for the latter case respectively to the output buffer else
// remove the last segment and its preceding "/" (if any) from the
// output buffer and if hereby the first character in the output
// buffer was removed and it was not the root slash then delete a
// leading slash from the input buffer; otherwise,
} else if (input.startsWith("/../")) {
input = input.substring(3);
if (output.length() == 0) {
output.append('/');
} else if (output.toString().endsWith("../")) {
output.append("..");
} else if (output.toString().endsWith("..")) {
output.append("/..");
} else {
int index = output.lastIndexOf("/");
if (index == -1) {
output = new StringBuilder();
if (input.charAt(0) == '/') {
input = input.substring(1);
}
} else {
output = output.delete(index, output.length());
}
}
printStep("2C", output.toString(), input);
} else if ("/..".equals(input)) {
// FIXME: what is complete path segment?
input = input.replaceFirst("/..", "/");
if (output.length() == 0) {
output.append('/');
} else if (output.toString().endsWith("../")) {
output.append("..");
} else if (output.toString().endsWith("..")) {
output.append("/..");
} else {
int index = output.lastIndexOf("/");
if (index == -1) {
output = new StringBuilder();
if (input.charAt(0) == '/') {
input = input.substring(1);
}
} else {
output = output.delete(index, output.length());
}
}
printStep("2C", output.toString(), input);
// 2D. if the input buffer consists only of ".", then remove
// that from the input buffer else if the input buffer consists
// only of ".." and if the output buffer does not contain only
// the root slash "/", then move the ".." to the output buffer
// else delete it.; otherwise,
} else if (".".equals(input)) {
input = "";
printStep("2D", output.toString(), input);
} else if ("..".equals(input)) {
if (!"/".equals(output.toString())) {
output.append("..");
}
input = "";
printStep("2D", output.toString(), input);
// 2E. move the first path segment (if any) in the input buffer
// to the end of the output buffer, including the initial "/"
// character (if any) and any subsequent characters up to, but not
// including, the next "/" character or the end of the input buffer.
} else {
int end = -1;
int begin = input.indexOf('/');
if (begin == 0) {
end = input.indexOf('/', 1);
} else {
end = begin;
begin = 0;
}
String segment;
if (end == -1) {
segment = input.substring(begin);
input = "";
} else {
segment = input.substring(begin, end);
input = input.substring(end);
}
output.append(segment);
printStep("2E", output.toString(), input);
}
}
// 3. Finally, if the only or last segment of the output buffer is
// "..", where ".." is a complete path segment not followed by a slash
// then append a slash "/". The output buffer is returned as the result
// of remove_dot_segments
if (output.toString().endsWith("..")) {
output.append('/');
printStep("3 ", output.toString(), input);
}
return output.toString();
}
private static void printStep(String step, String output, String input) {
if (LOG.isDebugEnabled()) {
LOG.debug(" " + step + ": " + output);
if (output.length() == 0) {
LOG.debug("\t\t\t\t" + input);
} else {
LOG.debug("\t\t\t" + input);
}
}
}
}

View file

@ -0,0 +1,91 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.exceptions;
public class AlgorithmAlreadyRegisteredException extends XMLSecurityException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor AlgorithmAlreadyRegisteredException
*
*/
public AlgorithmAlreadyRegisteredException() {
super();
}
/**
* Constructor AlgorithmAlreadyRegisteredException
*
* @param msgID
*/
public AlgorithmAlreadyRegisteredException(String msgID) {
super(msgID);
}
/**
* Constructor AlgorithmAlreadyRegisteredException
*
* @param msgID
* @param exArgs
*/
public AlgorithmAlreadyRegisteredException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor AlgorithmAlreadyRegisteredException
*
* @param originalException
* @param msgID
*/
public AlgorithmAlreadyRegisteredException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor AlgorithmAlreadyRegisteredException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public AlgorithmAlreadyRegisteredException(
Exception originalException, String msgID, Object[] exArgs
) {
super(originalException, msgID, exArgs);
}
@Deprecated
public AlgorithmAlreadyRegisteredException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,91 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.exceptions;
/**
* This Exception is thrown if decoding of Base64 data fails.
*
*/
public class Base64DecodingException extends XMLSecurityException {
private static final long serialVersionUID = 1L;
/**
* Constructor Base64DecodingException
*
*/
public Base64DecodingException() {
super();
}
/**
* Constructor Base64DecodingException
*
* @param msgID
*/
public Base64DecodingException(String msgID) {
super(msgID);
}
/**
* Constructor Base64DecodingException
*
* @param msgID
* @param exArgs
*/
public Base64DecodingException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor Base64DecodingException
*
* @param originalException
* @param msgID
*/
public Base64DecodingException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public Base64DecodingException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor Base64DecodingException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public Base64DecodingException(Exception originalException, String msgID, Object[] exArgs) {
super(originalException, msgID, exArgs);
}
@Deprecated
public Base64DecodingException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,203 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.exceptions;
import java.text.MessageFormat;
import com.sun.org.apache.xml.internal.security.utils.I18n;
/**
* The mother of all Exceptions in this bundle. It allows exceptions to have
* their messages translated to the different locales.
*
* The {@code xmlsecurity_en.properties} file contains this line:
* <pre>
* xml.WrongElement = Can't create a {0} from a {1} element
* </pre>
*
* Usage in the Java source is:
* <pre>
* {
* Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
*
* throw new XMLSecurityException("xml.WrongElement", exArgs);
* }
* </pre>
*
* Additionally, if another Exception has been caught, we can supply it, too
* <pre>
* try {
* ...
* } catch (Exception oldEx) {
* Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
*
* throw new XMLSecurityException("xml.WrongElement", exArgs, oldEx);
* }
* </pre>
*
*
*/
public class XMLSecurityException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/** Field msgID */
protected String msgID;
/**
* Constructor XMLSecurityException
*
*/
public XMLSecurityException() {
super("Missing message string");
this.msgID = null;
}
/**
* Constructor XMLSecurityException
*
* @param msgID
*/
public XMLSecurityException(String msgID) {
super(I18n.getExceptionMessage(msgID));
this.msgID = msgID;
}
/**
* Constructor XMLSecurityException
*
* @param msgID
* @param exArgs
*/
public XMLSecurityException(String msgID, Object[] exArgs) {
super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
this.msgID = msgID;
}
/**
* Constructor XMLSecurityException
*
* @param originalException
*/
public XMLSecurityException(Exception originalException) {
super(originalException.getMessage(), originalException);
}
/**
* Constructor XMLSecurityException
*
* @param msgID
* @param originalException
*/
public XMLSecurityException(Exception originalException, String msgID) {
super(I18n.getExceptionMessage(msgID, originalException), originalException);
this.msgID = msgID;
}
@Deprecated
public XMLSecurityException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor XMLSecurityException
*
* @param msgID
* @param exArgs
* @param originalException
*/
public XMLSecurityException(Exception originalException, String msgID, Object[] exArgs) {
super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException);
this.msgID = msgID;
}
@Deprecated
public XMLSecurityException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
/**
* Method getMsgID
*
* @return the messageId
*/
public String getMsgID() {
if (msgID == null) {
return "Missing message ID";
}
return msgID;
}
/** {@inheritDoc} */
@Override
public String toString() {
String s = this.getClass().getName();
String message = super.getLocalizedMessage();
if (message != null) {
message = s + ": " + message;
} else {
message = s;
}
if (super.getCause() != null) {
message = message + "\nOriginal Exception was " + super.getCause().toString();
}
return message;
}
/**
* Method printStackTrace
*
*/
@Override
public void printStackTrace() {
synchronized (System.err) {
super.printStackTrace(System.err);
}
}
/**
* Method getOriginalException
*
* @return the original exception
*/
public Exception getOriginalException() {
if (this.getCause() instanceof Exception) {
return (Exception)this.getCause();
}
return null;
}
}

View file

@ -0,0 +1,150 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides content model support for the {@code dsig11:DEREncodedKeyvalue} element.
*
*/
public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent {
/** JCA algorithm key types supported by this implementation. */
private static final String[] supportedKeyTypes = { "RSA", "DSA", "EC",
"DiffieHellman", "DH", "XDH", "X25519", "X448",
"EdDSA", "Ed25519", "Ed448",
"RSASSA-PSS"};
/**
* Constructor DEREncodedKeyValue
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public DEREncodedKeyValue(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor DEREncodedKeyValue
*
* @param doc
* @param publicKey
* @throws XMLSecurityException
*/
public DEREncodedKeyValue(Document doc, PublicKey publicKey) throws XMLSecurityException {
super(doc);
this.addBase64Text(getEncodedDER(publicKey));
}
/**
* Constructor DEREncodedKeyValue
*
* @param doc
* @param encodedKey
*/
public DEREncodedKeyValue(Document doc, byte[] encodedKey) {
super(doc);
this.addBase64Text(encodedKey);
}
/**
* Sets the {@code Id} attribute
*
* @param id ID
*/
public void setId(String id) {
setLocalIdAttribute(Constants._ATT_ID, id);
}
/**
* Returns the {@code Id} attribute
*
* @return the {@code Id} attribute
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_DERENCODEDKEYVALUE;
}
/**
* Method getPublicKey
*
* @return the public key
* @throws XMLSecurityException
*/
public PublicKey getPublicKey() throws XMLSecurityException {
byte[] encodedKey = getBytesFromTextChild();
// Iterate over the supported key types until one produces a public key.
for (String keyType : supportedKeyTypes) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(keyType);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
if (publicKey != null) {
return publicKey;
}
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) { //NOPMD
// Do nothing, try the next type
}
}
throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedEncodedKey");
}
/**
* Method getEncodedDER
*
* @return the public key
* @throws XMLSecurityException
*/
protected byte[] getEncodedDER(PublicKey publicKey) throws XMLSecurityException {
try {
KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm());
X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class);
return keySpec.getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
Object[] exArgs = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
}
}
}

View file

@ -0,0 +1,30 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
/**
* Empty interface just to identify Elements that can be children of ds:KeyInfo.
*
*/
public interface KeyInfoContent {
}

View file

@ -0,0 +1,102 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides content model support for the {@code dsig11:KeyInfoReference} element.
*
*/
public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent {
/**
* Constructor RetrievalMethod
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor RetrievalMethod
*
* @param doc
* @param uri
*/
public KeyInfoReference(Document doc, String uri) {
super(doc);
setLocalAttribute(Constants._ATT_URI, uri);
}
/**
* Method getURIAttr
*
* @return the URI attribute
*/
public Attr getURIAttr() {
return getElement().getAttributeNodeNS(null, Constants._ATT_URI);
}
/**
* Method getURI
*
* @return URI string
*/
public String getURI() {
return this.getURIAttr().getNodeValue();
}
/**
* Sets the {@code Id} attribute
*
* @param id ID
*/
public void setId(String id) {
setLocalIdAttribute(Constants._ATT_ID, id);
}
/**
* Returns the {@code Id} attribute
*
* @return the {@code Id} attribute
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_KEYINFOREFERENCE;
}
}

View file

@ -0,0 +1,72 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*/
public class KeyName extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor KeyName
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public KeyName(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor KeyName
*
* @param doc
* @param keyName
*/
public KeyName(Document doc, String keyName) {
super(doc);
this.addText(keyName);
}
/**
* Method getKeyName
*
* @return key name
*/
public String getKeyName() {
return this.getTextFromTextChild();
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_KEYNAME;
}
}

View file

@ -0,0 +1,180 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import java.security.PublicKey;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.ECKeyValue;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.RSAKeyValue;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* The KeyValue element contains a single public key that may be useful in
* validating the signature. Structured formats for defining DSA (REQUIRED)
* and RSA (RECOMMENDED) public keys are defined in Signature Algorithms
* (section 6.4). The KeyValue element may include externally defined public
* keys values represented as PCDATA or element types from an external
* namespace.
*/
public class KeyValue extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor KeyValue
*
* @param doc
* @param dsaKeyValue
*/
public KeyValue(Document doc, DSAKeyValue dsaKeyValue) {
super(doc);
addReturnToSelf();
appendSelf(dsaKeyValue);
addReturnToSelf();
}
/**
* Constructor KeyValue
*
* @param doc
* @param rsaKeyValue
*/
public KeyValue(Document doc, RSAKeyValue rsaKeyValue) {
super(doc);
addReturnToSelf();
appendSelf(rsaKeyValue);
addReturnToSelf();
}
/**
* Constructor KeyValue
*
* @param doc
* @param unknownKeyValue
*/
public KeyValue(Document doc, Element unknownKeyValue) {
super(doc);
addReturnToSelf();
appendSelf(unknownKeyValue);
addReturnToSelf();
}
/**
* Constructor KeyValue
*
* @param doc
* @param pk
*/
public KeyValue(Document doc, PublicKey pk) {
super(doc);
addReturnToSelf();
if (pk instanceof java.security.interfaces.DSAPublicKey) {
DSAKeyValue dsa = new DSAKeyValue(getDocument(), pk);
appendSelf(dsa);
addReturnToSelf();
} else if (pk instanceof java.security.interfaces.RSAPublicKey) {
RSAKeyValue rsa = new RSAKeyValue(getDocument(), pk);
appendSelf(rsa);
addReturnToSelf();
} else if (pk instanceof java.security.interfaces.ECPublicKey) {
ECKeyValue ec = new ECKeyValue(getDocument(), pk);
appendSelf(ec);
addReturnToSelf();
} else {
String error = "The given PublicKey type " + pk + " is not supported. Only DSAPublicKey and "
+ "RSAPublicKey and ECPublicKey types are currently supported";
throw new IllegalArgumentException(error);
}
}
/**
* Verifies that the XML KeyValue encoding is supported for the given key type. If the
* encoding is supported, it returns true else false.
*
* @return true if the public key has a KeyValue encoding, false otherwise.
*/
public static boolean isSupportedKeyType(PublicKey publicKey) {
return publicKey instanceof java.security.interfaces.DSAPublicKey
|| publicKey instanceof java.security.interfaces.RSAPublicKey
|| publicKey instanceof java.security.interfaces.ECPublicKey;
}
/**
* Constructor KeyValue
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public KeyValue(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Method getPublicKey
*
* @return the public key
* @throws XMLSecurityException
*/
public PublicKey getPublicKey() throws XMLSecurityException {
Element rsa =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
if (rsa != null) {
RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI);
return kv.getPublicKey();
}
Element dsa =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
if (dsa != null) {
DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI);
return kv.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_KEYVALUE;
}
}

View file

@ -0,0 +1,73 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*/
public class MgmtData extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor MgmtData
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public MgmtData(Element element, String baseURI)
throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor MgmtData
*
* @param doc
* @param mgmtData
*/
public MgmtData(Document doc, String mgmtData) {
super(doc);
this.addText(mgmtData);
}
/**
* Method getMgmtData
*
* @return the management data
*/
public String getMgmtData() {
return this.getTextFromTextChild();
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_MGMTDATA;
}
}

View file

@ -0,0 +1,51 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Element;
/**
* $todo$ Implement
*/
public class PGPData extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor PGPData
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public PGPData(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_PGPDATA;
}
}

View file

@ -0,0 +1,136 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent {
/** DSA retrieval */
public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue";
/** RSA retrieval */
public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue";
/** PGP retrieval */
public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData";
/** SPKI retrieval */
public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData";
/** MGMT retrieval */
public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData";
/** X509 retrieval */
public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data";
/** RAWX509 retrieval */
public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate";
/**
* Constructor RetrievalMethod
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public RetrievalMethod(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor RetrievalMethod
*
* @param doc
* @param URI
* @param transforms
* @param Type
*/
public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) {
super(doc);
setLocalAttribute(Constants._ATT_URI, URI);
if (Type != null) {
setLocalAttribute(Constants._ATT_TYPE, Type);
}
if (transforms != null) {
appendSelf(transforms);
addReturnToSelf();
}
}
/**
* Method getURIAttr
*
* @return the URI attribute
*/
public Attr getURIAttr() {
return getElement().getAttributeNodeNS(null, Constants._ATT_URI);
}
/**
* Method getURI
*
* @return URI string
*/
public String getURI() {
return getLocalAttribute(Constants._ATT_URI);
}
/** @return the type*/
public String getType() {
return getLocalAttribute(Constants._ATT_TYPE);
}
/**
* Method getTransforms
*
* @throws XMLSecurityException
* @return the transformations
*/
public Transforms getTransforms() throws XMLSecurityException {
try {
Element transformsElem =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_TRANSFORMS, 0);
if (transformsElem != null) {
return new Transforms(transformsElem, this.baseURI);
}
return null;
} catch (XMLSignatureException ex) {
throw new XMLSecurityException(ex);
}
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_RETRIEVALMETHOD;
}
}

View file

@ -0,0 +1,52 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Element;
/**
* $todo$ implement
*/
public class SPKIData extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor SPKIData
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public SPKIData(Element element, String baseURI)
throws XMLSecurityException {
super(element, baseURI);
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_SPKIDATA;
}
}

View file

@ -0,0 +1,535 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
import java.math.BigInteger;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509CRL;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class X509Data extends SignatureElementProxy implements KeyInfoContent {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509Data.class);
/**
* Constructor X509Data
*
* @param doc
*/
public X509Data(Document doc) {
super(doc);
addReturnToSelf();
}
/**
* Constructor X509Data
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public X509Data(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
Node sibling = getFirstChild();
while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
sibling = sibling.getNextSibling();
}
if (sibling == null || sibling.getNodeType() != Node.ELEMENT_NODE) {
/* No Elements found */
Object[] exArgs = { "Elements", Constants._TAG_X509DATA };
throw new XMLSecurityException("xml.WrongContent", exArgs);
}
}
/**
* Method addIssuerSerial
*
* @param X509IssuerName
* @param X509SerialNumber
*/
public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) {
this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
}
/**
* Method addIssuerSerial
*
* @param X509IssuerName
* @param X509SerialNumber
*/
public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) {
this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
}
/**
* Method addIssuerSerial
*
* @param X509IssuerName
* @param X509SerialNumber
*/
public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) {
this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
}
/**
* Method add
*
* @param xmlX509IssuerSerial
*/
public void add(XMLX509IssuerSerial xmlX509IssuerSerial) {
appendSelf(xmlX509IssuerSerial);
addReturnToSelf();
}
/**
* Method addSKI
*
* @param skiBytes
*/
public void addSKI(byte[] skiBytes) {
this.add(new XMLX509SKI(getDocument(), skiBytes));
}
/**
* Method addSKI
*
* @param x509certificate
* @throws XMLSecurityException
*/
public void addSKI(X509Certificate x509certificate)
throws XMLSecurityException {
this.add(new XMLX509SKI(getDocument(), x509certificate));
}
/**
* Method add
*
* @param xmlX509SKI
*/
public void add(XMLX509SKI xmlX509SKI) {
appendSelf(xmlX509SKI);
addReturnToSelf();
}
/**
* Method addSubjectName
*
* @param subjectName
*/
public void addSubjectName(String subjectName) {
this.add(new XMLX509SubjectName(getDocument(), subjectName));
}
/**
* Method addSubjectName
*
* @param x509certificate
*/
public void addSubjectName(X509Certificate x509certificate) {
this.add(new XMLX509SubjectName(getDocument(), x509certificate));
}
/**
* Method add
*
* @param xmlX509SubjectName
*/
public void add(XMLX509SubjectName xmlX509SubjectName) {
appendSelf(xmlX509SubjectName);
addReturnToSelf();
}
/**
* Method addCertificate
*
* @param x509certificate
* @throws XMLSecurityException
*/
public void addCertificate(X509Certificate x509certificate)
throws XMLSecurityException {
this.add(new XMLX509Certificate(getDocument(), x509certificate));
}
/**
* Method addCertificate
*
* @param x509certificateBytes
*/
public void addCertificate(byte[] x509certificateBytes) {
this.add(new XMLX509Certificate(getDocument(), x509certificateBytes));
}
/**
* Method add
*
* @param xmlX509Certificate
*/
public void add(XMLX509Certificate xmlX509Certificate) {
appendSelf(xmlX509Certificate);
addReturnToSelf();
}
/**
* Method addCRL
*
* @param crlBytes
*/
public void addCRL(byte[] crlBytes) {
this.add(new XMLX509CRL(getDocument(), crlBytes));
}
/**
* Method add
*
* @param xmlX509CRL
*/
public void add(XMLX509CRL xmlX509CRL) {
appendSelf(xmlX509CRL);
addReturnToSelf();
}
/**
* Method addDigest
*
* @param x509certificate
* @param algorithmURI
* @throws XMLSecurityException
*/
public void addDigest(X509Certificate x509certificate, String algorithmURI)
throws XMLSecurityException {
this.add(new XMLX509Digest(getDocument(), x509certificate, algorithmURI));
}
/**
* Method addDigest
*
* @param x509CertificateDigestBytes
* @param algorithmURI
*/
public void addDigest(byte[] x509CertificateDigestBytes, String algorithmURI) {
this.add(new XMLX509Digest(getDocument(), x509CertificateDigestBytes, algorithmURI));
}
/**
* Method add
*
* @param xmlX509Digest
*/
public void add(XMLX509Digest xmlX509Digest) {
appendSelf(xmlX509Digest);
addReturnToSelf();
}
/**
* Method addUnknownElement
*
* @param element
*/
public void addUnknownElement(Element element) {
appendSelf(element);
addReturnToSelf();
}
/**
* Method lengthIssuerSerial
*
* @return the number of IssuerSerial elements in this X509Data
*/
public int lengthIssuerSerial() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL);
}
/**
* Method lengthSKI
*
* @return the number of SKI elements in this X509Data
*/
public int lengthSKI() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI);
}
/**
* Method lengthSubjectName
*
* @return the number of SubjectName elements in this X509Data
*/
public int lengthSubjectName() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME);
}
/**
* Method lengthCertificate
*
* @return the number of Certificate elements in this X509Data
*/
public int lengthCertificate() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE);
}
/**
* Method lengthCRL
*
* @return the number of CRL elements in this X509Data
*/
public int lengthCRL() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL);
}
/**
* Method lengthDigest
*
* @return the number of X509Digest elements in this X509Data
*/
public int lengthDigest() {
return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST);
}
/**
* Method lengthUnknownElement
*
* @return the number of UnknownElement elements in this X509Data
*/
public int lengthUnknownElement() {
int result = 0;
Node n = getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE
&& !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
result++;
}
n = n.getNextSibling();
}
return result;
}
/**
* Method itemIssuerSerial
*
* @param i
* @return the X509IssuerSerial, null if not present
* @throws XMLSecurityException
*/
public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
if (e != null) {
return new XMLX509IssuerSerial(e, this.baseURI);
}
return null;
}
/**
* Method itemSKI
*
* @param i
* @return the X509SKI, null if not present
* @throws XMLSecurityException
*/
public XMLX509SKI itemSKI(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_X509SKI, i);
if (e != null) {
return new XMLX509SKI(e, this.baseURI);
}
return null;
}
/**
* Method itemSubjectName
*
* @param i
* @return the X509SubjectName, null if not present
* @throws XMLSecurityException
*/
public XMLX509SubjectName itemSubjectName(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
if (e != null) {
return new XMLX509SubjectName(e, this.baseURI);
}
return null;
}
/**
* Method itemCertificate
*
* @param i
* @return the X509Certificate, null if not present
* @throws XMLSecurityException
*/
public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
if (e != null) {
return new XMLX509Certificate(e, this.baseURI);
}
return null;
}
/**
* Method itemCRL
*
* @param i
* @return the X509CRL, null if not present
* @throws XMLSecurityException
*/
public XMLX509CRL itemCRL(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
getFirstChild(), Constants._TAG_X509CRL, i);
if (e != null) {
return new XMLX509CRL(e, this.baseURI);
}
return null;
}
/**
* Method itemDigest
*
* @param i
* @return the X509Digest, null if not present
* @throws XMLSecurityException
*/
public XMLX509Digest itemDigest(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDs11Node(
getFirstChild(), Constants._TAG_X509DIGEST, i);
if (e != null) {
return new XMLX509Digest(e, this.baseURI);
}
return null;
}
/**
* Method itemUnknownElement
*
* @param i
* @return the Unknown Element at i
* TODO implement
**/
public Element itemUnknownElement(int i) {
LOG.debug("itemUnknownElement not implemented: {}", i);
return null;
}
/**
* Method containsIssuerSerial
*
* @return true if this X509Data contains a IssuerSerial
*/
public boolean containsIssuerSerial() {
return this.lengthIssuerSerial() > 0;
}
/**
* Method containsSKI
*
* @return true if this X509Data contains a SKI
*/
public boolean containsSKI() {
return this.lengthSKI() > 0;
}
/**
* Method containsSubjectName
*
* @return true if this X509Data contains a SubjectName
*/
public boolean containsSubjectName() {
return this.lengthSubjectName() > 0;
}
/**
* Method containsCertificate
*
* @return true if this X509Data contains a Certificate
*/
public boolean containsCertificate() {
return this.lengthCertificate() > 0;
}
/**
* Method containsDigest
*
* @return true if this X509Data contains an X509Digest
*/
public boolean containsDigest() {
return this.lengthDigest() > 0;
}
/**
* Method containsCRL
*
* @return true if this X509Data contains a CRL
*/
public boolean containsCRL() {
return this.lengthCRL() > 0;
}
/**
* Method containsUnknownElement
*
* @return true if this X509Data contains an UnknownElement
*/
public boolean containsUnknownElement() {
return this.lengthUnknownElement() > 0;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509DATA;
}
}

View file

@ -0,0 +1,131 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent {
/**
* Constructor DSAKeyValue
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public DSAKeyValue(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor DSAKeyValue
*
* @param doc
* @param P
* @param Q
* @param G
* @param Y
*/
public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) {
super(doc);
addReturnToSelf();
this.addBigIntegerElement(P, Constants._TAG_P);
this.addBigIntegerElement(Q, Constants._TAG_Q);
this.addBigIntegerElement(G, Constants._TAG_G);
this.addBigIntegerElement(Y, Constants._TAG_Y);
}
/**
* Constructor DSAKeyValue
*
* @param doc
* @param key
* @throws IllegalArgumentException
*/
public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
super(doc);
addReturnToSelf();
if (key instanceof DSAPublicKey) {
DSAParams params = ((DSAPublicKey) key).getParams();
this.addBigIntegerElement(params.getP(), Constants._TAG_P);
this.addBigIntegerElement(params.getQ(), Constants._TAG_Q);
this.addBigIntegerElement(params.getG(), Constants._TAG_G);
this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y);
} else {
Object[] exArgs = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
}
}
/** {@inheritDoc} */
@Override
public PublicKey getPublicKey() throws XMLSecurityException {
try {
DSAPublicKeySpec pkspec =
new DSAPublicKeySpec(
this.getBigIntegerFromChildElement(
Constants._TAG_Y, Constants.SignatureSpecNS
),
this.getBigIntegerFromChildElement(
Constants._TAG_P, Constants.SignatureSpecNS
),
this.getBigIntegerFromChildElement(
Constants._TAG_Q, Constants.SignatureSpecNS
),
this.getBigIntegerFromChildElement(
Constants._TAG_G, Constants.SignatureSpecNS
)
);
KeyFactory dsaFactory = KeyFactory.getInstance("DSA");
return dsaFactory.generatePublic(pkspec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
throw new XMLSecurityException(ex);
}
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_DSAKEYVALUE;
}
}

View file

@ -0,0 +1,414 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECField;
import java.security.spec.ECFieldFp;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.EllipticCurve;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.xml.crypto.MarshalException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public class ECKeyValue extends Signature11ElementProxy implements KeyValueContent {
/* Supported curve, secp256r1 */
private static final Curve SECP256R1 = initializeCurve(
"secp256r1 [NIST P-256, X9.62 prime256v1]",
"1.2.840.10045.3.1.7",
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B",
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",
"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",
1
);
/* Supported curve secp384r1 */
private static final Curve SECP384R1 = initializeCurve(
"secp384r1 [NIST P-384]",
"1.3.132.0.34",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC",
"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF",
"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7",
"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F",
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973",
1
);
/* Supported curve secp521r1 */
private static final Curve SECP521R1 = initializeCurve(
"secp521r1 [NIST P-521]",
"1.3.132.0.35",
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC",
"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00",
"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66",
"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650",
"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409",
1
);
/* Supported curve brainpoolP256r1 */
private static final Curve BRAINPOOLP256R1 = initializeCurve(
"brainpoolP256r1 [RFC 5639]",
"1.3.36.3.3.2.8.1.1.7",
"A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377",
"7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9",
"26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6",
"8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262",
"547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997",
"A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7",
1
);
/* Supported curve brainpoolP384r1 */
private static final Curve BRAINPOOLP384R1 = initializeCurve(
"brainpoolP384r1 [RFC 5639]",
"1.3.36.3.3.2.8.1.1.11",
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53",
"7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826",
"04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11",
"1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E",
"8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315",
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565",
1
);
/* Supported curve brainpoolP512r1 */
private static final Curve BRAINPOOLP512R1 = initializeCurve(
"brainpoolP512r1 [RFC 5639]",
"1.3.36.3.3.2.8.1.1.13",
"AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3",
"7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA",
"3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723",
"81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822",
"7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892",
"AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069",
1
);
private static Curve initializeCurve(String name, String oid,
String sfield, String a, String b,
String x, String y, String n, int h) {
BigInteger p = bigInt(sfield);
ECField field = new ECFieldFp(p);
EllipticCurve curve = new EllipticCurve(field, bigInt(a),
bigInt(b));
ECPoint g = new ECPoint(bigInt(x), bigInt(y));
return new Curve(name, oid, curve, g, bigInt(n), h);
}
/**
* Constructor DSAKeyValue
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public ECKeyValue(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor DSAKeyValue
*
* @param doc
* @param key
* @throws IllegalArgumentException
*/
public ECKeyValue(Document doc, Key key) throws IllegalArgumentException {
super(doc);
addReturnToSelf();
if (key instanceof ECPublicKey) {
ECParameterSpec ecParams = ((ECPublicKey)key).getParams();
// NamedCurve
String oid = getCurveOid(ecParams);
if (oid == null) {
throw new IllegalArgumentException("Invalid ECParameterSpec");
}
Element namedCurveElement = XMLUtils.createElementInSignature11Space(getDocument(), "NamedCurve");
namedCurveElement.setAttributeNS(null, "URI", "urn:oid:" + oid);
appendSelf(namedCurveElement);
addReturnToSelf();
// PublicKey
ECPoint ecPoint = ((ECPublicKey)key).getW();
byte[] secPublicKey = encodePoint(ecPoint, ecParams.getCurve());
String encoded = XMLUtils.encodeToString(secPublicKey);
Element publicKeyElement = XMLUtils.createElementInSignature11Space(getDocument(), "PublicKey");
Text text = getDocument().createTextNode(encoded);
publicKeyElement.appendChild(text);
appendSelf(publicKeyElement);
addReturnToSelf();
} else {
Object[] exArgs = { Constants._TAG_ECKEYVALUE, key.getClass().getName() };
throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
}
}
/** {@inheritDoc} */
@Override
public PublicKey getPublicKey() throws XMLSecurityException {
try {
ECParameterSpec ecParams = null;
Element curElem = getFirstChildElement(getElement());
if (curElem == null) {
throw new MarshalException("KeyValue must contain at least one type");
}
if ("ECParameters".equals(curElem.getLocalName())
&& Constants.SignatureSpec11NS.equals(curElem.getNamespaceURI())) {
throw new UnsupportedOperationException
("ECParameters not supported");
} else if ("NamedCurve".equals(curElem.getLocalName())
&& Constants.SignatureSpec11NS.equals(curElem.getNamespaceURI())) {
String uri = null;
if (curElem.hasAttributeNS(null, "URI")) {
uri = curElem.getAttributeNS(null, "URI");
}
// strip off "urn:oid"
if (uri != null && uri.startsWith("urn:oid:")) {
String oid = uri.substring("urn:oid:".length());
ecParams = getECParameterSpec(oid);
if (ecParams == null) {
throw new MarshalException("Invalid curve OID");
}
} else {
throw new MarshalException("Invalid NamedCurve URI");
}
} else {
throw new MarshalException("Invalid ECKeyValue");
}
curElem = getNextSiblingElement(curElem, "PublicKey", Constants.SignatureSpec11NS);
ECPoint ecPoint = null;
try {
String content = XMLUtils.getFullTextChildrenFromNode(curElem);
ecPoint = decodePoint(XMLUtils.decode(content), ecParams.getCurve());
} catch (IOException ioe) {
throw new MarshalException("Invalid EC Point", ioe);
}
ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams);
return KeyFactory.getInstance("EC").generatePublic(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException | MarshalException ex) {
throw new XMLSecurityException(ex);
}
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_ECKEYVALUE;
}
private static Element getFirstChildElement(Node node) {
Node child = node.getFirstChild();
while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
child = child.getNextSibling();
}
return (Element)child;
}
private static Element getNextSiblingElement(Node node, String localName, String namespaceURI)
throws MarshalException
{
return verifyElement(getNextSiblingElement(node), localName, namespaceURI);
}
private static Element getNextSiblingElement(Node node) {
Node sibling = node.getNextSibling();
while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
sibling = sibling.getNextSibling();
}
return (Element)sibling;
}
private static Element verifyElement(Element elem, String localName, String namespaceURI)
throws MarshalException
{
if (elem == null) {
throw new MarshalException("Missing " + localName + " element");
}
String name = elem.getLocalName();
String namespace = elem.getNamespaceURI();
if (!name.equals(localName) || namespace == null && namespaceURI != null
|| namespace != null && !namespace.equals(namespaceURI)) {
throw new MarshalException("Invalid element name: " +
namespace + ":" + name + ", expected " + namespaceURI + ":" + localName);
}
return elem;
}
private static String getCurveOid(ECParameterSpec params) {
// Check that the params represent one of the supported
// curves. If there is a match, return the object identifier
// of the curve.
Curve match;
if (matchCurve(params, SECP256R1)) {
match = SECP256R1;
} else if (matchCurve(params, SECP384R1)) {
match = SECP384R1;
} else if (matchCurve(params, SECP521R1)) {
match = SECP521R1;
} else if (matchCurve(params, BRAINPOOLP256R1)) {
match = BRAINPOOLP256R1;
} else if (matchCurve(params, BRAINPOOLP384R1)) {
match = BRAINPOOLP384R1;
} else if (matchCurve(params, BRAINPOOLP512R1)) {
match = BRAINPOOLP512R1;
}else {
return null;
}
return match.getObjectId();
}
private static boolean matchCurve(ECParameterSpec params, Curve curve) {
int fieldSize = params.getCurve().getField().getFieldSize();
return curve.getCurve().getField().getFieldSize() == fieldSize
&& curve.getCurve().equals(params.getCurve())
&& curve.getGenerator().equals(params.getGenerator())
&& curve.getOrder().equals(params.getOrder())
&& curve.getCofactor() == params.getCofactor();
}
private static ECPoint decodePoint(byte[] data, EllipticCurve curve)
throws IOException {
if (data.length == 0 || data[0] != 4) {
throw new IOException("Only uncompressed point format " +
"supported");
}
// Per ANSI X9.62, an encoded point is a 1 byte type followed by
// ceiling(LOG base 2 field-size / 8) bytes of x and the same of y.
int n = (data.length - 1) / 2;
if (n != (curve.getField().getFieldSize() + 7) >> 3) {
throw new IOException("Point does not match field size");
}
byte[] xb = Arrays.copyOfRange(data, 1, 1 + n);
byte[] yb = Arrays.copyOfRange(data, n + 1, n + 1 + n);
return new ECPoint(new BigInteger(1, xb), new BigInteger(1, yb));
}
private static byte[] encodePoint(ECPoint point, EllipticCurve curve) {
// get field size in bytes (rounding up)
int n = (curve.getField().getFieldSize() + 7) >> 3;
byte[] xb = trimZeroes(point.getAffineX().toByteArray());
byte[] yb = trimZeroes(point.getAffineY().toByteArray());
if (xb.length > n || yb.length > n) {
throw new RuntimeException("Point coordinates do not " +
"match field size");
}
byte[] b = new byte[1 + (n << 1)];
b[0] = 4; // uncompressed
System.arraycopy(xb, 0, b, n - xb.length + 1, xb.length);
System.arraycopy(yb, 0, b, b.length - yb.length, yb.length);
return b;
}
private static byte[] trimZeroes(byte[] b) {
int i = 0;
while (i < b.length - 1 && b[i] == 0) {
i++;
}
if (i == 0) {
return b;
}
return Arrays.copyOfRange(b, i, b.length);
}
private static ECParameterSpec getECParameterSpec(String oid) {
if (oid.equals(SECP256R1.getObjectId())) {
return SECP256R1;
} else if (oid.equals(SECP384R1.getObjectId())) {
return SECP384R1;
} else if (oid.equals(SECP521R1.getObjectId())) {
return SECP521R1;
} else if (oid.equals(BRAINPOOLP256R1.getObjectId())) {
return BRAINPOOLP256R1;
} else if (oid.equals(BRAINPOOLP384R1.getObjectId())) {
return BRAINPOOLP384R1;
} else if (oid.equals(BRAINPOOLP512R1.getObjectId())) {
return BRAINPOOLP512R1;
} else {
return null;
}
}
static final class Curve extends ECParameterSpec {
private final String name;
private final String oid;
Curve(String name, String oid, EllipticCurve curve,
ECPoint g, BigInteger n, int h) {
super(curve, g, n, h);
this.name = name;
this.oid = oid;
}
private String getName() {
return name;
}
private String getObjectId() {
return oid;
}
}
private static BigInteger bigInt(String s) {
return new BigInteger(s, 16);
}
}

View file

@ -0,0 +1,39 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
import java.security.PublicKey;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
public interface KeyValueContent {
/**
* Method getPublicKey
*
* @return the public key
* @throws XMLSecurityException
*/
PublicKey getPublicKey() throws XMLSecurityException;
}

View file

@ -0,0 +1,123 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.keyvalues;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent {
/**
* Constructor RSAKeyValue
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public RSAKeyValue(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor RSAKeyValue
*
* @param doc
* @param modulus
* @param exponent
*/
public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
super(doc);
addReturnToSelf();
this.addBigIntegerElement(modulus, Constants._TAG_MODULUS);
this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT);
}
/**
* Constructor RSAKeyValue
*
* @param doc
* @param key
* @throws IllegalArgumentException
*/
public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
super(doc);
addReturnToSelf();
if (key instanceof RSAPublicKey ) {
this.addBigIntegerElement(
((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS
);
this.addBigIntegerElement(
((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT
);
} else {
Object[] exArgs = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() };
throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
}
}
/** {@inheritDoc} */
@Override
public PublicKey getPublicKey() throws XMLSecurityException {
try {
KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec rsaKeyspec =
new RSAPublicKeySpec(
this.getBigIntegerFromChildElement(
Constants._TAG_MODULUS, Constants.SignatureSpecNS
),
this.getBigIntegerFromChildElement(
Constants._TAG_EXPONENT, Constants.SignatureSpecNS
)
);
PublicKey pk = rsaFactory.generatePublic(rsaKeyspec);
return pk;
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
throw new XMLSecurityException(ex);
}
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_RSAKEYVALUE;
}
}

View file

@ -0,0 +1,71 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent {
/**
* Constructor XMLX509CRL
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public XMLX509CRL(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor X509CRL
*
* @param doc
* @param crlBytes
*/
public XMLX509CRL(Document doc, byte[] crlBytes) {
super(doc);
this.addBase64Text(crlBytes);
}
/**
* Method getCRLBytes
*
* @return the CRL bytes
* @throws XMLSecurityException
*/
public byte[] getCRLBytes() throws XMLSecurityException {
return this.getBytesFromTextChild();
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509CRL;
}
}

View file

@ -0,0 +1,162 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent {
/** Field JCA_CERT_ID */
public static final String JCA_CERT_ID = "X.509";
/**
* Constructor X509Certificate
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public XMLX509Certificate(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor X509Certificate
*
* @param doc
* @param certificateBytes
*/
public XMLX509Certificate(Document doc, byte[] certificateBytes) {
super(doc);
this.addBase64Text(certificateBytes);
}
/**
* Constructor XMLX509Certificate
*
* @param doc
* @param x509certificate
* @throws XMLSecurityException
*/
public XMLX509Certificate(Document doc, X509Certificate x509certificate)
throws XMLSecurityException {
super(doc);
try {
this.addBase64Text(x509certificate.getEncoded());
} catch (java.security.cert.CertificateEncodingException ex) {
throw new XMLSecurityException(ex);
}
}
/**
* Method getCertificateBytes
*
* @return the certificate bytes
* @throws XMLSecurityException
*/
public byte[] getCertificateBytes() throws XMLSecurityException {
return this.getBytesFromTextChild();
}
/**
* Method getX509Certificate
*
* @return the x509 certificate
* @throws XMLSecurityException
*/
public X509Certificate getX509Certificate() throws XMLSecurityException {
byte[] certbytes = this.getCertificateBytes();
try (InputStream is = new ByteArrayInputStream(certbytes)) {
CertificateFactory certFact =
CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
return (X509Certificate) certFact.generateCertificate(is);
} catch (CertificateException | IOException ex) {
throw new XMLSecurityException(ex);
}
}
/**
* Method getPublicKey
*
* @return the publickey
* @throws XMLSecurityException
*/
public PublicKey getPublicKey() throws XMLSecurityException, IOException {
X509Certificate cert = this.getX509Certificate();
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (!(obj instanceof XMLX509Certificate)) {
return false;
}
XMLX509Certificate other = (XMLX509Certificate) obj;
try {
return Arrays.equals(other.getCertificateBytes(), this.getCertificateBytes());
} catch (XMLSecurityException ex) {
return false;
}
}
@Override
public int hashCode() {
int result = 17;
try {
byte[] bytes = getCertificateBytes();
for (byte element : bytes) {
result = 31 * result + element;
}
} catch (XMLSecurityException e) {
LOG.debug(e.getMessage(), e);
}
return result;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509CERTIFICATE;
}
}

View file

@ -0,0 +1,30 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
/**
* Just used for tagging contents that are allowed inside a ds:X509Data Element.
*
*/
public interface XMLX509DataContent {
}

View file

@ -0,0 +1,139 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
import java.security.MessageDigest;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides content model support for the {@code dsig11:X509Digest} element.
*
*/
public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent {
/**
* Constructor XMLX509Digest
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public XMLX509Digest(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor XMLX509Digest
*
* @param doc
* @param digestBytes
* @param algorithmURI
*/
public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) {
super(doc);
this.addBase64Text(digestBytes);
setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
}
/**
* Constructor XMLX509Digest
*
* @param doc
* @param x509certificate
* @param algorithmURI
* @throws XMLSecurityException
*/
public XMLX509Digest(Document doc, X509Certificate x509certificate, String algorithmURI) throws XMLSecurityException {
super(doc);
this.addBase64Text(getDigestBytesFromCert(x509certificate, algorithmURI));
setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
}
/**
* Method getAlgorithmAttr
*
* @return the Algorithm attribute
*/
public Attr getAlgorithmAttr() {
return getElement().getAttributeNodeNS(null, Constants._ATT_ALGORITHM);
}
/**
* Method getAlgorithm
*
* @return Algorithm string
*/
public String getAlgorithm() {
return this.getAlgorithmAttr().getNodeValue();
}
/**
* Method getDigestBytes
*
* @return the digestbytes
* @throws XMLSecurityException
*/
public byte[] getDigestBytes() throws XMLSecurityException {
return this.getBytesFromTextChild();
}
/**
* Method getDigestBytesFromCert
*
* @param cert
* @param algorithmURI
* @return digest bytes from the given certificate
*
* @throws XMLSecurityException
*/
public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException {
String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI);
if (jcaDigestAlgorithm == null) {
Object[] exArgs = {algorithmURI};
throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs);
}
try {
MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
return md.digest(cert.getEncoded());
} catch (Exception e) {
Object[] exArgs = {jcaDigestAlgorithm};
throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
}
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509DIGEST;
}
}

View file

@ -0,0 +1,160 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
import java.math.BigInteger;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.RFC2253Parser;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLX509IssuerSerial.class);
/**
* Constructor XMLX509IssuerSerial
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor XMLX509IssuerSerial
*
* @param doc
* @param x509IssuerName
* @param x509SerialNumber
*/
public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) {
super(doc);
addReturnToSelf();
addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME);
addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER);
}
/**
* Constructor XMLX509IssuerSerial
*
* @param doc
* @param x509IssuerName
* @param x509SerialNumber
*/
public XMLX509IssuerSerial(Document doc, String x509IssuerName, String x509SerialNumber) {
this(doc, x509IssuerName, new BigInteger(x509SerialNumber));
}
/**
* Constructor XMLX509IssuerSerial
*
* @param doc
* @param x509IssuerName
* @param x509SerialNumber
*/
public XMLX509IssuerSerial(Document doc, String x509IssuerName, int x509SerialNumber) {
this(doc, x509IssuerName, new BigInteger(Integer.toString(x509SerialNumber)));
}
/**
* Constructor XMLX509IssuerSerial
*
* @param doc
* @param x509certificate
*/
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
this(
doc,
x509certificate.getIssuerX500Principal().getName(),
x509certificate.getSerialNumber()
);
}
/**
* Method getSerialNumber
*
* @return the serial number
*/
public BigInteger getSerialNumber() {
String text =
this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS);
LOG.debug("X509SerialNumber text: {}", text);
return new BigInteger(text);
}
/**
* Method getSerialNumberInteger
*
* @return the serial number as plain int
*/
public int getSerialNumberInteger() {
return this.getSerialNumber().intValue();
}
/**
* Method getIssuerName
*
* @return the issuer name
*/
public String getIssuerName() {
return RFC2253Parser.normalize(
this.getTextFromChildElement(Constants._TAG_X509ISSUERNAME, Constants.SignatureSpecNS)
);
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (!(obj instanceof XMLX509IssuerSerial)) {
return false;
}
XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj;
return this.getSerialNumber().equals(other.getSerialNumber())
&& this.getIssuerName().equals(other.getIssuerName());
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getSerialNumber().hashCode();
result = 31 * result + getIssuerName().hashCode();
return result;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509ISSUERSERIAL;
}
}

View file

@ -0,0 +1,183 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Handles SubjectKeyIdentifier (SKI) for X.509v3.
*
* @see <A HREF="http://docs.oracle.com/javase/8/docs/api/java/security/cert/X509Extension.html">
* Interface X509Extension</A>
*/
public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLX509SKI.class);
/**
* {@code SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14)}:
* This extension identifies the public key being certified. It enables
* distinct keys used by the same subject to be differentiated
* (e.g., as key updating occurs).
* <p></p>
* A key identifier shall be unique with respect to all key identifiers
* for the subject with which it is used. This extension is always non-critical.
*/
public static final String SKI_OID = "2.5.29.14"; //NOPMD
/**
* Constructor X509SKI
*
* @param doc
* @param skiBytes
*/
public XMLX509SKI(Document doc, byte[] skiBytes) {
super(doc);
this.addBase64Text(skiBytes);
}
/**
* Constructor XMLX509SKI
*
* @param doc
* @param x509certificate
* @throws XMLSecurityException
*/
public XMLX509SKI(Document doc, X509Certificate x509certificate)
throws XMLSecurityException {
super(doc);
this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate));
}
/**
* Constructor XMLX509SKI
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public XMLX509SKI(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Method getSKIBytes
*
* @return the skibytes
* @throws XMLSecurityException
*/
public byte[] getSKIBytes() throws XMLSecurityException {
return this.getBytesFromTextChild();
}
/**
* Method getSKIBytesFromCert
*
* @param cert
* @return ski bytes from the given certificate
*
* @throws XMLSecurityException
* @see java.security.cert.X509Extension#getExtensionValue(java.lang.String)
*/
public static byte[] getSKIBytesFromCert(X509Certificate cert)
throws XMLSecurityException {
if (cert.getVersion() < 3) {
Object[] exArgs = { cert.getVersion() };
throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
}
/*
* Gets the DER-encoded OCTET string for the extension value
* (extnValue) identified by the passed-in oid String. The oid
* string is represented by a set of positive whole numbers
* separated by periods.
*/
byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID);
if (extensionValue == null) {
throw new XMLSecurityException("certificate.noSki.null");
}
/**
* Strip away first four bytes from the extensionValue
* The first two bytes are the tag and length of the extensionValue
* OCTET STRING, and the next two bytes are the tag and length of
* the ski OCTET STRING.
*/
byte[] skidValue = new byte[extensionValue.length - 4];
System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);
if (LOG.isDebugEnabled()) {
LOG.debug("Base64 of SKI is " + XMLUtils.encodeToString(skidValue));
}
return skidValue;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (!(obj instanceof XMLX509SKI)) {
return false;
}
XMLX509SKI other = (XMLX509SKI) obj;
try {
return Arrays.equals(other.getSKIBytes(), this.getSKIBytes());
} catch (XMLSecurityException ex) {
return false;
}
}
@Override
public int hashCode() {
int result = 17;
try {
byte[] bytes = getSKIBytes();
for (byte element : bytes) {
result = 31 * result + element;
}
} catch (XMLSecurityException e) {
LOG.debug(e.getMessage(), e);
}
return result;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509SKI;
}
}

View file

@ -0,0 +1,108 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.RFC2253Parser;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*/
public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent {
/**
* Constructor X509SubjectName
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public XMLX509SubjectName(Element element, String baseURI)
throws XMLSecurityException {
super(element, baseURI);
}
/**
* Constructor X509SubjectName
*
* @param doc
* @param X509SubjectNameString
*/
public XMLX509SubjectName(Document doc, String X509SubjectNameString) {
super(doc);
this.addText(X509SubjectNameString);
}
/**
* Constructor XMLX509SubjectName
*
* @param doc
* @param x509certificate
*/
public XMLX509SubjectName(Document doc, X509Certificate x509certificate) {
this(doc, x509certificate.getSubjectX500Principal().getName());
}
/**
* Method getSubjectName
*
*
* @return the subject name
*/
public String getSubjectName() {
return RFC2253Parser.normalize(this.getTextFromTextChild());
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (!(obj instanceof XMLX509SubjectName)) {
return false;
}
XMLX509SubjectName other = (XMLX509SubjectName) obj;
String otherSubject = other.getSubjectName();
String thisSubject = this.getSubjectName();
return thisSubject.equals(otherSubject);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + this.getSubjectName().hashCode();
return result;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_X509SUBJECTNAME;
}
}

View file

@ -0,0 +1,84 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver;
// NOTE! This is a duplicate of utils.ClassLoaderUtils with public
// modifiers changed to package-private. Make sure to integrate any future
// changes to utils.ClassLoaderUtils to this file.
final class ClassLoaderUtils {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
private ClassLoaderUtils() {
}
/**
* Load a class with a given name. <p></p> It will try to load the class in the
* following order:
* <ul>
* <li>From Thread.currentThread().getContextClassLoader()
* <li>Using the basic Class.forName()
* <li>From ClassLoaderUtil.class.getClassLoader()
* <li>From the callingClass.getClassLoader()
* </ul>
*
* @param className The name of the class to load
* @param callingClass The Class object of the calling object
* @throws ClassNotFoundException If the class cannot be found anywhere.
*/
static Class<?> loadClass(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return cl.loadClass(className);
}
} catch (ClassNotFoundException e) {
LOG.debug(e.getMessage(), e);
//ignore
}
return loadClass2(className, callingClass);
}
private static Class<?> loadClass2(String className, Class<?> callingClass)
throws ClassNotFoundException {
try {
return Class.forName(className);
} catch (ClassNotFoundException ex) {
try {
if (ClassLoaderUtils.class.getClassLoader() != null) {
return ClassLoaderUtils.class.getClassLoader().loadClass(className);
}
} catch (ClassNotFoundException exc) {
if (callingClass != null && callingClass.getClassLoader() != null) {
return callingClass.getClassLoader().loadClass(className);
}
}
LOG.debug(ex.getMessage(), ex);
throw ex;
}
}
}

View file

@ -0,0 +1,321 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver;
import java.lang.reflect.InvocationTargetException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.ECKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.KeyInfoReferenceResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509DigestResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* KeyResolver is factory class for subclass of KeyResolverSpi that
* represent child element of KeyInfo.
*/
public class KeyResolver {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyResolver.class);
private static List<KeyResolverSpi> resolverList = new CopyOnWriteArrayList<>();
private static final AtomicBoolean defaultResolversAdded = new AtomicBoolean();
/**
* Method length
*
* @return the length of resolvers registered
*/
public static int length() {
return resolverList.size();
}
/**
* Method getX509Certificate
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return The certificate represented by the element.
*
* @throws KeyResolverException
*/
public static final X509Certificate getX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
for (KeyResolverSpi resolver : resolverList) {
if (resolver == null) {
Object[] exArgs = {
element != null
&& element.getNodeType() == Node.ELEMENT_NODE
? element.getTagName() : "null"
};
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
LOG.debug("check resolvability by class {}", resolver.getClass());
X509Certificate cert = resolver.engineLookupResolveX509Certificate(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert;
}
}
Object[] exArgs = {
element != null && element.getNodeType() == Node.ELEMENT_NODE
? element.getTagName() : "null"
};
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
/**
* Method getPublicKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return the public key contained in the element
*
* @throws KeyResolverException
*/
public static final PublicKey getPublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
for (KeyResolverSpi resolver : resolverList) {
if (resolver == null) {
Object[] exArgs = {
element != null
&& element.getNodeType() == Node.ELEMENT_NODE
? element.getTagName() : "null"
};
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
LOG.debug("check resolvability by class {}", resolver.getClass());
PublicKey cert = resolver.engineLookupAndResolvePublicKey(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert;
}
}
Object[] exArgs = {
element != null && element.getNodeType() == Node.ELEMENT_NODE
? element.getTagName() : "null"
};
throw new KeyResolverException("utils.resolver.noClass", exArgs);
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* Please note that this method will create a new copy of the underlying array, as the
* underlying collection is a CopyOnWriteArrayList.
*
* @param className
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void register(String className) throws
ClassNotFoundException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JavaUtils.checkRegisterPermission();
KeyResolverSpi keyResolverSpi = (KeyResolverSpi)
JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class));
register(keyResolverSpi, false);
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* Please note that this method will create a new copy of the underlying array, as the
* underlying collection is a CopyOnWriteArrayList.
*
* @param className
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void registerAtStart(String className) {
JavaUtils.checkRegisterPermission();
KeyResolverSpi keyResolverSpi = null;
Exception ex = null;
try {
keyResolverSpi = (KeyResolverSpi)
JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class));
register(keyResolverSpi, true);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
ex = e;
}
if (ex != null) {
throw (IllegalArgumentException) new
IllegalArgumentException("Invalid KeyResolver class name").initCause(ex);
}
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* Please note that this method will create a new copy of the underlying array, as the
* underlying collection is a CopyOnWriteArrayList.
*
* @param keyResolverSpi a KeyResolverSpi instance to register
* @param start whether to register the KeyResolverSpi at the start of the list or not
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void register(
KeyResolverSpi keyResolverSpi,
boolean start
) {
JavaUtils.checkRegisterPermission();
if (start) {
resolverList.add(0, keyResolverSpi);
} else {
resolverList.add(keyResolverSpi);
}
}
/**
* This method is used for registering {@link KeyResolverSpi}s which are
* available to <I>all</I> {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that
* personalized {@link KeyResolverSpi}s should only be registered directly
* to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using
* {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}.
* The KeyResolverSpi instances are not registered as a global resolver.
*
*
* @param classNames
* @throws InstantiationException
* @throws IllegalAccessException
* @throws ClassNotFoundException
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to register the key resolver
*/
public static void registerClassNames(List<String> classNames)
throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
JavaUtils.checkRegisterPermission();
List<KeyResolverSpi> keyResolverList = new ArrayList<>(classNames.size());
for (String className : classNames) {
KeyResolverSpi keyResolverSpi = (KeyResolverSpi)
JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class));
keyResolverList.add(keyResolverSpi);
}
resolverList.addAll(keyResolverList);
}
/**
* This method registers the default resolvers.
*/
public static void registerDefaultResolvers() {
// Add a guard so that we don't repeatedly add the default resolvers
if (defaultResolversAdded.compareAndSet(false, true)) {
List<KeyResolverSpi> keyResolverList = new ArrayList<>();
keyResolverList.add(new RSAKeyValueResolver());
keyResolverList.add(new DSAKeyValueResolver());
keyResolverList.add(new X509CertificateResolver());
keyResolverList.add(new X509SKIResolver());
keyResolverList.add(new RetrievalMethodResolver());
keyResolverList.add(new X509SubjectNameResolver());
keyResolverList.add(new X509IssuerSerialResolver());
keyResolverList.add(new DEREncodedKeyValueResolver());
keyResolverList.add(new KeyInfoReferenceResolver());
keyResolverList.add(new X509DigestResolver());
keyResolverList.add(new ECKeyValueResolver());
resolverList.addAll(keyResolverList);
}
}
/**
* Iterate over the KeyResolverSpi instances
*/
static class ResolverIterator implements Iterator<KeyResolverSpi> {
private List<KeyResolverSpi> res;
private Iterator<KeyResolverSpi> it;
public ResolverIterator(List<KeyResolverSpi> list) {
res = list;
it = res.iterator();
}
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public KeyResolverSpi next() {
KeyResolverSpi resolver = it.next();
if (resolver == null) {
throw new RuntimeException("utils.resolver.noClass");
}
return resolver;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Can't remove resolvers using the iterator");
}
}
public static Iterator<KeyResolverSpi> iterator() {
return new ResolverIterator(resolverList);
}
}

View file

@ -0,0 +1,95 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
public class KeyResolverException extends XMLSecurityException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor KeyResolverException
*
*/
public KeyResolverException() {
super();
}
public KeyResolverException(Exception ex) {
super(ex);
}
/**
* Constructor KeyResolverException
*
* @param msgID
*/
public KeyResolverException(String msgID) {
super(msgID);
}
/**
* Constructor KeyResolverException
*
* @param msgID
* @param exArgs
*/
public KeyResolverException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor KeyResolverException
*
* @param originalException
* @param msgID
*/
public KeyResolverException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public KeyResolverException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor KeyResolverException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public KeyResolverException(Exception originalException, String msgID, Object[] exArgs) {
super(originalException, msgID, exArgs);
}
@Deprecated
public KeyResolverException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,222 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* This class is an abstract class to resolve a Key of some kind given a KeyInfo element.
*
* If you want the your KeyResolver, at firstly you must extend this class, and register
* as following in config.xml
* <PRE>
* &lt;KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
* JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
* </PRE>
*
* Extensions of this class must be thread-safe.
*/
public abstract class KeyResolverSpi {
/**
* This method returns whether the KeyResolverSpi is able to perform the requested action.
*
* @param element
* @param baseURI
* @param storage
* @return whether the KeyResolverSpi is able to perform the requested action.
*/
protected abstract boolean engineCanResolve(Element element, String baseURI, StorageResolver storage);
/**
* Method engineResolvePublicKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved public key from the registered from the element.
*
* @throws KeyResolverException
*/
protected abstract PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException;
/**
* Method engineLookupAndResolvePublicKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved public key from the registered from the element.
*
* @throws KeyResolverException
*/
public PublicKey engineLookupAndResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (!engineCanResolve(element, baseURI, storage)) {
return null;
}
return engineResolvePublicKey(element, baseURI, storage, secureValidation);
}
/**
* Method engineResolveCertificate
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved X509Certificate key from the registered from the elements
*
* @throws KeyResolverException
*/
protected abstract X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException;
/**
* Method engineLookupResolveX509Certificate
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved X509Certificate key from the registered from the elements
*
* @throws KeyResolverException
*/
public X509Certificate engineLookupResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (!engineCanResolve(element, baseURI, storage)) {
return null;
}
return engineResolveX509Certificate(element, baseURI, storage, secureValidation);
}
/**
* Method engineResolveSecretKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved SecretKey key from the registered from the elements
*
* @throws KeyResolverException
*/
protected abstract SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException;
/**
* Method engineLookupAndResolveSecretKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved SecretKey key from the registered from the elements
*
* @throws KeyResolverException
*/
public SecretKey engineLookupAndResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (!engineCanResolve(element, baseURI, storage)) {
return null;
}
return engineResolveSecretKey(element, baseURI, storage, secureValidation);
}
/**
* Method engineResolvePrivateKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved PrivateKey key from the registered from the elements
*
* @throws KeyResolverException
*/
protected abstract PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException;
/**
* Method engineLookupAndResolvePrivateKey
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return resolved PrivateKey key from the registered from the elements
*
* @throws KeyResolverException
*/
public PrivateKey engineLookupAndResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (!engineCanResolve(element, baseURI, storage)) {
return null;
}
return engineResolvePrivateKey(element, baseURI, storage, secureValidation);
}
/**
* Parses a byte array and returns the parsed Element.
*
* @param bytes
* @return the Document Element after parsing bytes
* @throws KeyResolverException if something goes wrong
*/
protected static Element getDocFromBytes(byte[] bytes, boolean secureValidation) throws KeyResolverException {
try (InputStream is = new ByteArrayInputStream(bytes)) {
Document doc = XMLUtils.read(is, secureValidation);
return doc.getDocumentElement();
} catch (XMLParserException ex) {
throw new KeyResolverException(ex);
} catch (IOException ex) {
throw new KeyResolverException(ex);
}
}
}

View file

@ -0,0 +1,99 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
/**
* KeyResolverSpi implementation which resolves public keys from a
* {@code dsig11:DEREncodedKeyValue} element.
*
*/
public class DEREncodedKeyValueResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(DEREncodedKeyValueResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
try {
DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI);
return derKeyValue.getPublicKey();
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected SecretKey engineResolveSecretKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,110 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
public class DSAKeyValueResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(DSAKeyValueResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE)
|| XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
if (element == null) {
return null;
}
Element dsaKeyElement = null;
boolean isKeyValue =
XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
if (isKeyValue) {
dsaKeyElement =
XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
} else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) {
// this trick is needed to allow the RetrievalMethodResolver to eat a
// ds:DSAKeyValue directly (without KeyValue)
dsaKeyElement = element;
}
if (dsaKeyElement == null) {
return null;
}
try {
DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, baseURI);
PublicKey pk = dsaKeyValue.getPublicKey();
return pk;
} catch (XMLSecurityException ex) {
LOG.debug(ex.getMessage(), ex);
//do nothing
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,108 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.ECKeyValue;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
public class ECKeyValueResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(ECKeyValueResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE)
|| XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_ECKEYVALUE);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
if (element == null) {
return null;
}
Element ecKeyElement = null;
boolean isKeyValue =
XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
if (isKeyValue) {
ecKeyElement =
XMLUtils.selectDs11Node(element.getFirstChild(), Constants._TAG_ECKEYVALUE, 0);
} else if (XMLUtils.elementIsInSignature11Space(element, Constants._TAG_ECKEYVALUE)) {
// this trick is needed to allow the RetrievalMethodResolver to eat a
// ds:ECKeyValue directly (without KeyValue)
ecKeyElement = element;
}
if (ecKeyElement == null) {
return null;
}
try {
ECKeyValue ecKeyValue = new ECKeyValue(ecKeyElement, baseURI);
return ecKeyValue.getPublicKey();
} catch (XMLSecurityException ex) {
LOG.debug(ex.getMessage(), ex);
//do nothing
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,242 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import javax.crypto.SecretKey;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a
* {@code dsig11:KeyInfoReference} element.
*
*/
public class KeyInfoReferenceResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyInfoReferenceResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
try {
KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation);
if (referent != null) {
return referent.getPublicKey();
}
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
try {
KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation);
if (referent != null) {
return referent.getX509Certificate();
}
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
}
return null;
}
/** {@inheritDoc} */
@Override
protected SecretKey engineResolveSecretKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
try {
KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation);
if (referent != null) {
return referent.getSecretKey();
}
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
}
return null;
}
/** {@inheritDoc} */
@Override
public PrivateKey engineResolvePrivateKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
try {
KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation);
if (referent != null) {
return referent.getPrivateKey();
}
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
}
return null;
}
/**
* Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance.
*
* @param element
* @param baseURI
* @param storage
* @param secureValidation
* @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved
* @throws XMLSecurityException
*/
private KeyInfo resolveReferentKeyInfo(Element element, String baseURI,
StorageResolver storage, boolean secureValidation) throws XMLSecurityException {
KeyInfoReference reference = new KeyInfoReference(element, baseURI);
Attr uriAttr = reference.getURIAttr();
XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation);
Element referentElement = null;
try {
referentElement = obtainReferenceElement(resource, secureValidation);
} catch (Exception e) {
LOG.debug("XMLSecurityException", e);
return null;
}
if (referentElement == null) {
LOG.debug("De-reference of KeyInfoReference URI returned null: {}", uriAttr.getValue());
return null;
}
validateReference(referentElement, secureValidation);
KeyInfo referent = new KeyInfo(referentElement, baseURI);
referent.setSecureValidation(secureValidation);
referent.addStorageResolver(storage);
return referent;
}
/**
* Validate the Element referred to by the KeyInfoReference.
*
* @param referentElement
* @param secureValidation
*
* @throws XMLSecurityException
*/
private void validateReference(Element referentElement, boolean secureValidation) throws XMLSecurityException {
if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) {
Object[] exArgs = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) };
throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs);
}
KeyInfo referent = new KeyInfo(referentElement, "");
if (referent.containsKeyInfoReference() || referent.containsRetrievalMethod()) {
if (secureValidation) {
throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure");
} else {
// Don't support chains of references at this time. If do support in the future, this is where the code
// would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic
// to implement, and/or very expensive given remote URI references.
throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure");
}
}
}
/**
* Resolve the XML signature input represented by the specified URI.
*
* @param uri
* @param baseURI
* @param secureValidation
* @return the XML signature input represented by the specified URI.
* @throws XMLSecurityException
*/
private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation)
throws XMLSecurityException {
ResourceResolverContext resContext = new ResourceResolverContext(uri, baseURI, secureValidation);
return ResourceResolver.resolve(resContext);
}
/**
* Resolve the Element effectively represented by the XML signature input source.
*
* @param resource
* @param secureValidation
* @return the Element effectively represented by the XML signature input source.
* @throws CanonicalizationException
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @throws KeyResolverException
*/
private Element obtainReferenceElement(XMLSignatureInput resource, boolean secureValidation)
throws CanonicalizationException, ParserConfigurationException,
IOException, SAXException, KeyResolverException {
Element e;
if (resource.isElement()) {
e = (Element) resource.getSubNode();
} else if (resource.isNodeSet()) {
LOG.debug("De-reference of KeyInfoReference returned an unsupported NodeSet");
return null;
} else {
// Retrieved resource is a byte stream
byte[] inputBytes = resource.getBytes();
e = getDocFromBytes(inputBytes, secureValidation);
}
return e;
}
}

View file

@ -0,0 +1,332 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
/**
* Resolves a PrivateKey within a KeyStore based on the KeyInfo hints.
* For X509Data hints, the certificate associated with the private key entry must match.
* For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore.
*/
public class PrivateKeyResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(PrivateKeyResolver.class);
private final KeyStore keyStore;
private final char[] password;
/**
* Constructor.
*/
public PrivateKeyResolver(KeyStore keyStore, char[] password) {
this.keyStore = keyStore;
this.password = password;
}
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)
|| XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
public PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
PrivateKey privKey = resolveX509Data(element, baseURI);
if (privKey != null) {
return privKey;
}
} else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
LOG.debug("Can I resolve KeyName?");
String keyName = element.getFirstChild().getNodeValue();
try {
Key key = keyStore.getKey(keyName, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
} catch (Exception e) {
LOG.debug("Cannot recover the key", e);
}
}
return null;
}
private PrivateKey resolveX509Data(Element element, String baseURI) {
LOG.debug("Can I resolve X509Data?");
try {
X509Data x509Data = new X509Data(element, baseURI);
int len = x509Data.lengthSKI();
for (int i = 0; i < len; i++) {
XMLX509SKI x509SKI = x509Data.itemSKI(i);
PrivateKey privKey = resolveX509SKI(x509SKI);
if (privKey != null) {
return privKey;
}
}
len = x509Data.lengthIssuerSerial();
for (int i = 0; i < len; i++) {
XMLX509IssuerSerial x509Serial = x509Data.itemIssuerSerial(i);
PrivateKey privKey = resolveX509IssuerSerial(x509Serial);
if (privKey != null) {
return privKey;
}
}
len = x509Data.lengthSubjectName();
for (int i = 0; i < len; i++) {
XMLX509SubjectName x509SubjectName = x509Data.itemSubjectName(i);
PrivateKey privKey = resolveX509SubjectName(x509SubjectName);
if (privKey != null) {
return privKey;
}
}
len = x509Data.lengthCertificate();
for (int i = 0; i < len; i++) {
XMLX509Certificate x509Cert = x509Data.itemCertificate(i);
PrivateKey privKey = resolveX509Certificate(x509Cert);
if (privKey != null) {
return privKey;
}
}
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
} catch (KeyStoreException e) {
LOG.debug("KeyStoreException", e);
}
return null;
}
/*
* Search for a private key entry in the KeyStore with the same Subject Key Identifier
*/
private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException {
LOG.debug("Can I resolve X509SKI?");
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStore.isKeyEntry(alias)) {
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);
if (certSKI.equals(x509SKI)) {
LOG.debug("match !!! ");
try {
Key key = keyStore.getKey(alias, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
} catch (Exception e) {
LOG.debug("Cannot recover the key", e);
// Keep searching
}
}
}
}
}
return null;
}
/*
* Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair.
*/
private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException {
LOG.debug("Can I resolve X509IssuerSerial?");
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStore.isKeyEntry(alias)) {
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
XMLX509IssuerSerial certSerial =
new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert);
if (certSerial.equals(x509Serial)) {
LOG.debug("match !!! ");
try {
Key key = keyStore.getKey(alias, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
} catch (Exception e) {
LOG.debug("Cannot recover the key", e);
// Keep searching
}
}
}
}
}
return null;
}
/*
* Search for a private key entry in the KeyStore with the same Subject Name.
*/
private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException {
LOG.debug("Can I resolve X509SubjectName?");
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStore.isKeyEntry(alias)) {
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
XMLX509SubjectName certSN =
new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert);
if (certSN.equals(x509SubjectName)) {
LOG.debug("match !!! ");
try {
Key key = keyStore.getKey(alias, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
} catch (Exception e) {
LOG.debug("Cannot recover the key", e);
// Keep searching
}
}
}
}
}
return null;
}
/*
* Search for a private key entry in the KeyStore with the same Certificate.
*/
private PrivateKey resolveX509Certificate(
XMLX509Certificate x509Cert
) throws XMLSecurityException, KeyStoreException {
LOG.debug("Can I resolve X509Certificate?");
byte[] x509CertBytes = x509Cert.getCertificateBytes();
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStore.isKeyEntry(alias)) {
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
byte[] certBytes = null;
try {
certBytes = cert.getEncoded();
} catch (CertificateEncodingException e1) {
LOG.debug("Cannot recover the key", e1);
}
if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) {
LOG.debug("match !!! ");
try {
Key key = keyStore.getKey(alias, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
}
catch (Exception e) {
LOG.debug("Cannot recover the key", e);
// Keep searching
}
}
}
}
}
return null;
}
}

View file

@ -0,0 +1,109 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.RSAKeyValue;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
public class RSAKeyValueResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(RSAKeyValueResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE)
|| XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
if (element == null) {
return null;
}
LOG.debug("Can I resolve {}", element.getTagName());
boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE);
Element rsaKeyElement = null;
if (isKeyValue) {
rsaKeyElement =
XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
} else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) {
// this trick is needed to allow the RetrievalMethodResolver to eat a
// ds:RSAKeyValue directly (without KeyValue)
rsaKeyElement = element;
}
if (rsaKeyElement == null) {
return null;
}
try {
RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, baseURI);
return rsaKeyValue.getPublicKey();
} catch (XMLSecurityException ex) {
LOG.debug("XMLSecurityException", ex);
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,314 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.RetrievalMethod;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* The RetrievalMethodResolver can retrieve public keys and certificates from
* other locations. The location is specified using the ds:RetrievalMethod
* element which points to the location. This includes the handling of raw
* (binary) X.509 certificate which are not encapsulated in an XML structure.
* If the retrieval process encounters an element which the
* RetrievalMethodResolver cannot handle itself, resolving of the extracted
* element is delegated back to the KeyResolver mechanism.
*
*/
public class RetrievalMethodResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(RetrievalMethodResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
try {
// Create a retrieval method over the given element
RetrievalMethod rm = new RetrievalMethod(element, baseURI);
String type = rm.getType();
XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation);
if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
// a raw certificate, direct parsing is done!
X509Certificate cert = getRawCertificate(resource);
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
Element e = obtainReferenceElement(resource, secureValidation);
// Check to make sure that the reference is not to another RetrievalMethod
// which points to this element
if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) {
if (secureValidation) {
if (LOG.isDebugEnabled()) {
String error = "Error: It is forbidden to have one RetrievalMethod "
+ "point to another with secure validation";
LOG.debug(error);
}
return null;
}
RetrievalMethod rm2 = new RetrievalMethod(e, baseURI);
XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation);
Element e2 = obtainReferenceElement(resource2, secureValidation);
if (e2 == element) {
LOG.debug("Error: Can't have RetrievalMethods pointing to each other");
return null;
}
}
return resolveKey(e, baseURI, storage, secureValidation);
} catch (XMLSecurityException ex) {
LOG.debug("XMLSecurityException", ex);
} catch (CertificateException ex) {
LOG.debug("CertificateException", ex);
} catch (IOException ex) {
LOG.debug("IOException", ex);
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation) {
try {
RetrievalMethod rm = new RetrievalMethod(element, baseURI);
String type = rm.getType();
XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation);
if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
return getRawCertificate(resource);
}
Element e = obtainReferenceElement(resource, secureValidation);
// Check to make sure that the reference is not to another RetrievalMethod
// which points to this element
if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) {
if (secureValidation) {
if (LOG.isDebugEnabled()) {
String error = "Error: It is forbidden to have one RetrievalMethod "
+ "point to another with secure validation";
LOG.debug(error);
}
return null;
}
RetrievalMethod rm2 = new RetrievalMethod(e, baseURI);
XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation);
Element e2 = obtainReferenceElement(resource2, secureValidation);
if (e2 == element) {
LOG.debug("Error: Can't have RetrievalMethods pointing to each other");
return null;
}
}
return resolveCertificate(e, baseURI, storage, secureValidation);
} catch (XMLSecurityException ex) {
LOG.debug("XMLSecurityException", ex);
} catch (CertificateException ex) {
LOG.debug("CertificateException", ex);
} catch (IOException ex) {
LOG.debug("IOException", ex);
}
return null;
}
/**
* Retrieves a x509Certificate from the given information
* @param e
* @param baseURI
* @param storage
* @return a x509Certificate from the given information
* @throws KeyResolverException
*/
private static X509Certificate resolveCertificate(
Element e, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
// An element has been provided
if (e != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Now we have a {" + e.getNamespaceURI() + "}"
+ e.getLocalName() + " Element");
}
return KeyResolver.getX509Certificate(e, baseURI, storage, secureValidation);
}
return null;
}
/**
* Retrieves a PublicKey from the given information
* @param e
* @param baseURI
* @param storage
* @param secureValidation
* @return a PublicKey from the given information
* @throws KeyResolverException
*/
private static PublicKey resolveKey(
Element e, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
// An element has been provided
if (e != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Now we have a {" + e.getNamespaceURI() + "}"
+ e.getLocalName() + " Element");
}
return KeyResolver.getPublicKey(e, baseURI, storage, secureValidation);
}
return null;
}
private static Element obtainReferenceElement(XMLSignatureInput resource, boolean secureValidation)
throws CanonicalizationException, XMLParserException, IOException, KeyResolverException {
Element e;
if (resource.isElement()) {
e = (Element) resource.getSubNode();
} else if (resource.isNodeSet()) {
// Retrieved resource is a nodeSet
e = getDocumentElement(resource.getNodeSet());
} else {
// Retrieved resource is an inputStream
byte[] inputBytes = resource.getBytes();
e = getDocFromBytes(inputBytes, secureValidation);
// otherwise, we parse the resource, create an Element and delegate
LOG.debug("we have to parse {} bytes", inputBytes.length);
}
return e;
}
private static X509Certificate getRawCertificate(XMLSignatureInput resource)
throws CanonicalizationException, IOException, CertificateException {
byte[] inputBytes = resource.getBytes();
// if the resource stores a raw certificate, we have to handle it
CertificateFactory certFact =
CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
try (InputStream is = new ByteArrayInputStream(inputBytes)) {
return (X509Certificate) certFact.generateCertificate(is);
}
}
/**
* Resolves the input from the given retrieval method
* @return the input from the given retrieval method
* @throws XMLSecurityException
*/
private static XMLSignatureInput resolveInput(
RetrievalMethod rm, String baseURI, boolean secureValidation
) throws XMLSecurityException {
Attr uri = rm.getURIAttr();
// Apply the transforms
Transforms transforms = rm.getTransforms();
ResourceResolverContext resContext = new ResourceResolverContext(uri, baseURI, secureValidation);
XMLSignatureInput resource = ResourceResolver.resolve(resContext);
if (transforms != null) {
LOG.debug("We have Transforms");
resource = transforms.performTransforms(resource);
}
return resource;
}
/** {@inheritDoc} */
@Override
public javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
private static Element getDocumentElement(Set<Node> set) {
Element e = null;
for (Node currentNode : set) {
if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
e = (Element) currentNode;
break;
}
}
List<Node> parents = new ArrayList<>();
// Obtain all the parents of the element
while (e != null) {
parents.add(e);
Node n = e.getParentNode();
if (n == null || Node.ELEMENT_NODE != n.getNodeType()) {
break;
}
e = (Element) n;
}
// Visit them in reverse order.
ListIterator<Node> it2 = parents.listIterator(parents.size()-1);
Element ele = null;
while (it2.hasPrevious()) {
ele = (Element) it2.previous();
if (set.contains(ele)) {
return ele;
}
}
return null;
}
}

View file

@ -0,0 +1,112 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
/**
* Resolves a SecretKey within a KeyStore based on the KeyName.
* The KeyName is the key entry alias within the KeyStore.
*/
public class SecretKeyResolver extends KeyResolverSpi
{
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(SecretKeyResolver.class);
private final KeyStore keyStore;
private final char[] password;
/**
* Constructor.
*/
public SecretKeyResolver(KeyStore keyStore, char[] password) {
this.keyStore = keyStore;
this.password = password;
}
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
LOG.debug("Can I resolve {}?", element.getTagName());
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
String keyName = element.getFirstChild().getNodeValue();
try {
Key key = keyStore.getKey(keyName, password);
if (key instanceof SecretKey) {
return (SecretKey) key;
}
} catch (Exception e) {
LOG.debug("Cannot recover the key", e);
}
}
LOG.debug("I can't");
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,143 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
/**
* Resolves a single Key based on the KeyName.
*/
public class SingleKeyResolver extends KeyResolverSpi {
private final String keyName;
private final PublicKey publicKey;
private final PrivateKey privateKey;
private final SecretKey secretKey;
/**
* Constructor.
* @param keyName
* @param publicKey
*/
public SingleKeyResolver(String keyName, PublicKey publicKey) {
this.keyName = keyName;
this.publicKey = publicKey;
privateKey = null;
secretKey = null;
}
/**
* Constructor.
* @param keyName
* @param privateKey
*/
public SingleKeyResolver(String keyName, PrivateKey privateKey) {
this.keyName = keyName;
this.privateKey = privateKey;
publicKey = null;
secretKey = null;
}
/**
* Constructor.
* @param keyName
* @param secretKey
*/
public SingleKeyResolver(String keyName, SecretKey secretKey) {
this.keyName = keyName;
this.secretKey = secretKey;
publicKey = null;
privateKey = null;
}
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (publicKey != null) {
String name = element.getFirstChild().getNodeValue();
if (keyName.equals(name)) {
return publicKey;
}
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
return null;
}
/** {@inheritDoc} */
@Override
protected SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (secretKey != null) {
String name = element.getFirstChild().getNodeValue();
if (keyName.equals(name)) {
return secretKey;
}
}
return null;
}
/** {@inheritDoc} */
@Override
public PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
if (privateKey != null) {
String name = element.getFirstChild().getNodeValue();
if (keyName.equals(name)) {
return privateKey;
}
}
return null;
}
}

View file

@ -0,0 +1,118 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
/**
* Resolves Certificates which are directly contained inside a
* {@code ds:X509Certificate} Element.
*
*/
public class X509CertificateResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509CertificateResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return Constants.SignatureSpecNS.equals(element.getNamespaceURI());
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
X509Certificate cert =
this.engineResolveX509Certificate(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
try {
Element[] els =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE);
if (els == null || els.length == 0) {
Element el =
XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0);
if (el != null) {
return engineResolveX509Certificate(el, baseURI, storage, secureValidation);
}
return null;
}
// populate Object array
for (Element el : els) {
XMLX509Certificate xmlCert = new XMLX509Certificate(el, baseURI);
X509Certificate cert = xmlCert.getX509Certificate();
if (cert != null) {
return cert;
}
}
return null;
} catch (XMLSecurityException ex) {
LOG.debug("Security Exception", ex);
throw new KeyResolverException(ex);
}
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,177 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import javax.crypto.SecretKey;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
/**
* KeyResolverSpi implementation which resolves public keys and X.509 certificates from a
* {@code dsig11:X509Digest} element.
*
*/
public class X509DigestResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509DigestResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
try {
X509Data x509Data = new X509Data(element, baseURI);
return x509Data.containsDigest();
} catch (XMLSecurityException e) {
return false;
}
} else {
return false;
}
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
X509Certificate cert = this.engineResolveX509Certificate(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
try {
return resolveCertificate(element, baseURI, storage);
} catch (XMLSecurityException e) {
LOG.debug("XMLSecurityException", e);
}
return null;
}
/** {@inheritDoc} */
@Override
protected SecretKey engineResolveSecretKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation)
throws KeyResolverException {
return null;
}
/**
* Resolves from the storage resolver the actual certificate represented by the digest.
*
* @param element
* @param baseURI
* @param storage
* @return the certificate represented by the digest.
* @throws XMLSecurityException
*/
private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage)
throws XMLSecurityException {
XMLX509Digest x509Digests[] = null;
Element x509childNodes[] = XMLUtils.selectDs11Nodes(element.getFirstChild(), Constants._TAG_X509DIGEST);
if (x509childNodes == null || x509childNodes.length <= 0) {
return null;
}
try {
checkStorage(storage);
x509Digests = new XMLX509Digest[x509childNodes.length];
for (int i = 0; i < x509childNodes.length; i++) {
x509Digests[i] = new XMLX509Digest(x509childNodes[i], baseURI);
}
Iterator<Certificate> storageIterator = storage.getIterator();
while (storageIterator.hasNext()) {
X509Certificate cert = (X509Certificate) storageIterator.next();
for (XMLX509Digest keyInfoDigest : x509Digests) {
byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm());
if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) {
LOG.debug("Found certificate with: {}", cert.getSubjectX500Principal().getName());
return cert;
}
}
}
} catch (XMLSecurityException ex) {
throw new KeyResolverException(ex);
}
return null;
}
/**
* Method checkSrorage
*
* @param storage
* @throws KeyResolverException
*/
private void checkStorage(StorageResolver storage) throws KeyResolverException {
if (storage == null) {
Object[] exArgs = { Constants._TAG_X509DIGEST };
KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
LOG.debug("", ex);
throw ex;
}
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,150 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
public class X509IssuerSerialResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509IssuerSerialResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
try {
X509Data x509Data = new X509Data(element, baseURI);
return x509Data.containsIssuerSerial();
} catch (XMLSecurityException e) {
return false;
}
} else {
return false;
}
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
X509Certificate cert =
this.engineResolveX509Certificate(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
X509Data x509data = null;
try {
x509data = new X509Data(element, baseURI);
} catch (XMLSecurityException ex) {
return null;
}
if (!x509data.containsIssuerSerial()) {
return null;
}
try {
if (storage == null) {
Object[] exArgs = { Constants._TAG_X509ISSUERSERIAL };
KeyResolverException ex =
new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
LOG.debug("", ex);
throw ex;
}
int noOfISS = x509data.lengthIssuerSerial();
Iterator<Certificate> storageIterator = storage.getIterator();
while (storageIterator.hasNext()) {
X509Certificate cert = (X509Certificate)storageIterator.next();
XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert);
LOG.debug("Found Certificate Issuer: {}", certSerial.getIssuerName());
LOG.debug("Found Certificate Serial: {}", certSerial.getSerialNumber().toString());
for (int i = 0; i < noOfISS; i++) {
XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i);
LOG.debug("Found Element Issuer: {}", xmliss.getIssuerName());
LOG.debug("Found Element Serial: {}", xmliss.getSerialNumber().toString());
if (certSerial.equals(xmliss)) {
LOG.debug("match !!! ");
return cert;
}
LOG.debug("no match...");
}
}
return null;
} catch (XMLSecurityException ex) {
LOG.debug("XMLSecurityException", ex);
throw new KeyResolverException(ex);
}
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,135 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
public class X509SKIResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SKIResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
return false;
}
Element[] x509childNodes =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);
return x509childNodes != null && x509childNodes.length > 0;
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
X509Certificate cert =
this.engineResolveX509Certificate(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
Element[] x509childNodes =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);
if (!(x509childNodes != null && x509childNodes.length > 0)) {
return null;
}
try {
if (storage == null) {
Object[] exArgs = { Constants._TAG_X509SKI };
KeyResolverException ex =
new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
LOG.debug("", ex);
throw ex;
}
XMLX509SKI[] x509childObject = new XMLX509SKI[x509childNodes.length];
for (int i = 0; i < x509childNodes.length; i++) {
x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI);
}
Iterator<Certificate> storageIterator = storage.getIterator();
while (storageIterator.hasNext()) {
X509Certificate cert = (X509Certificate) storageIterator.next();
XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert);
for (XMLX509SKI childNodeSKI : x509childObject) {
if (certSKI.equals(childNodeSKI)) {
LOG.debug("Return PublicKey from {}", cert.getSubjectX500Principal().getName());
return cert;
}
}
}
} catch (XMLSecurityException ex) {
throw new KeyResolverException(ex);
}
return null;
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,140 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
public class X509SubjectNameResolver extends KeyResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SubjectNameResolver.class);
/** {@inheritDoc} */
@Override
protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
return false;
}
Element[] x509childNodes =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME);
return x509childNodes != null && x509childNodes.length > 0;
}
/** {@inheritDoc} */
@Override
protected PublicKey engineResolvePublicKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
X509Certificate cert =
this.engineResolveX509Certificate(element, baseURI, storage, secureValidation);
if (cert != null) {
return cert.getPublicKey();
}
return null;
}
/** {@inheritDoc} */
@Override
protected X509Certificate engineResolveX509Certificate(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) throws KeyResolverException {
Element[] x509childNodes =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME);
if (!(x509childNodes != null && x509childNodes.length > 0)) {
return null;
}
try {
if (storage == null) {
Object[] exArgs = { Constants._TAG_X509SUBJECTNAME };
KeyResolverException ex =
new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
LOG.debug("", ex);
throw ex;
}
XMLX509SubjectName[] x509childObject = new XMLX509SubjectName[x509childNodes.length];
for (int i = 0; i < x509childNodes.length; i++) {
x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI);
}
Iterator<Certificate> storageIterator = storage.getIterator();
while (storageIterator.hasNext()) {
X509Certificate cert = (X509Certificate) storageIterator.next();
XMLX509SubjectName certSN = new XMLX509SubjectName(element.getOwnerDocument(), cert);
LOG.debug("Found Certificate SN: {}", certSN.getSubjectName());
for (XMLX509SubjectName childSubject : x509childObject) {
LOG.debug("Found Element SN: {}", childSubject.getSubjectName());
if (certSN.equals(childSubject)) {
LOG.debug("match !!! ");
return cert;
}
LOG.debug("no match...");
}
}
return null;
} catch (XMLSecurityException ex) {
LOG.debug("XMLSecurityException", ex);
throw new KeyResolverException(ex);
}
}
/** {@inheritDoc} */
@Override
protected javax.crypto.SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
/** {@inheritDoc} */
@Override
protected PrivateKey engineResolvePrivateKey(
Element element, String baseURI, StorageResolver storage, boolean secureValidation
) {
return null;
}
}

View file

@ -0,0 +1,181 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver;
import com.sun.org.apache.xml.internal.security.keys.storage.implementations.SingleCertificateResolver;
/**
* This class collects customized resolvers for Certificates.
*/
public class StorageResolver {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(StorageResolver.class);
/** Field storageResolvers */
private final List<StorageResolverSpi> storageResolvers = new ArrayList<>();
/**
* Constructor StorageResolver
*
* @param resolver
*/
public StorageResolver(StorageResolverSpi resolver) {
this.add(resolver);
}
/**
* Constructor StorageResolver
*
* @param keyStore
*/
public StorageResolver(KeyStore keyStore) {
this.add(keyStore);
}
/**
* Constructor StorageResolver
*
* @param x509certificate
*/
public StorageResolver(X509Certificate x509certificate) {
this.add(x509certificate);
}
/**
* Method addResolver
*
* @param resolver
*/
public void add(StorageResolverSpi resolver) {
this.storageResolvers.add(resolver);
}
/**
* Method addKeyStore
*
* @param keyStore
*/
public void add(KeyStore keyStore) {
try {
this.add(new KeyStoreResolver(keyStore));
} catch (StorageResolverException ex) {
LOG.error("Could not add KeyStore because of: ", ex);
}
}
/**
* Method addCertificate
*
* @param x509certificate
*/
public void add(X509Certificate x509certificate) {
this.add(new SingleCertificateResolver(x509certificate));
}
/**
* Method getIterator
* @return the iterator for the resolvers.
*/
public Iterator<Certificate> getIterator() {
return new StorageResolverIterator(this.storageResolvers.iterator());
}
/**
* Class StorageResolverIterator
* This iterates over all the Certificates found in all the resolvers.
*/
static class StorageResolverIterator implements Iterator<Certificate> {
/** Field resolvers */
private final Iterator<StorageResolverSpi> resolvers;
/** Field currentResolver */
private Iterator<Certificate> currentResolver;
/**
* Constructor StorageResolverIterator
*
* @param resolvers
*/
public StorageResolverIterator(Iterator<StorageResolverSpi> resolvers) {
this.resolvers = resolvers;
currentResolver = findNextResolver();
}
/** {@inheritDoc} */
@Override
public boolean hasNext() {
if (currentResolver == null) {
return false;
}
if (currentResolver.hasNext()) {
return true;
}
currentResolver = findNextResolver();
return currentResolver != null;
}
/** {@inheritDoc} */
@Override
public Certificate next() {
if (hasNext()) {
return currentResolver.next();
}
throw new NoSuchElementException();
}
/**
* Method remove
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Can't remove keys from KeyStore");
}
// Find the next storage with at least one element and return its Iterator
private Iterator<Certificate> findNextResolver() {
while (resolvers.hasNext()) {
StorageResolverSpi resolverSpi = resolvers.next();
Iterator<Certificate> iter = resolverSpi.getIterator();
if (iter.hasNext()) {
return iter;
}
}
return null;
}
}
}

View file

@ -0,0 +1,96 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
public class StorageResolverException extends XMLSecurityException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor StorageResolverException
*
*/
public StorageResolverException() {
super();
}
public StorageResolverException(Exception ex) {
super(ex);
}
/**
* Constructor StorageResolverException
*
* @param msgID
*/
public StorageResolverException(String msgID) {
super(msgID);
}
/**
* Constructor StorageResolverException
*
* @param msgID
* @param exArgs
*/
public StorageResolverException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor StorageResolverException
*
* @param originalException
* @param msgID
*/
public StorageResolverException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public StorageResolverException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor StorageResolverException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public StorageResolverException(Exception originalException, String msgID, Object[] exArgs) {
super(originalException, msgID, exArgs);
}
@Deprecated
public StorageResolverException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,36 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage;
import java.security.cert.Certificate;
import java.util.Iterator;
public abstract class StorageResolverSpi {
/**
* Method getIterator
*
* @return the iterator for the storage
*/
public abstract Iterator<Certificate> getIterator();
}

View file

@ -0,0 +1,132 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
/**
* Makes the Certificates from a JAVA {@link KeyStore} object available to the
* {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
*/
public class KeyStoreResolver extends StorageResolverSpi {
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyStoreResolver.class);
/** Field keyStore */
private final KeyStore keyStore;
/**
* Constructor KeyStoreResolver
*
* @param keyStore is the keystore which contains the Certificates
* @throws StorageResolverException
*/
public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException {
this.keyStore = keyStore;
// Do a quick check on the keystore
try {
keyStore.aliases();
} catch (KeyStoreException ex) {
throw new StorageResolverException(ex);
}
}
/** {@inheritDoc} */
@Override
public Iterator<Certificate> getIterator() {
return new KeyStoreIterator(this.keyStore);
}
/**
* Class KeyStoreIterator
*/
static class KeyStoreIterator implements Iterator<Certificate> {
private final List<Certificate> certs;
private int i;
/**
* Constructor KeyStoreIterator
*
* @param keyStore
*/
public KeyStoreIterator(KeyStore keyStore) {
List<Certificate> tmpCerts = new ArrayList<>();
try {
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
Certificate cert = keyStore.getCertificate(alias);
if (cert != null) {
tmpCerts.add(cert);
}
}
} catch (KeyStoreException ex) {
LOG.debug("Error reading certificates: {}", ex.getMessage());
}
certs = Collections.unmodifiableList(tmpCerts);
this.i = 0;
}
/** {@inheritDoc} */
@Override
public boolean hasNext() {
return this.i < this.certs.size();
}
/** {@inheritDoc} */
@Override
public Certificate next() {
if (hasNext()) {
return this.certs.get(this.i++);
}
throw new NoSuchElementException();
}
/**
* Method remove
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Can't remove keys from KeyStore");
}
}
}

View file

@ -0,0 +1,98 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
/**
* This {@link StorageResolverSpi} makes a single {@link X509Certificate}
* available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
*/
public class SingleCertificateResolver extends StorageResolverSpi {
/** Field certificate */
private final X509Certificate certificate;
/**
* @param x509cert the single {@link X509Certificate}
*/
public SingleCertificateResolver(X509Certificate x509cert) {
this.certificate = x509cert;
}
/** {@inheritDoc} */
@Override
public Iterator<Certificate> getIterator() {
return new InternalIterator(this.certificate);
}
/**
* Class InternalIterator
*/
static class InternalIterator implements Iterator<Certificate> {
/** Field alreadyReturned */
private boolean alreadyReturned;
/** Field certificate */
private final X509Certificate certificate;
/**
* Constructor InternalIterator
*
* @param x509cert
*/
public InternalIterator(X509Certificate x509cert) {
this.certificate = x509cert;
}
/** {@inheritDoc} */
@Override
public boolean hasNext() {
return !this.alreadyReturned;
}
/** {@inheritDoc} */
@Override
public Certificate next() {
if (this.alreadyReturned) {
throw new NoSuchElementException();
}
this.alreadyReturned = true;
return this.certificate;
}
/**
* Method remove
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Can't remove keys from KeyStore");
}
}
}

View file

@ -0,0 +1,45 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.parser;
import java.io.InputStream;
import org.w3c.dom.Document;
/**
* A interface to allow pluggable ways of parsing an InputStream into a DOM Document.
*/
public interface XMLParser {
/**
* Parses a document from the input stream.
* Caller is responsible for closing the stream.
*
* @param inputStream
* @param disallowDocTypeDeclarations
* @return {@link Document}
* @throws XMLParserException
*/
Document parse(InputStream inputStream, boolean disallowDocTypeDeclarations) throws XMLParserException;
}

View file

@ -0,0 +1,83 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.parser;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
public class XMLParserException extends XMLSecurityException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor XMLParserException
*
*/
public XMLParserException() {
super();
}
/**
* Constructor XMLParserException
*
* @param msgID
*/
public XMLParserException(String msgID) {
super(msgID);
}
/**
* Constructor XMLParserException
*
* @param msgID
* @param exArgs
*/
public XMLParserException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor XMLParserException
*
* @param originalException
* @param msgID
*/
public XMLParserException(Exception originalException, String msgID) {
super(originalException, msgID);
}
/**
* Constructor XMLParserException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public XMLParserException(
Exception originalException, String msgID, Object[] exArgs
) {
super(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,144 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.parser;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.Map;
import java.util.Queue;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
* A default implementation of XMLParser that uses two pools of DocumentBuilders.
*/
public class XMLParserImpl implements XMLParser {
@SuppressWarnings("removal")
private static int parserPoolSize =
AccessController.doPrivileged(
(PrivilegedAction<Integer>) () -> Integer.getInteger("com.sun.org.apache.xml.internal.security.parser.pool-size", 20));
private static final Map<ClassLoader, Queue<DocumentBuilder>> DOCUMENT_BUILDERS =
Collections.synchronizedMap(new WeakHashMap<>());
private static final Map<ClassLoader, Queue<DocumentBuilder>> DOCUMENT_BUILDERS_DISALLOW_DOCTYPE =
Collections.synchronizedMap(new WeakHashMap<>());
@Override
public Document parse(InputStream inputStream, boolean disallowDocTypeDeclarations) throws XMLParserException {
try {
ClassLoader loader = getContextClassLoader();
if (loader == null) {
loader = getClassLoader(XMLUtils.class);
}
// If the ClassLoader is null then just create a DocumentBuilder and use it
if (loader == null) {
DocumentBuilder documentBuilder = createDocumentBuilder(disallowDocTypeDeclarations);
return documentBuilder.parse(inputStream);
}
Queue<DocumentBuilder> queue = getDocumentBuilderQueue(disallowDocTypeDeclarations, loader);
DocumentBuilder documentBuilder = getDocumentBuilder(disallowDocTypeDeclarations, queue);
Document doc = documentBuilder.parse(inputStream);
repoolDocumentBuilder(documentBuilder, queue);
return doc;
} catch (ParserConfigurationException | SAXException | IOException ex) {
throw new XMLParserException(ex, "empty", new Object[] {"Error parsing the inputstream"});
}
}
private static Queue<DocumentBuilder> getDocumentBuilderQueue(boolean disallowDocTypeDeclarations, ClassLoader loader) throws ParserConfigurationException {
Map<ClassLoader, Queue<DocumentBuilder>> docBuilderCache =
disallowDocTypeDeclarations ? DOCUMENT_BUILDERS_DISALLOW_DOCTYPE : DOCUMENT_BUILDERS;
Queue<DocumentBuilder> queue = docBuilderCache.get(loader);
if (queue == null) {
queue = new ArrayBlockingQueue<>(parserPoolSize);
docBuilderCache.put(loader, queue);
}
return queue;
}
private static DocumentBuilder getDocumentBuilder(boolean disallowDocTypeDeclarations, Queue<DocumentBuilder> queue) throws ParserConfigurationException {
DocumentBuilder db = queue.poll();
if (db == null) {
db = createDocumentBuilder(disallowDocTypeDeclarations);
}
return db;
}
private static DocumentBuilder createDocumentBuilder(boolean disallowDocTypeDeclarations) throws ParserConfigurationException {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setNamespaceAware(true);
f.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", disallowDocTypeDeclarations);
return f.newDocumentBuilder();
}
private static void repoolDocumentBuilder(DocumentBuilder db, Queue<DocumentBuilder> queue) {
if (queue != null) {
db.reset();
queue.offer(db);
}
}
@SuppressWarnings("removal")
private static ClassLoader getContextClassLoader() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
return Thread.currentThread().getContextClassLoader();
}
@SuppressWarnings("removal")
private static ClassLoader getClassLoader(final Class<?> clazz) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
});
}
return clazz.getClassLoader();
}
}

View file

@ -0,0 +1,73 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!ELEMENT Configuration (CanonicalizationMethods , TransformAlgorithms , JCEAlgorithmMappings , Log4J , ResourceBundles , UnitTests , ResourceResolvers , KeyResolvers)>
<!ATTLIST Configuration xmlns CDATA #FIXED 'http://www.xmlsecurity.org/NS/#configuration'
target CDATA #IMPLIED>
<!ELEMENT CanonicalizationMethods (CanonicalizationMethod+)>
<!ATTLIST CanonicalizationMethods JAVACLASS CDATA #FIXED 'com.sun.org.apache.xml.internal.security.c14n.Canonicalizer' >
<!ELEMENT CanonicalizationMethod EMPTY>
<!ATTLIST CanonicalizationMethod URI CDATA #REQUIRED
JAVACLASS CDATA #REQUIRED >
<!ELEMENT TransformAlgorithms (TransformAlgorithm+)>
<!ATTLIST TransformAlgorithms JAVACLASS CDATA #FIXED 'com.sun.org.apache.xml.internal.security.transforms.Transform' >
<!ELEMENT TransformAlgorithm EMPTY>
<!ATTLIST TransformAlgorithm URI CDATA #REQUIRED
JAVACLASS CDATA #REQUIRED >
<!ELEMENT JCEAlgorithmMappings (Providers , Algorithms)>
<!ELEMENT Providers (Provider+)>
<!ELEMENT Provider EMPTY>
<!ATTLIST Provider Id ID #REQUIRED
Class CDATA #REQUIRED
Info CDATA #IMPLIED
ProviderURL CDATA #IMPLIED >
<!ELEMENT Algorithms (Algorithm+)>
<!ELEMENT Algorithm (ProviderAlgo+)>
<!ATTLIST Algorithm URI CDATA #REQUIRED
Description CDATA #IMPLIED
AlgorithmClass CDATA #IMPLIED >
<!ELEMENT ProviderAlgo EMPTY>
<!ATTLIST ProviderAlgo ProviderId IDREF #REQUIRED
JCEName CDATA #REQUIRED
JCEAlias CDATA #IMPLIED >
<!ELEMENT Log4J EMPTY>
<!ATTLIST Log4J configFile CDATA 'data/log4j.xml' >
<!ELEMENT ResourceBundles (ResourceBundle+)>
<!ATTLIST ResourceBundles defaultLanguageCode CDATA 'de'
defaultCountryCode CDATA 'DE' >
<!ELEMENT ResourceBundle EMPTY>
<!ATTLIST ResourceBundle LanguageCode CDATA #REQUIRED
CountryCode CDATA #REQUIRED
LOCATION CDATA #REQUIRED >
<!ELEMENT UnitTests (UnitTest+)>
<!ATTLIST UnitTests JAVACLASS CDATA #FIXED 'com.sun.org.apache.xml.internal.security.test.AllTests' >
<!ELEMENT ResourceResolvers (Resolver+)>
<!ELEMENT Resolver EMPTY>
<!ATTLIST Resolver JAVACLASS CDATA #REQUIRED
DESCRIPTION CDATA #IMPLIED >
<!ELEMENT KeyResolvers (KeyResolver+)>
<!ATTLIST KeyResolvers JAVACLASS CDATA #FIXED 'com.sun.org.apache.xml.internal.security.keys.KeyResolver' >
<!ELEMENT KeyResolver EMPTY>
<!ATTLIST KeyResolver URI CDATA #REQUIRED
JAVACLASS CDATA #REQUIRED >
<!ELEMENT UnitTest (#PCDATA)>
<!ATTLIST UnitTest JAVACLASS CDATA #REQUIRED >

View file

@ -0,0 +1,687 @@
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
<!DOCTYPE Configuration SYSTEM "config.dtd">
-->
<!-- This configuration file is used for configuration of the com.sun.org.apache.xml.internal.security package -->
<Configuration target="com.sun.org.apache.xml.internal.security" xmlns="http://www.xmlsecurity.org/NS/#configuration">
<CanonicalizationMethods>
<CanonicalizationMethod URI="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments" />
<CanonicalizationMethod URI="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments" />
<CanonicalizationMethod URI="http://www.w3.org/2001/10/xml-exc-c14n#"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclOmitComments"/>
<CanonicalizationMethod URI="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments"/>
<CanonicalizationMethod URI="http://www.w3.org/2006/12/xml-c14n11"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments"/>
<CanonicalizationMethod URI="http://www.w3.org/2006/12/xml-c14n11#WithComments"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments"/>
<CanonicalizationMethod URI="http://santuario.apache.org/c14n/physical"
JAVACLASS="com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical"/>
</CanonicalizationMethods>
<TransformAlgorithms>
<!-- Base64 -->
<TransformAlgorithm URI="http://www.w3.org/2000/09/xmldsig#base64"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode" />
<!-- c14n omitting comments -->
<TransformAlgorithm URI="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N" />
<!-- c14n with comments -->
<TransformAlgorithm URI="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NWithComments" />
<!-- c14n 1.1 omitting comments -->
<TransformAlgorithm URI="http://www.w3.org/2006/12/xml-c14n11"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N11" />
<!-- c14n 1.1 with comments -->
<TransformAlgorithm URI="http://www.w3.org/2006/12/xml-c14n11#WithComments"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14N11_WithComments" />
<!-- exclusive c14n omitting comments -->
<TransformAlgorithm URI="http://www.w3.org/2001/10/xml-exc-c14n#"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NExclusive" />
<!-- exclusive c14n with comments -->
<TransformAlgorithm URI="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformC14NExclusiveWithComments" />
<!-- XPath transform -->
<TransformAlgorithm URI="http://www.w3.org/TR/1999/REC-xpath-19991116"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath" />
<!-- enveloped signature -->
<TransformAlgorithm URI="http://www.w3.org/2000/09/xmldsig#enveloped-signature"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformEnvelopedSignature" />
<!-- XSLT -->
<TransformAlgorithm URI="http://www.w3.org/TR/1999/REC-xslt-19991116"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT" />
<!-- XPath version 2 -->
<TransformAlgorithm URI="http://www.w3.org/2002/06/xmldsig-filter2"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter" />
</TransformAlgorithms>
<SignatureAlgorithms>
<SignatureAlgorithm URI="http://www.w3.org/2000/09/xmldsig#dsa-sha1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureDSA" />
<SignatureAlgorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA1" />
<SignatureAlgorithm URI="http://www.w3.org/2000/09/xmldsig#hmac-sha1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacSHA1" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-md5"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSAMD5" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSARIPEMD160" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha224"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA224" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA256" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA384" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA1MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA224MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA256MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA384MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-224-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_224MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-256-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_256MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-384-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_384MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-512-rsa-MGF1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA3_512MGF1" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA1" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA224" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA256" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA384" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA512" />
<SignatureAlgorithm URI="http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSARIPEMD160" />
<SignatureAlgorithm URI="http://www.w3.org/2021/04/xmldsig-more#eddsa-ed25519"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureEDDSA$SignatureEd25519" />
<SignatureAlgorithm URI="http://www.w3.org/2021/04/xmldsig-more#eddsa-ed448"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureEDDSA$SignatureEd448" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacMD5" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacRIPEMD160" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacSHA256" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacSHA384" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacSHA512" />
</SignatureAlgorithms>
<JCEAlgorithmMappings>
<Algorithms>
<!-- MessageDigest Algorithms -->
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#md5"
Description="MD5 message digest from RFC 1321"
AlgorithmClass="MessageDigest"
RequirementLevel="NOT RECOMMENDED"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="MD5"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#ripemd160"
Description="RIPEMD-160 message digest"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="RIPEMD160"/>
<Algorithm URI="http://www.w3.org/2000/09/xmldsig#sha1"
Description="SHA-1 message digest"
AlgorithmClass="MessageDigest"
RequirementLevel="REQUIRED"
JCEName="SHA-1"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#sha224"
Description="SHA-224 message digest"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="SHA-224"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#sha256"
Description="SHA-1 message digest with 256 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="RECOMMENDED"
JCEName="SHA-256"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#sha384"
Description="SHA message digest with 384 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="SHA-384"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#sha512"
Description="SHA-1 message digest with 512 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="SHA-512"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#whirlpool"
Description="WHIRLPOOL message digest"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="WHIRLPOOL"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-224"
Description="SHA-3 message digest with 224 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="SHA3-224"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-256"
Description="SHA-3 message digest with 256 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="SHA3-256"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-384"
Description="SHA-3 message digest with 384 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="SHA3-384"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha3-512"
Description="SHA-3 message digest with 512 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
JCEName="SHA3-512"/>
<!-- Signature Algorithms -->
<Algorithm URI="http://www.w3.org/2000/09/xmldsig#dsa-sha1"
Description="Digital Signature Algorithm with SHA-1 message digest"
AlgorithmClass="Signature"
RequirementLevel="REQUIRED"
RequiredKey="DSA"
JCEName="SHA1withDSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-md5"
Description="RSA Signature with MD5 message digest"
AlgorithmClass="Signature"
RequirementLevel="NOT RECOMMENDED"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="RSA"
JCEName="MD5withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"
Description="RSA Signature with RIPEMD-160 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="RSA"
JCEName="RIPEMD160withRSA"/>
<Algorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"
Description="RSA Signature with SHA-1 message digest"
AlgorithmClass="Signature"
RequirementLevel="RECOMMENDED"
RequiredKey="RSA"
JCEName="SHA1withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha224"
Description="RSA Signature with SHA-224 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="RSA"
JCEName="SHA224withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
Description="RSA Signature with SHA-256 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="RSA"
JCEName="SHA256withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
Description="RSA Signature with SHA-384 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="RSA"
JCEName="SHA384withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
Description="RSA Signature with SHA-512 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="RSA"
JCEName="SHA512withRSA"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha1-rsa-MGF1"
Description="RSASSA-PSS Signature with SHA-1 message digest"
AlgorithmClass="Signature"
RequirementLevel="RECOMMENDED"
RequiredKey="RSA"
JCEName="SHA1withRSAandMGF1"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha224-rsa-MGF1"
Description="RSASSA-PSS Signature with SHA-224 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
RequiredKey="RSA"
JCEName="SHA224withRSAandMGF1"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1"
Description="RSASSA-PSS Signature with SHA-256 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
RequiredKey="RSA"
JCEName="SHA256withRSAandMGF1"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha384-rsa-MGF1"
Description="RSASSA-PSS Signature with SHA-384 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
RequiredKey="RSA"
JCEName="SHA384withRSAandMGF1"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#sha512-rsa-MGF1"
Description="RSASSA-PSS Signature with SHA-512 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc6931.txt"
RequiredKey="RSA"
JCEName="SHA512withRSAandMGF1"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
Description="ECDSA Signature with SHA-1 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="EC"
JCEName="SHA1withECDSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224"
Description="ECDSA Signature with SHA-224 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="EC"
JCEName="SHA224withECDSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
Description="ECDSA Signature with SHA-256 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="EC"
JCEName="SHA256withECDSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
Description="ECDSA Signature with SHA-384 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="EC"
JCEName="SHA384withECDSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
Description="ECDSA Signature with SHA-512 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
RequiredKey="EC"
JCEName="SHA512withECDSA"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160"
Description="ECDSA Signature with RIPEMD-160 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
SpecificationURL="https://tools.ietf.org/html/rfc6931"
RequiredKey="EC"
JCEName="RIPEMD160withECDSA"/>
<!-- MAC Algorithms -->
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
Description="Message Authentication code using MD5"
AlgorithmClass="Mac"
RequirementLevel="NOT RECOMMENDED"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
KeyLength="0"
RequiredKey=""
JCEName="HmacMD5"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"
Description="Message Authentication code using RIPEMD-160"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
KeyLength="0"
RequiredKey=""
JCEName="HMACRIPEMD160"/>
<Algorithm URI="http://www.w3.org/2000/09/xmldsig#hmac-sha1"
Description="Message Authentication code using SHA1"
AlgorithmClass="Mac"
RequirementLevel="REQUIRED"
KeyLength="0"
RequiredKey=""
JCEName="HmacSHA1"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha224"
Description="Message Authentication code using SHA-224"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
KeyLength="0"
RequiredKey=""
JCEName="HmacSHA224"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"
Description="Message Authentication code using SHA-256"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
KeyLength="0"
RequiredKey=""
JCEName="HmacSHA256"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"
Description="Message Authentication code using SHA-384"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
KeyLength="0"
RequiredKey=""
JCEName="HmacSHA384"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"
Description="Message Authentication code using SHA-512"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
KeyLength="0"
RequiredKey=""
JCEName="HmacSHA512"/>
<!-- Block encryption Algorithms -->
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"
Description="Block encryption using Triple-DES"
AlgorithmClass="BlockEncryption"
RequirementLevel="REQUIRED"
KeyLength="192"
IVLength="64"
RequiredKey="DESede"
JCEName="DESede/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#aes128-cbc"
Description="Block encryption using AES with a key length of 128 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="REQUIRED"
KeyLength="128"
IVLength="128"
RequiredKey="AES"
JCEName="AES/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#aes192-cbc"
Description="Block encryption using AES with a key length of 192 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="192"
IVLength="128"
RequiredKey="AES"
JCEName="AES/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#aes256-cbc"
Description="Block encryption using AES with a key length of 256 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="REQUIRED"
KeyLength="256"
IVLength="128"
RequiredKey="AES"
JCEName="AES/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2009/xmlenc11#aes128-gcm"
Description="Block encryption using AES with a key length of 128 bit in GCM"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="128"
IVLength="96"
RequiredKey="AES"
JCEName="AES/GCM/NoPadding"/>
<Algorithm URI="http://www.w3.org/2009/xmlenc11#aes192-gcm"
Description="Block encryption using AES with a key length of 192 bit in GCM"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="192"
IVLength="96"
RequiredKey="AES"
JCEName="AES/GCM/NoPadding"/>
<Algorithm URI="http://www.w3.org/2009/xmlenc11#aes256-gcm"
Description="Block encryption using AES with a key length of 256 bit in GCM"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="256"
IVLength="96"
RequiredKey="AES"
JCEName="AES/GCM/NoPadding"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#seed128-cbc"
Description="Block encryption using SEED with a key length of 128 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="128"
IVLength="128"
RequiredKey="SEED"
JCEName="SEED/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#camellia128-cbc"
Description="Block encryption using Camellia with a key length of 128 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="128"
IVLength="128"
RequiredKey="Camellia"
JCEName="Camellia/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#camellia192-cbc"
Description="Block encryption using Camellia with a key length of 192 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="192"
IVLength="128"
RequiredKey="Camellia"
JCEName="Camellia/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#camellia256-cbc"
Description="Block encryption using Camellia with a key length of 256 bit"
AlgorithmClass="BlockEncryption"
RequirementLevel="OPTIONAL"
KeyLength="256"
IVLength="128"
RequiredKey="Camellia"
JCEName="Camellia/CBC/ISO10126Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"
Description="Key Transport RSA-v1.5"
AlgorithmClass="KeyTransport"
RequirementLevel="REQUIRED"
RequiredKey="RSA"
JCEName="RSA/ECB/PKCS1Padding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"
Description="Key Transport RSA-OAEP"
AlgorithmClass="KeyTransport"
RequirementLevel="REQUIRED"
RequiredKey="RSA"
JCEName="RSA/ECB/OAEPPadding"/>
<Algorithm URI="http://www.w3.org/2009/xmlenc11#rsa-oaep"
Description="Key Transport RSA-OAEP"
AlgorithmClass="KeyTransport"
RequirementLevel="OPTIONAL"
RequiredKey="RSA"
JCEName="RSA/ECB/OAEPPadding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#dh"
Description="Key Agreement Diffie-Hellman"
AlgorithmClass="KeyAgreement"
RequirementLevel="OPTIONAL"
RequiredKey="DH"
JCEName="DH"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#kw-tripledes"
Description="Symmetric Key Wrap using Triple DES"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="REQUIRED"
KeyLength="192"
RequiredKey="DESede"
JCEName="DESedeWrap"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#kw-aes128"
Description="Symmetric Key Wrap using AES with a key length of 128 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="REQUIRED"
KeyLength="128"
RequiredKey="AES"
JCEName="AESWrap"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#kw-aes192"
Description="Symmetric Key Wrap using AES with a key length of 192 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="OPTIONAL"
KeyLength="192"
RequiredKey="AES"
JCEName="AESWrap"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#kw-aes256"
Description="Symmetric Key Wrap using AES with a key length of 256 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="REQUIRED"
KeyLength="256"
RequiredKey="AES"
JCEName="AESWrap"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#kw-camellia128"
Description="Symmetric Key Wrap using CAMELLIA with a key length of 128 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="OPTIONAL"
KeyLength="128"
RequiredKey="Camellia"
JCEName="CamelliaWrap"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#kw-camellia192"
Description="Symmetric Key Wrap using CAMELLIA with a key length of 192 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="OPTIONAL"
KeyLength="192"
RequiredKey="Camellia"
JCEName="CamelliaWrap"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#kw-camellia256"
Description="Symmetric Key Wrap using CAMELLIA with a key length of 256 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="OPTIONAL"
KeyLength="256"
RequiredKey="Camellia"
JCEName="CamelliaWrap"/>
<Algorithm URI="http://www.w3.org/2007/05/xmldsig-more#kw-seed128"
Description="Symmetric Key Wrap using SEED with a key length of 128 bit"
AlgorithmClass="SymmetricKeyWrap"
RequirementLevel="OPTIONAL"
KeyLength="128"
RequiredKey="SEED"
JCEName="SEEDWrap"/>
</Algorithms>
</JCEAlgorithmMappings>
<ResourceBundles defaultLanguageCode="en" defaultCountryCode="US"/>
<ResourceResolvers>
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP"
DESCRIPTION="A simple resolver for requests to HTTP space" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverLocalFilesystem"
DESCRIPTION="A simple resolver for requests to the local file system" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment"
DESCRIPTION="A simple resolver for requests of same-document URIs" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverXPointer"
DESCRIPTION="A simple resolver for requests of XPointer fragments" />
</ResourceResolvers>
<KeyResolver>
<!-- This section contains a list of KeyResolvers that are available in
every KeyInfo object -->
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver"
DESCRIPTION="Can extract RSA public keys" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver"
DESCRIPTION="Can extract DSA public keys" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver"
DESCRIPTION="Can extract public keys from X509 certificates" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver"
DESCRIPTION="Uses an X509v3 SubjectKeyIdentifier extension to retrieve a certificate from the storages" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver"
DESCRIPTION="Resolves keys and certificates using ResourceResolvers" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver"
DESCRIPTION="Uses an X509 SubjectName to retrieve a certificate from the storages" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver"
DESCRIPTION="Uses an X509 IssuerName and IssuerSerial to retrieve a certificate from the storages" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.ECKeyValueResolver"
DESCRIPTION="Can extract EC public keys" />
</KeyResolver>
<PrefixMappings>
<!-- Many classes create Elements which are in a specific namespace;
here, the prefixes for these namespaces are defined. But this
can also be overwritten using the ElementProxy#setDefaultPrefix()
method. You can even set all prefixes to "" so that the corresponding
elements are created using the default namespace -->
<PrefixMapping namespace="http://www.w3.org/2000/09/xmldsig#"
prefix="ds" />
<PrefixMapping namespace="http://www.w3.org/2001/04/xmlenc#"
prefix="xenc" />
<PrefixMapping namespace="http://www.xmlsecurity.org/experimental#"
prefix="experimental" />
<PrefixMapping namespace="http://www.w3.org/2002/04/xmldsig-filter2"
prefix="dsig-xpath-old" />
<PrefixMapping namespace="http://www.w3.org/2002/06/xmldsig-filter2"
prefix="dsig-xpath" />
<PrefixMapping namespace="http://www.w3.org/2001/10/xml-exc-c14n#"
prefix="ec" />
<PrefixMapping namespace="http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"
prefix="xx" />
<PrefixMapping namespace="http://www.w3.org/2009/xmldsig11#"
prefix="dsig11" />
</PrefixMappings>
</Configuration>

View file

@ -0,0 +1,200 @@
#
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#
algorithm.alreadyRegistered = URI {0} already assigned to class {1}
algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH
algorithm.ClassDoesNotExist = Class {0} does not exist
algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2}
algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
algorithms.HMACOutputLengthMax = HMACOutputLength must not be more than {0}
algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
algorithms.MissingRSAPSSParams = RSAPSSParams is a required Element for http://www.w3.org/2007/05/xmldsig-more#rsa-pss
algorithms.NoSuchAlgorithmNoEx = The requested algorithm {0} does not exist.
algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1}
algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1}
algorithms.operationOnlyVerification = A public key can only used for verification of a signature.
algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed.
attributeValueIllegal = The attribute {0} has value {1} but must be {2}
c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0}
c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1}
c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0}
c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0}
c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}"
c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0}
c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0}
c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0}
c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation
c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document)
certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0}
certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString
certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier
defaultNamespaceCannotBeSetHere = Default namespace cannot be set here
ElementProxy.nullElement = Cannot create an ElementProxy from a null argument
empty = {0}
encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0}
encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams
encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt
encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap
encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit
encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this.
encryption.RSAOAEP.dataHashWrong = data hash wrong
encryption.RSAOAEP.dataStartWrong = data wrong start {0}
encryption.RSAOAEP.dataTooShort = data too short
encryption.RSAPKCS15.blockTruncated = block truncated
encryption.RSAPKCS15.noDataInBlock = no data in block
encryption.RSAPKCS15.unknownBlockType = unknown block type
encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers
endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
errorMessages.IOException = Other file I/O and similar exceptions.
errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
errorMessages.NotYetImplementedException = Functionality not yet there.
errorMessages.XMLSignatureException = Verification failed for some other reason.
decoding.divisible.four = It should be divisible by four
decoding.general = Error while decoding
FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
generic.dontHaveConstructionElement = I do not have a construction Element
generic.EmptyMessage = {0}
generic.NotYetImplemented = {0} Not YET implemented ;-((
java.security.InvalidKeyException = Invalid key
java.security.NoSuchProviderException = Unknown or unsupported provider
java.security.UnknownKeyType = Unknown or unsupported key type {0}
KeyInfo.error = Error loading Key Info
KeyInfo.needKeyResolver = More than one keyResolver have to be registered
KeyInfo.nokey = Cannot get key from {0}
KeyInfo.noKey = Cannot get the public key
KeyInfo.wrongNumberOfObject = Need {0} keyObjects
KeyInfo.wrongUse = This object was made for getting {0}
keyResolver.alreadyRegistered = {1} class has already been registered for {0}
KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0}
KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0}
KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0}
KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0}
KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0}
KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0}
KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0}
KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0}
KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0}
KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0}
KeyStore.alreadyRegistered = {0} Class has already been registered for {1}
KeyStore.register = {1} type class register error in class {0}
KeyStore.registerStore.register = Registration error for type {0}
KeyValue.IllegalArgument = Cannot create a {0} from {1}
namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1}
notYetInitialized = The module {0} is not yet initialized
prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2}
signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0}
signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
signature.Reference.NoDigestMethod = A Signature Reference Element must contain a DigestMethod child
signature.Reference.NoDigestValue = A Signature Reference Element must contain a DigestValue child
signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set
signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation
signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation
signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform
signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled
signature.Transform.NotYetImplemented = Transform {0} not yet implemented
signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug?
signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0}
signature.Transform.XPathError = Error evaluating XPath expression
signature.Transform.node = Current Node: {0}
signature.Transform.nodeAndType = Current Node: {0}, type: {1}
signature.Util.BignumNonPositive = bigInteger.signum() must be positive
signature.Util.NonTextNode = Not a text node
signature.Util.TooManyChilds = Too many childs of Type {0} in {1}
signature.Verification.certificateError = Certificate error
signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References
signature.Verification.internalError = Internal error
signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0}
signature.Verification.InvalidElement = Current Node {0} is not permitted in this location in the Signature
signature.Verification.keyStore = KeyStore error
signature.Verification.MissingID = Cannot resolve element with ID {0}
signature.Verification.MissingResources = Cannot resolve external resource {0}
signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1}
signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput
signature.Verification.SignatureError = Signature error
signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0}
signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it
signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference
transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream.
transform.init.NotInitialized =
transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization
transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element
utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4
Base64Decoding = Error while decoding
utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1}
xml.WrongContent = Cannot find {0} in {1}
xml.WrongElement = Cannot create a {0} from a {1} element
xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node
xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0}
secureProcessing.MaximumAllowedTransformsPerReference = {0} transforms are contained in the Reference, maximum {1} are allowed. You can raise the maximum via the \"MaximumAllowedTransformsPerReference\" property in the configuration.
secureProcessing.MaximumAllowedReferencesPerManifest = {0} references are contained in the Manifest, maximum {1} are allowed. You can raise the maximum via the \"MaximumAllowedReferencesPerManifest\" property in the configuration.
secureProcessing.DoNotThrowExceptionForManifests = Signature Manifests are not supported. You can disable throwing of an exception via the \"DoNotThrowExceptionForManifests\" property in the configuration.
secureProcessing.AllowMD5Algorithm = The use of MD5 algorithm is strongly discouraged. Nonetheless can it be enabled via the \"AllowMD5Algorithm\" property in the configuration.
secureProcessing.AllowNotSameDocumentReferences = External references found. Processing of external references is disabled by default. You can enable it via the \"AllowNotSameDocumentReferences\" property in the configuration.
secureProcessing.MaximumAllowedXMLStructureDepth = Maximum depth ({0}) of the XML structure reached. You can raise the maximum via the \"MaximumAllowedXMLStructureDepth\" property in the configuration.
secureProcessing.inputStreamLimitReached = Maximum byte count ({0}) reached.
stax.duplicateActions = Duplicate Actions are not allowed.
stax.missingSecurityProperties = SecurityProperties must not be null!
stax.noOutputAction = No outgoing actions specified.
stax.noKey = Key could not be resolved and no key was loaded for {0}
stax.keyNotFound = Key not found.
stax.unsupportedKeyValue = No or unsupported key in KeyValue.
stax.emptyReferenceURI = Reference is missing an URI attribute.
stax.encryption.unprocessedReferences = Some encryption references were not processed...
stax.signature.unprocessedReferences = Some signature references were not processed...
stax.unsupportedToken = {0} not supported.
stax.xmlStructureSizeExceeded = Maximum ({0}) allowed XML Structure size exceeded.
stax.unexpectedXMLEvent = Unexpected StAX-Event\: {0}
stax.encryption.noEncAlgo = xenc:EncryptedKey does not contain xenc:EncryptionMethod/@Algorithm.
stax.encryption.noCipherValue = EncryptedKey does not contain xenc:CipherData/xenc:CipherValue.
stax.unsecuredMessage = Unsecured message. Neither a Signature nor a EncryptedData element found.
stax.signature.signedInfoMissing = SignedInfo Element is missing.
stax.signature.signatureMethodMissing = Signature method is missing.
stax.signature.canonicalizationMethodMissing = Signature canonicalization method is missing.
stax.signature.signatureValueMissing = Signature value is missing.
stax.signature.publicKeyOrCertificateMissing = Certificate or public key not configured.
stax.encryption.encryptionKeyMissing = Key for encryption not configured.
stax.unsupportedKeyTransp = public key algorithm too weak to encrypt symmetric key.
stax.recursiveKeyReference = Recursive key reference detected.
stax.ecParametersNotSupported = ECParameters not supported.
stax.namedCurveMissing = NamedCurve is missing.
stax.encryption.securePartNotFound = Part to encrypt not found: {0}
stax.signature.securePartNotFound = Part to sign not found: {0}
stax.multipleSignaturesNotSupported = Multiple signatures are not supported.
stax.signature.keyNameMissing = KeyName not configured.
stax.keyNotFoundForName = No key configured for KeyName: {0}
stax.keyTypeNotSupported = Key of type {0} not supported for a KeyName lookup
stax.idsetbutnotgenerated = An Id attribute is specified, but Id generation is disabled
stax.idgenerationdisablewithmultipleparts = Id generation must not be disabled when multiple parts need signing

View file

@ -0,0 +1,95 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
/**
* Raised when the computed hash value doesn't match the given <i>DigestValue</i>.
* Additional human readable info is passed to the constructor -- this being the benefit
* of raising an exception or returning a value.
*
*/
public class InvalidDigestValueException extends XMLSignatureException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor InvalidDigestValueException
*
*/
public InvalidDigestValueException() {
super();
}
/**
* Constructor InvalidDigestValueException
*
* @param msgID
*/
public InvalidDigestValueException(String msgID) {
super(msgID);
}
/**
* Constructor InvalidDigestValueException
*
* @param msgID
* @param exArgs
*/
public InvalidDigestValueException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor InvalidDigestValueException
*
* @param originalException
* @param msgID
*/
public InvalidDigestValueException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public InvalidDigestValueException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor InvalidDigestValueException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public InvalidDigestValueException(Exception originalException, String msgID, Object[] exArgs) {
super(originalException, msgID, exArgs);
}
@Deprecated
public InvalidDigestValueException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,94 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
/**
* Raised if testing the signature value over <i>DigestValue</i> fails because of invalid signature.
*
* @see InvalidDigestValueException MissingKeyFailureException MissingResourceFailureException
*/
public class InvalidSignatureValueException extends XMLSignatureException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor InvalidSignatureValueException
*
*/
public InvalidSignatureValueException() {
super();
}
/**
* Constructor InvalidSignatureValueException
*
* @param msgID
*/
public InvalidSignatureValueException(String msgID) {
super(msgID);
}
/**
* Constructor InvalidSignatureValueException
*
* @param msgID
* @param exArgs
*/
public InvalidSignatureValueException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor InvalidSignatureValueException
*
* @param originalException
* @param msgID
*/
public InvalidSignatureValueException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public InvalidSignatureValueException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor InvalidSignatureValueException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public InvalidSignatureValueException(Exception originalException, String msgID, Object[] exArgs) {
super(originalException, msgID, exArgs);
}
@Deprecated
public InvalidSignatureValueException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,586 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.parser.XMLParserException;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Handles {@code &lt;ds:Manifest&gt;} elements.
* <p> This element holds the {@code Reference} elements</p>
*/
public class Manifest extends SignatureElementProxy {
/**
* The default maximum number of references per Manifest, if secure validation is enabled.
*/
public static final int MAXIMUM_REFERENCE_COUNT = 30;
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(Manifest.class);
@SuppressWarnings("removal")
private static Integer referenceCount =
AccessController.doPrivileged(
(PrivilegedAction<Integer>) () -> Integer.parseInt(System.getProperty("com.sun.org.apache.xml.internal.security.maxReferences",
Integer.toString(MAXIMUM_REFERENCE_COUNT))));
/** Field references */
private List<Reference> references;
private Element[] referencesEl;
/** Field verificationResults[] */
private List<VerifiedReference> verificationResults;
/** Field resolverProperties */
private Map<String, String> resolverProperties;
/** Field perManifestResolvers */
private List<ResourceResolverSpi> perManifestResolvers;
private boolean secureValidation;
/**
* Constructs {@link Manifest}
*
* @param doc the {@link Document} in which {@code XMLsignature} is placed
*/
public Manifest(Document doc) {
super(doc);
addReturnToSelf();
this.references = new ArrayList<>();
}
/**
* Constructor Manifest
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public Manifest(Element element, String baseURI) throws XMLSecurityException {
this(element, baseURI, true);
}
/**
* Constructor Manifest
*
* @param element
* @param baseURI
* @param secureValidation
* @throws XMLSecurityException
*/
public Manifest(
Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
super(element, baseURI);
Attr attr = element.getAttributeNodeNS(null, "Id");
if (attr != null) {
element.setIdAttributeNode(attr, true);
}
this.secureValidation = secureValidation;
// check out Reference children
this.referencesEl =
XMLUtils.selectDsNodes(
getFirstChild(), Constants._TAG_REFERENCE
);
int le = this.referencesEl.length;
if (le == 0) {
// At least one Reference must be present. Bad.
Object[] exArgs = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST };
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
I18n.translate("xml.WrongContent", exArgs));
}
if (secureValidation && le > referenceCount) {
Object[] exArgs = { le, referenceCount };
throw new XMLSecurityException("signature.tooManyReferences", exArgs);
}
// create List
this.references = new ArrayList<>(le);
for (int i = 0; i < le; i++) {
Element refElem = referencesEl[i];
Attr refAttr = refElem.getAttributeNodeNS(null, "Id");
if (refAttr != null) {
refElem.setIdAttributeNode(refAttr, true);
}
this.references.add(null);
}
}
/**
* This {@code addDocument} method is used to add a new resource to the
* signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
* from the supplied values.
*
* @param baseURI the URI of the resource where the XML instance was stored
* @param referenceURI {@code URI} attribute in {@code Reference} for specifying
* where data is
* @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered
* list of transformations to be performed.
* @param digestURI The digest algorithm URI to be used.
* @param referenceId
* @param referenceType
* @throws XMLSignatureException
*/
public void addDocument(
String baseURI, String referenceURI, Transforms transforms,
String digestURI, String referenceId, String referenceType
) throws XMLSignatureException {
// the this.doc is handed implicitly by the this.getOwnerDocument()
Reference ref =
new Reference(getDocument(), baseURI, referenceURI, this, transforms, digestURI);
if (referenceId != null) {
ref.setId(referenceId);
}
if (referenceType != null) {
ref.setType(referenceType);
}
// add Reference object to our cache vector
this.references.add(ref);
// add the Element of the Reference object to the Manifest/SignedInfo
appendSelf(ref);
addReturnToSelf();
}
/**
* The calculation of the DigestValues in the References must be after the
* References are already added to the document and during the signing
* process. This ensures that all necessary data is in place.
*
* @throws ReferenceNotInitializedException
* @throws XMLSignatureException
*/
public void generateDigestValues()
throws XMLSignatureException, ReferenceNotInitializedException {
for (int i = 0; i < this.getLength(); i++) {
// update the cached Reference object, the Element content is automatically updated
Reference currentRef = this.references.get(i);
currentRef.generateDigestValue();
}
}
/**
* Return the nonnegative number of added references.
*
* @return the number of references
*/
public int getLength() {
return this.references.size();
}
/**
* Return the <i>i</i><sup>th</sup> reference. Valid {@code i}
* values are 0 to {@code {link@ getSize}-1}.
*
* @param i Index of the requested {@link Reference}
* @return the <i>i</i><sup>th</sup> reference
* @throws XMLSecurityException
*/
public Reference item(int i) throws XMLSecurityException {
if (this.references.get(i) == null) {
// not yet constructed, so _we_ have to
Reference ref =
new Reference(referencesEl[i], this.baseURI, this, secureValidation);
this.references.set(i, ref);
}
return this.references.get(i);
}
/**
* Sets the {@code Id} attribute
*
* @param Id the {@code Id} attribute in {@code ds:Manifest}
*/
public void setId(String Id) {
if (Id != null) {
setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
* Returns the {@code Id} attribute
*
* @return the {@code Id} attribute in {@code ds:Manifest}
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/**
* Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
* validation</A> of all enclosed references using the {@link Reference#verify} method.
*
* <p>This step loops through all {@link Reference}s and does verify the hash
* values. If one or more verifications fail, the method returns
* {@code false}. If <i>all</i> verifications are successful,
* it returns {@code true}. The results of the individual reference
* validations are available by using the {@link #getVerificationResult(int)} method
*
* @return true if all References verify, false if one or more do not verify.
* @throws MissingResourceFailureException if a {@link Reference} does not verify
* (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException}
* because of an uninitialized {@link XMLSignatureInput}
* @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
* @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()
* @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
* @throws XMLSecurityException
*/
public boolean verifyReferences()
throws MissingResourceFailureException, XMLSecurityException {
return this.verifyReferences(false);
}
/**
* Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
* validation</A> of all enclosed references using the {@link Reference#verify} method.
*
* <p>This step loops through all {@link Reference}s and does verify the hash
* values. If one or more verifications fail, the method returns
* {@code false}. If <i>all</i> verifications are successful,
* it returns {@code true}. The results of the individual reference
* validations are available by using the {@link #getVerificationResult(int)} method
*
* @param followManifests
* @return true if all References verify, false if one or more do not verify.
* @throws MissingResourceFailureException if a {@link Reference} does not verify
* (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException}
* because of an uninitialized {@link XMLSignatureInput}
* @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
* @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean)
* @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
* @throws XMLSecurityException
*/
public boolean verifyReferences(boolean followManifests)
throws MissingResourceFailureException, XMLSecurityException {
if (referencesEl == null) {
this.referencesEl =
XMLUtils.selectDsNodes(
getFirstChild(), Constants._TAG_REFERENCE
);
}
LOG.debug("verify {} References", referencesEl.length);
LOG.debug("I am {} requested to follow nested Manifests", followManifests
? "" : "not");
if (referencesEl.length == 0) {
throw new XMLSecurityException("empty", new Object[]{"References are empty"});
}
if (secureValidation && referencesEl.length > referenceCount) {
Object[] exArgs = { referencesEl.length, referenceCount };
throw new XMLSecurityException("signature.tooManyReferences", exArgs);
}
this.verificationResults = new ArrayList<>(referencesEl.length);
boolean verify = true;
for (int i = 0; i < this.referencesEl.length; i++) {
Reference currentRef =
new Reference(referencesEl[i], this.baseURI, this, secureValidation);
this.references.set(i, currentRef);
// if only one item does not verify, the whole verification fails
try {
boolean currentRefVerified = currentRef.verify();
if (!currentRefVerified) {
verify = false;
}
LOG.debug("The Reference has Type {}", currentRef.getType());
List<VerifiedReference> manifestReferences = Collections.emptyList();
// was verification successful till now and do we want to verify the Manifest?
if (verify && followManifests && currentRef.typeIsReferenceToManifest()) {
LOG.debug("We have to follow a nested Manifest");
try {
XMLSignatureInput signedManifestNodes =
currentRef.dereferenceURIandPerformTransforms(null);
Set<Node> nl = signedManifestNodes.getNodeSet();
Manifest referencedManifest = null;
for (Node n : nl) {
if (n.getNodeType() == Node.ELEMENT_NODE
&& ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS)
&& ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST)
) {
try {
referencedManifest =
new Manifest(
(Element)n, signedManifestNodes.getSourceURI(), secureValidation
);
break;
} catch (XMLSecurityException ex) {
LOG.debug(ex.getMessage(), ex);
// Hm, seems not to be a ds:Manifest
}
}
}
if (referencedManifest == null) {
// The Reference stated that it points to a ds:Manifest
// but we did not find a ds:Manifest in the signed area
throw new MissingResourceFailureException(currentRef, "empty",
new Object[]{"No Manifest found"});
}
referencedManifest.perManifestResolvers = this.perManifestResolvers;
referencedManifest.resolverProperties = this.resolverProperties;
boolean referencedManifestValid =
referencedManifest.verifyReferences(followManifests);
if (!referencedManifestValid) {
verify = false;
LOG.warn("The nested Manifest was invalid (bad)");
} else {
LOG.debug("The nested Manifest was valid (good)");
}
manifestReferences = referencedManifest.getVerificationResults();
} catch (IOException ex) {
throw new ReferenceNotInitializedException(ex);
} catch (XMLParserException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
verificationResults.add(new VerifiedReference(currentRefVerified, currentRef.getURI(), manifestReferences));
} catch (ReferenceNotInitializedException ex) {
Object[] exArgs = { currentRef.getURI() };
throw new MissingResourceFailureException(
ex, currentRef, "signature.Verification.Reference.NoInput", exArgs
);
}
}
return verify;
}
/**
* After verifying a {@link Manifest} or a {@link SignedInfo} using the
* {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods,
* the individual results can be retrieved with this method.
*
* @param index an index of into a {@link Manifest} or a {@link SignedInfo}
* @return the results of reference validation at the specified index
* @throws XMLSecurityException
*/
public boolean getVerificationResult(int index) throws XMLSecurityException {
if (index < 0 || index > this.getLength() - 1) {
Object[] exArgs = { Integer.toString(index), Integer.toString(this.getLength()) };
Exception e =
new IndexOutOfBoundsException(
I18n.translate("signature.Verification.IndexOutOfBounds", exArgs)
);
throw new XMLSecurityException(e);
}
if (this.verificationResults == null) {
try {
this.verifyReferences();
} catch (Exception ex) {
throw new XMLSecurityException(ex);
}
}
return verificationResults.get(index).isValid();
}
/**
* Get the list of verification result objects
*/
public List<VerifiedReference> getVerificationResults() {
if (verificationResults == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(verificationResults);
}
/**
* Adds Resource Resolver for retrieving resources at specified {@code URI} attribute
* in {@code reference} element
*
* @param resolver {@link ResourceResolverSpi} can provide the implementation subclass of
* {@link ResourceResolverSpi} for retrieving resource.
*/
public void addResourceResolver(ResourceResolverSpi resolver) {
if (resolver == null) {
return;
}
if (perManifestResolvers == null) {
perManifestResolvers = new ArrayList<>();
}
this.perManifestResolvers.add(resolver);
}
/**
* Get the Per-Manifest Resolver List
* @return the per-manifest Resolver List
*/
public List<ResourceResolverSpi> getPerManifestResolvers() {
return perManifestResolvers;
}
/**
* Get the resolver property map
* @return the resolver property map
*/
public Map<String, String> getResolverProperties() {
return resolverProperties;
}
/**
* Used to pass parameters like proxy servers etc to the ResourceResolver
* implementation.
*
* @param key the key
* @param value the value
*/
public void setResolverProperty(String key, String value) {
if (resolverProperties == null) {
resolverProperties = new HashMap<>(10);
}
this.resolverProperties.put(key, value);
}
/**
* Returns the value at specified key
*
* @param key the key
* @return the value
*/
public String getResolverProperty(String key) {
return this.resolverProperties.get(key);
}
/**
* Method getSignedContentItem
*
* @param i
* @return The signed content of the i reference.
*
* @throws XMLSignatureException
*/
public byte[] getSignedContentItem(int i) throws XMLSignatureException {
try {
return this.getReferencedContentAfterTransformsItem(i).getBytes();
} catch (IOException ex) {
throw new XMLSignatureException(ex);
} catch (CanonicalizationException ex) {
throw new XMLSignatureException(ex);
} catch (InvalidCanonicalizerException ex) {
throw new XMLSignatureException(ex);
} catch (XMLSecurityException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method getReferencedContentPriorTransformsItem
*
* @param i
* @return The contents before transformation of the reference i.
* @throws XMLSecurityException
*/
public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i)
throws XMLSecurityException {
return this.item(i).getContentsBeforeTransformation();
}
/**
* Method getReferencedContentAfterTransformsItem
*
* @param i
* @return The contents after transformation of the reference i.
* @throws XMLSecurityException
*/
public XMLSignatureInput getReferencedContentAfterTransformsItem(int i)
throws XMLSecurityException {
return this.item(i).getContentsAfterTransformation();
}
/**
* Method getSignedContentLength
*
* @return The number of references contained in this reference.
*/
public int getSignedContentLength() {
return this.getLength();
}
/**
* Method getBaseLocalName
*
* {@inheritDoc}
*/
@Override
public String getBaseLocalName() {
return Constants._TAG_MANIFEST;
}
public boolean isSecureValidation() {
return secureValidation;
}
}

View file

@ -0,0 +1,148 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
/**
* Thrown by {@link com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()} when
* testing the signature fails because of uninitialized
* {@link com.sun.org.apache.xml.internal.security.signature.Reference}s.
*
* @see ReferenceNotInitializedException
*/
public class MissingResourceFailureException extends XMLSignatureException {
/**
*
*/
private static final long serialVersionUID = 1L;
/** Field uninitializedReference */
@SuppressWarnings("serial") // Type of field is not Serializable
private Reference uninitializedReference;
/**
* MissingKeyResourceFailureException constructor.
* @param reference
* @param msgID
* @see #getReference
*/
public MissingResourceFailureException(Reference reference, String msgID) {
super(msgID);
this.uninitializedReference = reference;
}
@Deprecated
public MissingResourceFailureException(String msgID, Reference reference) {
this(reference, msgID);
}
/**
* Constructor MissingResourceFailureException
*
* @param reference
* @param msgID
* @param exArgs
* @see #getReference
*/
public MissingResourceFailureException(Reference reference, String msgID, Object[] exArgs) {
super(msgID, exArgs);
this.uninitializedReference = reference;
}
@Deprecated
public MissingResourceFailureException(String msgID, Object[] exArgs, Reference reference) {
this(reference, msgID, exArgs);
}
/**
* Constructor MissingResourceFailureException
*
* @param originalException
* @param reference
* @param msgID
* @see #getReference
*/
public MissingResourceFailureException(
Exception originalException, Reference reference, String msgID
) {
super(originalException, msgID);
this.uninitializedReference = reference;
}
@Deprecated
public MissingResourceFailureException(
String msgID, Exception originalException, Reference reference
) {
this(originalException, reference, msgID);
}
/**
* Constructor MissingResourceFailureException
*
* @param originalException
* @param reference
* @param msgID
* @param exArgs
* @see #getReference
*/
public MissingResourceFailureException(
Exception originalException, Reference reference, String msgID, Object[] exArgs
) {
super(originalException, msgID, exArgs);
this.uninitializedReference = reference;
}
@Deprecated
public MissingResourceFailureException(
String msgID, Object[] exArgs, Exception originalException, Reference reference
) {
this(originalException, reference, msgID, exArgs);
}
/**
* used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference}
*
* @param reference the Reference object
* @see #getReference
*/
public void setReference(Reference reference) {
this.uninitializedReference = reference;
}
/**
* used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference}
*
* This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
* to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification.
*
* @return the Reference object
* @see #setReference
*/
public Reference getReference() {
return this.uninitializedReference;
}
}

View file

@ -0,0 +1,56 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
import org.w3c.dom.Node;
/**
* An interface to tell to the c14n if a node is included or not in the output
*/
public interface NodeFilter {
/**
* Tells if a node must be output in c14n.
* @param n
* @return 1 if the node should be output.
* 0 if node must not be output,
* -1 if the node and all it's child must not be output.
*
*/
int isNodeInclude(Node n) throws TransformationException;
/**
* Tells if a node must be output in a c14n.
* The caller must assured that this method is always call
* in document order. The implementations can use this
* restriction to optimize the transformation.
* @param n
* @param level the relative level in the tree
* @return 1 if the node should be output.
* 0 if node must not be output,
* -1 if the node and all it's child must not be output.
*/
int isNodeIncludeDO(Node n, int level) throws TransformationException;
}

View file

@ -0,0 +1,137 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Handles {@code &lt;ds:Object&gt;} elements
* {@code Object} {@link Element} supply facility which can contain any kind data
*
* $todo$ if we remove children, the boolean values are not updated
*/
public class ObjectContainer extends SignatureElementProxy {
/**
* Constructs {@link ObjectContainer}
*
* @param doc the {@link Document} in which {@code Object} element is placed
*/
public ObjectContainer(Document doc) {
super(doc);
}
/**
* Constructs {@link ObjectContainer} from {@link Element}
*
* @param element is {@code Object} element
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
*/
public ObjectContainer(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Sets the {@code Id} attribute
*
* @param Id {@code Id} attribute
*/
public void setId(String Id) {
if (Id != null) {
setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
* Returns the {@code Id} attribute
*
* @return the {@code Id} attribute
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/**
* Sets the {@code MimeType} attribute
*
* @param MimeType the {@code MimeType} attribute
*/
public void setMimeType(String MimeType) {
if (MimeType != null) {
setLocalAttribute(Constants._ATT_MIMETYPE, MimeType);
}
}
/**
* Returns the {@code MimeType} attribute
*
* @return the {@code MimeType} attribute
*/
public String getMimeType() {
return getLocalAttribute(Constants._ATT_MIMETYPE);
}
/**
* Sets the {@code Encoding} attribute
*
* @param Encoding the {@code Encoding} attribute
*/
public void setEncoding(String Encoding) {
if (Encoding != null) {
setLocalAttribute(Constants._ATT_ENCODING, Encoding);
}
}
/**
* Returns the {@code Encoding} attribute
*
* @return the {@code Encoding} attribute
*/
public String getEncoding() {
return getLocalAttribute(Constants._ATT_ENCODING);
}
/**
* Adds child Node
*
* @param node child Node
* @return the new node in the tree.
*/
public Node appendChild(Node node) {
appendSelf(node);
return node;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_OBJECT;
}
}

View file

@ -0,0 +1,818 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import java.io.IOException;
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.algorithms.Algorithm;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData;
import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData;
import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceOctetStreamData;
import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceSubTreeData;
import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
/**
* Handles {@code &lt;ds:Reference&gt;} elements.
*
* This includes:
*
* Construct a {@code ds:Reference} from an {@link org.w3c.dom.Element}.
*
* <p>Create a new reference</p>
* <pre>
* Document doc;
* MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
* Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
* "http://localhost/1.gif",
* (Transforms) null, sha1);
* Element refElem = ref.toElement(doc);
* </pre>
*
* <p>Verify a reference</p>
* <pre>
* Element refElem = doc.getElement("Reference"); // PSEUDO
* Reference ref = new Reference(refElem);
* String url = ref.getURI();
* ref.setData(new XMLSignatureInput(new FileInputStream(url)));
* if (ref.verify()) {
* System.out.println("verified");
* }
* </pre>
*
* <pre>
* &lt;element name="Reference" type="ds:ReferenceType"/&gt;
* &lt;complexType name="ReferenceType"&gt;
* &lt;sequence&gt;
* &lt;element ref="ds:Transforms" minOccurs="0"/&gt;
* &lt;element ref="ds:DigestMethod"/&gt;
* &lt;element ref="ds:DigestValue"/&gt;
* &lt;/sequence&gt;
* &lt;attribute name="Id" type="ID" use="optional"/&gt;
* &lt;attribute name="URI" type="anyURI" use="optional"/&gt;
* &lt;attribute name="Type" type="anyURI" use="optional"/&gt;
* &lt;/complexType&gt;
* </pre>
*
* @see ObjectContainer
* @see Manifest
*/
public class Reference extends SignatureElementProxy {
/** Field OBJECT_URI */
public static final String OBJECT_URI = Constants.SignatureSpecNS + Constants._TAG_OBJECT;
/** Field MANIFEST_URI */
public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
/**
* The maximum number of transforms per reference, if secure validation is enabled.
*/
public static final int MAXIMUM_TRANSFORM_COUNT = 5;
private boolean secureValidation;
/**
* Look up useC14N11 system property. If true, an explicit C14N11 transform
* will be added if necessary when generating the signature. See section
* 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
*/
@SuppressWarnings("removal")
private static boolean useC14N11 =
AccessController.doPrivileged((PrivilegedAction<Boolean>)
() -> Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
private static final com.sun.org.slf4j.internal.Logger LOG =
com.sun.org.slf4j.internal.LoggerFactory.getLogger(Reference.class);
private Manifest manifest;
private XMLSignatureInput transformsOutput;
private Transforms transforms;
private Element digestMethodElem;
private Element digestValueElement;
private ReferenceData referenceData;
private static final Set<String> TRANSFORM_ALGORITHMS;
static {
Set<String> algorithms = new HashSet<>();
algorithms.add(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
algorithms.add(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS);
algorithms.add(Transforms.TRANSFORM_C14N_OMIT_COMMENTS);
algorithms.add(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
algorithms.add(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
algorithms.add(Transforms.TRANSFORM_C14N11_WITH_COMMENTS);
TRANSFORM_ALGORITHMS = Collections.unmodifiableSet(algorithms);
}
/**
* Constructor Reference
*
* @param doc the {@link Document} in which {@code XMLsignature} is placed
* @param baseURI the URI of the resource where the XML instance will be stored
* @param referenceURI URI indicate where is data which will digested
* @param manifest
* @param transforms {@link Transforms} applied to data
* @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is
* applied to the data
* TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
*/
protected Reference(
Document doc, String baseURI, String referenceURI, Manifest manifest,
Transforms transforms, String messageDigestAlgorithm
) throws XMLSignatureException {
super(doc);
addReturnToSelf();
this.baseURI = baseURI;
this.manifest = manifest;
this.setURI(referenceURI);
// important: The ds:Reference must be added to the associated ds:Manifest
// or ds:SignedInfo _before_ the this.resolverResult() is called.
// this.manifest.appendChild(this.constructionElement);
// this.manifest.appendChild(this.doc.createTextNode("\n"));
if (transforms != null) {
this.transforms = transforms;
appendSelf(transforms);
addReturnToSelf();
}
// Create DigestMethod Element without actually instantiating a MessageDigest Object
Algorithm digestAlgorithm = new Algorithm(getDocument(), messageDigestAlgorithm) {
@Override
public String getBaseNamespace() {
return Constants.SignatureSpecNS;
}
@Override
public String getBaseLocalName() {
return Constants._TAG_DIGESTMETHOD;
}
};
digestMethodElem = digestAlgorithm.getElement();
appendSelf(digestMethodElem);
addReturnToSelf();
digestValueElement =
XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_DIGESTVALUE);
appendSelf(digestValueElement);
addReturnToSelf();
}
/**
* Build a {@link Reference} from an {@link Element}
*
* @param element {@code Reference} element
* @param baseURI the URI of the resource where the XML instance was stored
* @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
* We need this because the Manifest has the individual {@link ResourceResolver}s which have
* been set by the user
* @throws XMLSecurityException
*/
protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
this(element, baseURI, manifest, true);
}
/**
* Build a {@link Reference} from an {@link Element}
*
* @param element {@code Reference} element
* @param baseURI the URI of the resource where the XML instance was stored
* @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
* @param secureValidation whether secure validation is enabled or not
* We need this because the Manifest has the individual {@link ResourceResolver}s which have
* been set by the user
* @throws XMLSecurityException
*/
protected Reference(Element element, String baseURI, Manifest manifest, boolean secureValidation)
throws XMLSecurityException {
super(element, baseURI);
this.secureValidation = secureValidation;
this.baseURI = baseURI;
Element el = XMLUtils.getNextElement(element.getFirstChild());
if (el != null && Constants._TAG_TRANSFORMS.equals(el.getLocalName())
&& Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
transforms = new Transforms(el, this.baseURI);
transforms.setSecureValidation(secureValidation);
if (secureValidation && transforms.getLength() > MAXIMUM_TRANSFORM_COUNT) {
Object[] exArgs = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT };
throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
}
el = XMLUtils.getNextElement(el.getNextSibling());
}
digestMethodElem = el;
if (digestMethodElem == null ||
!(Constants.SignatureSpecNS.equals(digestMethodElem.getNamespaceURI())
&& Constants._TAG_DIGESTMETHOD.equals(digestMethodElem.getLocalName()))) {
throw new XMLSecurityException("signature.Reference.NoDigestMethod");
}
digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
if (digestValueElement == null ||
!(Constants.SignatureSpecNS.equals(digestValueElement.getNamespaceURI())
&& Constants._TAG_DIGESTVALUE.equals(digestValueElement.getLocalName()))) {
throw new XMLSecurityException("signature.Reference.NoDigestValue");
}
this.manifest = manifest;
}
/**
* Returns {@link MessageDigestAlgorithm}
*
*
* @return {@link MessageDigestAlgorithm}
*
* @throws XMLSignatureException
*/
public MessageDigestAlgorithm getMessageDigestAlgorithm() throws XMLSignatureException {
if (digestMethodElem == null) {
return null;
}
String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
if (uri.isEmpty()) {
return null;
}
if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
Object[] exArgs = { uri };
throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
}
return MessageDigestAlgorithm.getInstance(getDocument(), uri);
}
/**
* Sets the {@code URI} of this {@code Reference} element
*
* @param uri the {@code URI} of this {@code Reference} element
*/
public void setURI(String uri) {
if (uri != null) {
setLocalAttribute(Constants._ATT_URI, uri);
}
}
/**
* Returns the {@code URI} of this {@code Reference} element
*
* @return URI the {@code URI} of this {@code Reference} element
*/
public String getURI() {
return getLocalAttribute(Constants._ATT_URI);
}
/**
* Sets the {@code Id} attribute of this {@code Reference} element
*
* @param id the {@code Id} attribute of this {@code Reference} element
*/
public void setId(String id) {
if (id != null) {
setLocalIdAttribute(Constants._ATT_ID, id);
}
}
/**
* Returns the {@code Id} attribute of this {@code Reference} element
*
* @return Id the {@code Id} attribute of this {@code Reference} element
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/**
* Sets the {@code type} atttibute of the Reference indicate whether an
* {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest}
* element.
*
* @param type the {@code type} attribute of the Reference
*/
public void setType(String type) {
if (type != null) {
setLocalAttribute(Constants._ATT_TYPE, type);
}
}
/**
* Return the {@code type} attribute of the Reference indicate whether an
* {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest}
* element
*
* @return the {@code type} attribute of the Reference
*/
public String getType() {
return getLocalAttribute(Constants._ATT_TYPE);
}
/**
* Method isReferenceToObject
*
* This returns true if the {@code Type} attribute of the
* {@code Reference} element points to a {@code #Object} element
*
* @return true if the Reference type indicates that this Reference points to an
* {@code Object}
*/
public boolean typeIsReferenceToObject() {
return Reference.OBJECT_URI.equals(this.getType());
}
/**
* Method isReferenceToManifest
*
* This returns true if the {@code Type} attribute of the
* {@code Reference} element points to a {@code #Manifest} element
*
* @return true if the Reference type indicates that this Reference points to a
* {@link Manifest}
*/
public boolean typeIsReferenceToManifest() {
return Reference.MANIFEST_URI.equals(this.getType());
}
/**
* Method setDigestValueElement
*
* @param digestValue
*/
private void setDigestValueElement(byte[] digestValue) {
Node n = digestValueElement.getFirstChild();
while (n != null) {
digestValueElement.removeChild(n);
n = n.getNextSibling();
}
String base64codedValue = XMLUtils.encodeToString(digestValue);
Text t = createText(base64codedValue);
digestValueElement.appendChild(t);
}
/**
* Method generateDigestValue
*
* @throws ReferenceNotInitializedException
* @throws XMLSignatureException
*/
public void generateDigestValue()
throws XMLSignatureException, ReferenceNotInitializedException {
this.setDigestValueElement(this.calculateDigest(false));
}
/**
* Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
* @return the XMLSignatureInput of the source of this reference
* @throws ReferenceNotInitializedException If the resolver found any
* problem resolving the reference
*/
public XMLSignatureInput getContentsBeforeTransformation()
throws ReferenceNotInitializedException {
try {
Attr uriAttr =
getElement().getAttributeNodeNS(null, Constants._ATT_URI);
ResourceResolverContext resolverContext =
new ResourceResolverContext(uriAttr, this.baseURI,
secureValidation, this.manifest.getResolverProperties());
return ResourceResolver.resolve(this.manifest.getPerManifestResolvers(), resolverContext);
} catch (ResourceResolverException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
private XMLSignatureInput getContentsAfterTransformation(
XMLSignatureInput input, OutputStream os
) throws XMLSignatureException {
try {
Transforms transforms = this.getTransforms();
XMLSignatureInput output = null;
if (transforms != null) {
output = transforms.performTransforms(input, os);
this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
//this.transformsOutput.setSourceURI(output.getSourceURI());
} else {
output = input;
}
return output;
} catch (XMLSecurityException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Returns the XMLSignatureInput which is the result of the Transforms.
* @return a XMLSignatureInput with all transformations applied.
* @throws XMLSignatureException
*/
public XMLSignatureInput getContentsAfterTransformation()
throws XMLSignatureException {
XMLSignatureInput input = this.getContentsBeforeTransformation();
cacheDereferencedElement(input);
return this.getContentsAfterTransformation(input, null);
}
/**
* This method returns the XMLSignatureInput which represents the node set before
* some kind of canonicalization is applied for the first time.
* @return Gets a the node doing everything till the first c14n is needed
*
* @throws XMLSignatureException
*/
public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
throws XMLSignatureException {
try {
XMLSignatureInput input = this.getContentsBeforeTransformation();
cacheDereferencedElement(input);
XMLSignatureInput output = input;
Transforms transforms = this.getTransforms();
if (transforms != null) {
for (int i = 0; i < transforms.getLength(); i++) {
Transform t = transforms.item(i);
String uri = t.getURI();
if (TRANSFORM_ALGORITHMS.contains(uri)) {
break;
}
output = t.performTransform(output, null, secureValidation);
}
output.setSourceURI(input.getSourceURI());
}
return output;
} catch (IOException | XMLSecurityException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method getHTMLRepresentation
* @return The HTML of the transformation
* @throws XMLSignatureException
*/
public String getHTMLRepresentation() throws XMLSignatureException {
try {
XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
Transforms transforms = this.getTransforms();
Transform c14nTransform = null;
if (transforms != null) {
for (int i = 0; i < transforms.getLength(); i++) {
Transform t = transforms.item(i);
String uri = t.getURI();
if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
|| uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
c14nTransform = t;
break;
}
}
}
Set<String> inclusiveNamespaces = new HashSet<>();
if (c14nTransform != null
&& c14nTransform.length(
InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1) {
// there is one InclusiveNamespaces element
InclusiveNamespaces in =
new InclusiveNamespaces(
XMLUtils.selectNode(
c14nTransform.getElement().getFirstChild(),
InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
0
), this.getBaseURI());
inclusiveNamespaces =
InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
}
return nodes.getHTMLRepresentation(inclusiveNamespaces);
} catch (XMLSecurityException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* This method only works after a call to verify.
* @return the transformed output(i.e. what is going to be digested).
*/
public XMLSignatureInput getTransformsOutput() {
return this.transformsOutput;
}
/**
* Get the ReferenceData that corresponds to the cached representation of the dereferenced
* object before transformation.
*/
public ReferenceData getReferenceData() {
return referenceData;
}
/**
* This method returns the {@link XMLSignatureInput} which is referenced by the
* {@code URI} Attribute.
* @param os where to write the transformation can be null.
* @return the element to digest
*
* @throws XMLSignatureException
* @see Manifest#verifyReferences()
*/
protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
throws XMLSignatureException {
try {
XMLSignatureInput input = this.getContentsBeforeTransformation();
cacheDereferencedElement(input);
XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
this.transformsOutput = output;
return output;
} catch (XMLSecurityException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
/**
* Store the dereferenced Element(s) so that it/they can be retrieved later.
*/
private void cacheDereferencedElement(XMLSignatureInput input) {
if (input.isNodeSet()) {
try {
final Set<Node> s = input.getNodeSet();
referenceData = new ReferenceNodeSetData() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
final Iterator<Node> sIterator = s.iterator();
@Override
public boolean hasNext() {
return sIterator.hasNext();
}
@Override
public Node next() {
return sIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
} catch (Exception e) {
// LOG a warning
LOG.warn("cannot cache dereferenced data: " + e);
}
} else if (input.isElement()) {
referenceData = new ReferenceSubTreeData
(input.getSubNode(), input.isExcludeComments());
} else if (input.isOctetStream() || input.isByteArray()) {
try {
referenceData = new ReferenceOctetStreamData
(input.getOctetStream(), input.getSourceURI(),
input.getMIMEType());
} catch (IOException ioe) {
// LOG a warning
LOG.warn("cannot cache dereferenced data: " + ioe);
}
}
}
/**
* Method getTransforms
*
* @return The transforms that applied this reference.
* @throws InvalidTransformException
* @throws TransformationException
* @throws XMLSecurityException
* @throws XMLSignatureException
*/
public Transforms getTransforms()
throws XMLSignatureException, InvalidTransformException,
TransformationException, XMLSecurityException {
return transforms;
}
/**
* Method getReferencedBytes
*
* @return the bytes that will be used to generated digest.
* @throws ReferenceNotInitializedException
* @throws XMLSignatureException
*/
public byte[] getReferencedBytes()
throws ReferenceNotInitializedException, XMLSignatureException {
try {
XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null);
return output.getBytes();
} catch (IOException | CanonicalizationException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
/**
* Method calculateDigest
*
* @param validating true if validating the reference
* @return reference Calculate the digest of this reference.
* @throws ReferenceNotInitializedException
* @throws XMLSignatureException
*/
private byte[] calculateDigest(boolean validating)
throws ReferenceNotInitializedException, XMLSignatureException {
XMLSignatureInput input = this.getContentsBeforeTransformation();
if (input.isPreCalculatedDigest()) {
return getPreCalculatedDigest(input);
}
cacheDereferencedElement(input);
MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
mda.reset();
XMLSignatureInput output = null;
try (DigesterOutputStream diOs = new DigesterOutputStream(mda);
OutputStream os = new UnsyncBufferedOutputStream(diOs)) {
output = this.getContentsAfterTransformation(input, os);
this.transformsOutput = output;
// if signing and c14n11 property == true explicitly add
// C14N11 transform if needed
if (Reference.useC14N11 && !validating && !output.isOutputStreamSet()
&& !output.isOctetStream()) {
if (transforms == null) {
transforms = new Transforms(getDocument());
transforms.setSecureValidation(secureValidation);
getElement().insertBefore(transforms.getElement(), digestMethodElem);
}
transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
output.updateOutputStream(os, true);
} else {
output.updateOutputStream(os);
}
os.flush();
//this.getReferencedBytes(diOs);
//mda.update(data);
return diOs.getDigestValue();
} catch (XMLSecurityException | IOException ex) {
throw new ReferenceNotInitializedException(ex);
} finally { //NOPMD
try {
if (output != null && output.getOctetStreamReal() != null) {
output.getOctetStreamReal().close();
}
} catch (IOException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
}
/**
* Get the pre-calculated digest value from the XMLSignatureInput.
*
* @param input XMLSignature
* @return a pre-calculated digest value.
* @throws ReferenceNotInitializedException if there is an error decoding digest value
* in Base64. Properly encoded pre-calculated digest value must be set.
*/
private byte[] getPreCalculatedDigest(XMLSignatureInput input)
throws ReferenceNotInitializedException {
LOG.debug("Verifying element with pre-calculated digest");
String preCalculatedDigest = input.getPreCalculatedDigest();
return XMLUtils.decode(preCalculatedDigest);
}
/**
* Returns the digest value.
*
* @return the digest value.
* @throws XMLSecurityException if the Reference does not contain a DigestValue element
*/
public byte[] getDigestValue() throws XMLSecurityException {
if (digestValueElement == null) {
// The required element is not in the XML!
Object[] exArgs ={ Constants._TAG_DIGESTVALUE, Constants.SignatureSpecNS };
throw new XMLSecurityException(
"signature.Verification.NoSignatureElement", exArgs
);
}
String content = XMLUtils.getFullTextChildrenFromNode(digestValueElement);
return XMLUtils.decode(content);
}
/**
* Tests reference validation is success or false
*
* @return true if reference validation is success, otherwise false
* @throws ReferenceNotInitializedException
* @throws XMLSecurityException
*/
public boolean verify()
throws ReferenceNotInitializedException, XMLSecurityException {
byte[] elemDig = this.getDigestValue();
byte[] calcDig = this.calculateDigest(true);
boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
if (!equal) {
LOG.warn("Verification failed for URI \"" + this.getURI() + "\"");
LOG.warn("Expected Digest: " + XMLUtils.encodeToString(elemDig));
LOG.warn("Actual Digest: " + XMLUtils.encodeToString(calcDig));
} else {
LOG.debug("Verification successful for URI \"{}\"", this.getURI());
}
return equal;
}
/**
* Method getBaseLocalName
* {@inheritDoc}
*/
@Override
public String getBaseLocalName() {
return Constants._TAG_REFERENCE;
}
}

View file

@ -0,0 +1,98 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
/**
* Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
* because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
*
*/
public class ReferenceNotInitializedException extends XMLSignatureException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor ReferenceNotInitializedException
*
*/
public ReferenceNotInitializedException() {
super();
}
public ReferenceNotInitializedException(Exception ex) {
super(ex);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param msgID
*/
public ReferenceNotInitializedException(String msgID) {
super(msgID);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param msgID
* @param exArgs
*/
public ReferenceNotInitializedException(String msgID, Object[] exArgs) {
super(msgID, exArgs);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param originalException
* @param msgID
*/
public ReferenceNotInitializedException(Exception originalException, String msgID) {
super(originalException, msgID);
}
@Deprecated
public ReferenceNotInitializedException(String msgID, Exception originalException) {
this(originalException, msgID);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param originalException
* @param msgID
* @param exArgs
*/
public ReferenceNotInitializedException(Exception originalException, String msgID, Object[] exArgs) {
super(originalException, msgID, exArgs);
}
@Deprecated
public ReferenceNotInitializedException(String msgID, Object[] exArgs, Exception originalException) {
this(originalException, msgID, exArgs);
}
}

View file

@ -0,0 +1,146 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Handles {@code &lt;ds:SignatureProperties&gt;} elements
* This Element holds {@link SignatureProperty} properties that contain additional information items
* concerning the generation of the signature.
* for example, data-time stamp, serial number of cryptographic hardware.
*
*/
public class SignatureProperties extends SignatureElementProxy {
/**
* Constructor SignatureProperties
*
* @param doc
*/
public SignatureProperties(Document doc) {
super(doc);
addReturnToSelf();
}
/**
* Constructs {@link SignatureProperties} from {@link Element}
* @param element {@code SignatureProperties} element
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
*/
public SignatureProperties(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
Attr attr = element.getAttributeNodeNS(null, "Id");
if (attr != null) {
element.setIdAttributeNode(attr, true);
}
Element[] propertyElems =
XMLUtils.selectDsNodes(getFirstChild(), Constants._TAG_SIGNATUREPROPERTY);
for (Element propertyElem : propertyElems) {
Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
if (propertyAttr != null) {
propertyElem.setIdAttributeNode(propertyAttr, true);
}
}
}
/**
* Return the nonnegative number of added SignatureProperty elements.
*
* @return the number of SignatureProperty elements
*/
public int getLength() {
Element[] propertyElems =
XMLUtils.selectDsNodes(getFirstChild(), Constants._TAG_SIGNATUREPROPERTY);
return propertyElems.length;
}
/**
* Return the <i>i</i><sup>th</sup> SignatureProperty. Valid {@code i}
* values are 0 to {@code {@link getSize}-1}.
*
* @param i Index of the requested {@link SignatureProperty}
* @return the <i>i</i><sup>th</sup> SignatureProperty
* @throws XMLSignatureException
*/
public SignatureProperty item(int i) throws XMLSignatureException {
try {
Element propertyElem =
XMLUtils.selectDsNode(getFirstChild(), Constants._TAG_SIGNATUREPROPERTY, i);
if (propertyElem == null) {
return null;
}
return new SignatureProperty(propertyElem, this.baseURI);
} catch (XMLSecurityException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Sets the {@code Id} attribute
*
* @param Id the {@code Id} attribute
*/
public void setId(String Id) {
if (Id != null) {
setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
* Returns the {@code Id} attribute
*
* @return the {@code Id} attribute
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/**
* Method addSignatureProperty
*
* @param sp
*/
public void addSignatureProperty(SignatureProperty sp) {
appendSelf(sp);
addReturnToSelf();
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_SIGNATUREPROPERTIES;
}
}

View file

@ -0,0 +1,133 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Handles {@code &lt;ds:SignatureProperty&gt;} elements
* Additional information item concerning the generation of the signature(s) can
* be placed in this Element
*
*/
public class SignatureProperty extends SignatureElementProxy {
/**
* Constructs{@link SignatureProperty} using specified {@code target} attribute
*
* @param doc the {@link Document} in which {@code XMLsignature} is placed
* @param target the {@code target} attribute references the {@code Signature}
* element to which the property applies SignatureProperty
*/
public SignatureProperty(Document doc, String target) {
this(doc, target, null);
}
/**
* Constructs {@link SignatureProperty} using specified {@code target} attribute and
* {@code id} attribute
*
* @param doc the {@link Document} in which {@code XMLsignature} is placed
* @param target the {@code target} attribute references the {@code Signature}
* element to which the property applies
* @param id the {@code id} will be specified by {@link Reference#getURI} in validation
*/
public SignatureProperty(Document doc, String target, String id) {
super(doc);
this.setTarget(target);
this.setId(id);
}
/**
* Constructs a {@link SignatureProperty} from an {@link Element}
* @param element {@code SignatureProperty} element
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
*/
public SignatureProperty(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
/**
* Sets the {@code id} attribute
*
* @param id the {@code id} attribute
*/
public void setId(String id) {
if (id != null) {
setLocalIdAttribute(Constants._ATT_ID, id);
}
}
/**
* Returns the {@code id} attribute
*
* @return the {@code id} attribute
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/**
* Sets the {@code target} attribute
*
* @param target the {@code target} attribute
*/
public void setTarget(String target) {
if (target != null) {
setLocalAttribute(Constants._ATT_TARGET, target);
}
}
/**
* Returns the {@code target} attribute
*
* @return the {@code target} attribute
*/
public String getTarget() {
return getLocalAttribute(Constants._ATT_TARGET);
}
/**
* Method appendChild
*
* @param node
* @return the node in this element.
*/
public Node appendChild(Node node) {
appendSelf(node);
return node;
}
/** {@inheritDoc} */
@Override
public String getBaseLocalName() {
return Constants._TAG_SIGNATUREPROPERTY;
}
}

View file

@ -0,0 +1,432 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Provider;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Handles {@code &lt;ds:SignedInfo&gt;} elements
* This {@code SignedInfo} element includes the canonicalization algorithm,
* a signature algorithm, and one or more references.
*
*/
public class SignedInfo extends Manifest {
/** Field signatureAlgorithm */
private final SignatureAlgorithm signatureAlgorithm;
/** Field c14nizedBytes */
private byte[] c14nizedBytes;
private Element c14nMethod;
private Element signatureMethod;
/**
* Overwrites {@link Manifest#addDocument} because it creates another
* Element.
*
* @param doc the {@link Document} in which {@code XMLsignature} will
* be placed
* @throws XMLSecurityException
*/
public SignedInfo(Document doc) throws XMLSecurityException {
this(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA,
Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
}
/**
* Constructs {@link SignedInfo} using given Canonicalization algorithm and
* Signature algorithm.
*
* @param doc {@code SignedInfo} is placed in this document
* @param signatureMethodURI URI representation of the Digest and
* Signature algorithm
* @param canonicalizationMethodURI URI representation of the
* Canonicalization method
* @throws XMLSecurityException
*/
public SignedInfo(
Document doc, String signatureMethodURI, String canonicalizationMethodURI
) throws XMLSecurityException {
this(doc, signatureMethodURI, 0, canonicalizationMethodURI, null, null);
}
/**
* Constructs {@link SignedInfo} using given Canonicalization algorithm and
* Signature algorithm.
*
* @param doc {@code SignedInfo} is placed in this document
* @param signatureMethodURI URI representation of the Digest and
* Signature algorithm
* @param canonicalizationMethodURI URI representation of the
* Canonicalization method
* @param provider security provider to use
* @throws XMLSecurityException
*/
public SignedInfo(
Document doc, String signatureMethodURI, String canonicalizationMethodURI, Provider provider
) throws XMLSecurityException {
this(doc, signatureMethodURI, 0, canonicalizationMethodURI, provider, null);
}
/**
* Constructor SignedInfo
*
* @param doc {@code SignedInfo} is placed in this document
* @param signatureMethodURI URI representation of the Digest and
* Signature algorithm
* @param hMACOutputLength
* @param canonicalizationMethodURI URI representation of the
* Canonicalization method
* @throws XMLSecurityException
*/
public SignedInfo(
Document doc, String signatureMethodURI,
int hMACOutputLength, String canonicalizationMethodURI
) throws XMLSecurityException {
this(doc, signatureMethodURI, hMACOutputLength, canonicalizationMethodURI, null, null);
}
/**
* Constructs {@link SignedInfo} using given Canonicalization algorithm and
* Signature algorithm.
*
* @param doc {@code SignedInfo} is placed in this document
* @param signatureMethodURI URI representation of the Digest and
* Signature algorithm
* @param hMACOutputLength
* @param canonicalizationMethodURI URI representation of the
* Canonicalization method
* @param provider security provider to use
* @param spec AlgorithmParameterSpec to use
* @throws XMLSecurityException
*/
public SignedInfo(
Document doc, String signatureMethodURI,
int hMACOutputLength, String canonicalizationMethodURI, Provider provider, AlgorithmParameterSpec spec
) throws XMLSecurityException {
super(doc);
c14nMethod =
XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_CANONICALIZATIONMETHOD);
c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
appendSelf(c14nMethod);
addReturnToSelf();
if (hMACOutputLength > 0) {
this.signatureAlgorithm =
new SignatureAlgorithm(getDocument(), signatureMethodURI, hMACOutputLength, provider);
} else {
this.signatureAlgorithm = new SignatureAlgorithm(getDocument(), signatureMethodURI, provider, spec);
}
signatureMethod = this.signatureAlgorithm.getElement();
appendSelf(signatureMethod);
addReturnToSelf();
}
/**
* @param doc
* @param signatureMethodElem
* @param canonicalizationMethodElem
* @throws XMLSecurityException
*/
public SignedInfo(
Document doc, Element signatureMethodElem, Element canonicalizationMethodElem
) throws XMLSecurityException {
this(doc, signatureMethodElem, canonicalizationMethodElem, null);
}
public SignedInfo(
Document doc, Element signatureMethodElem, Element canonicalizationMethodElem, Provider provider
) throws XMLSecurityException {
super(doc);
// Check this?
this.c14nMethod = canonicalizationMethodElem;
appendSelf(c14nMethod);
addReturnToSelf();
this.signatureAlgorithm =
new SignatureAlgorithm(signatureMethodElem, null, provider);
signatureMethod = this.signatureAlgorithm.getElement();
appendSelf(signatureMethod);
addReturnToSelf();
}
/**
* Build a {@link SignedInfo} from an {@link Element}
*
* @param element {@code SignedInfo}
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
* @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
* Question</A>
* @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
* Answer</A>
*/
public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
this(element, baseURI, true, null);
}
/**
* Build a {@link SignedInfo} from an {@link Element}
*
* @param element {@code SignedInfo}
* @param baseURI the URI of the resource where the XML instance was stored
* @param secureValidation whether secure validation is enabled or not
* @throws XMLSecurityException
* @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
* Question</A>
* @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
* Answer</A>
*/
public SignedInfo(
Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
this(element, baseURI, secureValidation, null);
}
/**
* Build a {@link SignedInfo} from an {@link Element}
*
* @param element {@code SignedInfo}
* @param baseURI the URI of the resource where the XML instance was stored
* @param secureValidation whether secure validation is enabled or not
* @param provider security provider to use
* @throws XMLSecurityException
* @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
* Question</A>
* @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
* Answer</A>
*/
public SignedInfo(
Element element, String baseURI, boolean secureValidation, Provider provider
) throws XMLSecurityException {
super(element, baseURI, secureValidation);
c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
if (c14nMethod == null ||
!(Constants.SignatureSpecNS.equals(c14nMethod.getNamespaceURI())
&& Constants._TAG_CANONICALIZATIONMETHOD.equals(c14nMethod.getLocalName()))) {
Object[] exArgs = { Constants._TAG_CANONICALIZATIONMETHOD, Constants._TAG_SIGNEDINFO };
throw new XMLSignatureException("xml.WrongContent", exArgs);
}
signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
if (signatureMethod == null ||
!(Constants.SignatureSpecNS.equals(signatureMethod.getNamespaceURI())
&& Constants._TAG_SIGNATUREMETHOD.equals(signatureMethod.getLocalName()))) {
Object[] exArgs = { Constants._TAG_SIGNATUREMETHOD, Constants._TAG_SIGNEDINFO };
throw new XMLSignatureException("xml.WrongContent", exArgs);
}
this.signatureAlgorithm =
new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation, provider);
}
/**
* Tests core validation process
*
* @return true if verification was successful
* @throws MissingResourceFailureException
* @throws XMLSecurityException
*/
public boolean verify()
throws MissingResourceFailureException, XMLSecurityException {
return super.verifyReferences(false);
}
/**
* Tests core validation process
*
* @param followManifests defines whether the verification process has to verify referenced {@code ds:Manifest}s, too
* @return true if verification was successful
* @throws MissingResourceFailureException
* @throws XMLSecurityException
*/
public boolean verify(boolean followManifests)
throws MissingResourceFailureException, XMLSecurityException {
return super.verifyReferences(followManifests);
}
/**
* Returns getCanonicalizedOctetStream
*
* @return the canonicalization result octet stream of {@code SignedInfo} element
* @throws CanonicalizationException
* @throws InvalidCanonicalizerException
* @throws XMLSecurityException
* @throws IOException
*/
public byte[] getCanonicalizedOctetStream()
throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException, IOException {
if (this.c14nizedBytes == null) {
Canonicalizer c14nizer =
Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
String inclusiveNamespaces = this.getInclusiveNamespaces();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
if (inclusiveNamespaces == null) {
c14nizer.canonicalizeSubtree(getElement(), baos);
} else {
c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces, baos);
}
this.c14nizedBytes = baos.toByteArray();
}
}
// make defensive copy
return this.c14nizedBytes.clone();
}
/**
* Output the C14n stream to the given OutputStream.
* @param os
* @throws CanonicalizationException
* @throws InvalidCanonicalizerException
* @throws XMLSecurityException
*/
public void signInOctetStream(OutputStream os)
throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
if (this.c14nizedBytes == null) {
Canonicalizer c14nizer =
Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
String inclusiveNamespaces = this.getInclusiveNamespaces();
if (inclusiveNamespaces == null) {
c14nizer.canonicalizeSubtree(getElement(), os);
} else {
c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces, os);
}
} else {
try {
os.write(this.c14nizedBytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* Returns the Canonicalization method URI
*
* @return the Canonicalization method URI
*/
public String getCanonicalizationMethodURI() {
return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
}
/**
* Returns the Signature method URI
*
* @return the Signature method URI
*/
public String getSignatureMethodURI() {
Element signatureElement = this.getSignatureMethodElement();
if (signatureElement != null) {
return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
}
return null;
}
/**
* Method getSignatureMethodElement
* @return returns the SignatureMethod Element
*
*/
public Element getSignatureMethodElement() {
return signatureMethod;
}
/**
* Creates a SecretKey for the appropriate Mac algorithm based on a
* byte[] array password.
*
* @param secretKeyBytes
* @return the secret key for the SignedInfo element.
*/
public SecretKey createSecretKey(byte[] secretKeyBytes) {
return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
}
public SignatureAlgorithm getSignatureAlgorithm() {
return signatureAlgorithm;
}
/**
* Method getBaseLocalName
* {@inheritDoc}
*
*/
@Override
public String getBaseLocalName() {
return Constants._TAG_SIGNEDINFO;
}
public String getInclusiveNamespaces() {
String c14nMethodURI = getCanonicalizationMethodURI();
if (!("http://www.w3.org/2001/10/xml-exc-c14n#".equals(c14nMethodURI) ||
"http://www.w3.org/2001/10/xml-exc-c14n#WithComments".equals(c14nMethodURI))) {
return null;
}
Element inclusiveElement = XMLUtils.getNextElement(c14nMethod.getFirstChild());
if (inclusiveElement != null) {
try {
String inclusiveNamespaces =
new InclusiveNamespaces(
inclusiveElement,
InclusiveNamespaces.ExclusiveCanonicalizationNamespace
).getInclusiveNamespaces();
return inclusiveNamespaces;
} catch (XMLSecurityException e) {
return null;
}
}
return null;
}
}

View file

@ -0,0 +1,64 @@
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import java.util.Collections;
import java.util.List;
/**
* Holds the result of a Reference validation.
*/
public class VerifiedReference {
private final boolean valid;
private final String uri;
private final List<VerifiedReference> manifestReferences;
/**
* @param valid Whether this Reference was successfully validated or not
* @param uri The URI of this Reference
* @param manifestReferences If this reference is a reference to a Manifest, this holds the list
* of verified references associated with this Manifest
*/
public VerifiedReference(boolean valid, String uri, List<VerifiedReference> manifestReferences) {
this.valid = valid;
this.uri = uri;
if (manifestReferences != null) {
this.manifestReferences = manifestReferences;
} else {
this.manifestReferences = Collections.emptyList();
}
}
public boolean isValid() {
return valid;
}
public String getUri() {
return uri;
}
public List<VerifiedReference> getManifestReferences() {
return Collections.unmodifiableList(manifestReferences);
}
}

Some files were not shown because too many files have changed in this diff Show more