diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java index 845323dd5ee..6d386c682df 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/Init.java @@ -22,12 +22,15 @@ */ 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; @@ -89,13 +92,18 @@ public class Init { if (cfile == null) { return null; } - return Init.class.getResourceAsStream(cfile); + return getResourceAsStream(cfile, Init.class); } ); if (is == null) { dynamicInit(); } else { fileInit(is); + try { + is.close(); + } catch (IOException ex) { + LOG.warn(ex.getMessage()); + } } alreadyInitialized = true; @@ -168,7 +176,7 @@ public class Init { private static void fileInit(InputStream is) { try { /* read library configuration file */ - Document doc = XMLUtils.read(is, false); + Document doc = XMLUtils.read(is, true); Node config = doc.getFirstChild(); for (; config != null; config = config.getNextSibling()) { if ("Configuration".equals(config.getLocalName())) { @@ -208,7 +216,7 @@ public class Init { Canonicalizer.register(uri, javaClass); LOG.debug("Canonicalizer.register({}, {})", uri, javaClass); } catch (ClassNotFoundException e) { - Object exArgs[] = { uri, javaClass }; + Object[] exArgs = { uri, javaClass }; LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } } @@ -226,7 +234,7 @@ public class Init { Transform.register(uri, javaClass); LOG.debug("Transform.register({}, {})", uri, javaClass); } catch (ClassNotFoundException e) { - Object exArgs[] = { uri, javaClass }; + Object[] exArgs = { uri, javaClass }; LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } catch (NoClassDefFoundError ex) { @@ -262,7 +270,7 @@ public class Init { SignatureAlgorithm.register(uri, javaClass); LOG.debug("SignatureAlgorithm.register({}, {})", uri, javaClass); } catch (ClassNotFoundException e) { - Object exArgs[] = { uri, javaClass }; + Object[] exArgs = { uri, javaClass }; LOG.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } @@ -272,7 +280,7 @@ public class Init { if ("ResourceResolvers".equals(tag)) { Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); - + List classNames = new ArrayList<>(resolverElem.length); for (Element element : resolverElem) { String javaClass = element.getAttributeNS(null, "JAVACLASS"); @@ -284,16 +292,9 @@ public class Init { } else { LOG.debug("Register Resolver: {}: For unknown purposes", javaClass); } - try { - ResourceResolver.register(javaClass); - } catch (Throwable e) { - LOG.warn( - "Cannot register:" + javaClass - + " perhaps some needed jars are not installed", - e - ); - } + classNames.add(javaClass); } + ResourceResolver.registerClassNames(classNames); } if ("KeyResolver".equals(tag)){ @@ -335,6 +336,170 @@ public class Init { LOG.error("Bad: ", e); } } + /** + * Load a given resource.

This method will try to load the resource + * using the following methods (in order): + * + * + * @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) { + 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.

This method will try to load the resources + * using the following methods (in order): + * + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + private static List getResources(String resourceName, Class callingClass) { + List ret = new ArrayList<>(); + Enumeration urls = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + 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 != null && resourceName.charAt(0) != '/') { + return getResources('/' + resourceName, callingClass); + } + return ret; + } + + + /** + * This is a convenience method to load a resource as a stream.

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; + } + } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java index 41da6440fcb..46a265da6f1 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java @@ -38,8 +38,7 @@ 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 algorithmsMap = - new ConcurrentHashMap(); + private static Map algorithmsMap = new ConcurrentHashMap<>(); private static String providerName; @@ -182,6 +181,10 @@ public class JCEMapper { 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") diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java index bf39ad75613..6c3f500dbe8 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java @@ -23,6 +23,7 @@ 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; @@ -37,7 +38,7 @@ import org.w3c.dom.Document; * MessageDigestAlgorithm.getInstance() * */ -public class MessageDigestAlgorithm extends Algorithm { +public final class MessageDigestAlgorithm extends Algorithm { /** Message Digest - NOT RECOMMENDED MD5*/ public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = @@ -118,11 +119,7 @@ public class MessageDigestAlgorithm extends Algorithm { } else { md = MessageDigest.getInstance(algorithmID, provider); } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { + } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); @@ -169,7 +166,7 @@ public class MessageDigestAlgorithm extends Algorithm { * @param input * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method */ - public byte[] digest(byte input[]) { + public byte[] digest(byte[] input) { return algorithm.digest(input); } @@ -183,7 +180,7 @@ public class MessageDigestAlgorithm extends Algorithm { * @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 { + public int digest(byte[] buf, int offset, int len) throws java.security.DigestException { return algorithm.digest(buf, offset, len); } @@ -254,7 +251,7 @@ public class MessageDigestAlgorithm extends Algorithm { * @param offset * @param len */ - public void update(byte buf[], int offset, int len) { + public void update(byte[] buf, int offset, int len) { algorithm.update(buf, offset, len); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java index be1c9604997..750692f2e9b 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java @@ -22,7 +22,10 @@ */ 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; @@ -54,10 +57,10 @@ public class SignatureAlgorithm extends Algorithm { /** All available algorithm classes are registered here */ private static Map> algorithmHash = - new ConcurrentHashMap>(); + new ConcurrentHashMap<>(); /** Field signatureAlgorithm */ - private final SignatureAlgorithmSpi signatureAlgorithm; + private final SignatureAlgorithmSpi signatureAlgorithmSpi; private final String algorithmURI; @@ -69,11 +72,22 @@ public class SignatureAlgorithm extends Algorithm { * @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; - signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(getElement()); + signatureAlgorithmSpi = getSignatureAlgorithmSpi(algorithmURI, provider); + if (parameterSpec != null) { + signatureAlgorithmSpi.engineSetParameter(parameterSpec); + signatureAlgorithmSpi.engineAddContextToElement(getElement()); + } } /** @@ -86,15 +100,20 @@ public class SignatureAlgorithm extends Algorithm { */ 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; - signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(getElement()); + signatureAlgorithmSpi = getSignatureAlgorithmSpi(algorithmURI, provider); - signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength); - ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(getElement()); + signatureAlgorithmSpi.engineSetHMACOutputLength(hmacOutputLength); + signatureAlgorithmSpi.engineAddContextToElement(getElement()); } /** @@ -105,7 +124,11 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSecurityException */ public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException { - this(element, baseURI, true); + this(element, baseURI, true, null); + } + + public SignatureAlgorithm(Element element, String baseURI, Provider provider) throws XMLSecurityException { + this(element, baseURI, true, provider); } /** @@ -118,6 +141,12 @@ public class SignatureAlgorithm extends Algorithm { */ 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(); @@ -129,33 +158,42 @@ public class SignatureAlgorithm extends Algorithm { 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 }; + Object[] exArgs = { algorithmURI }; throw new XMLSecurityException("signature.signatureAlgorithm", exArgs); } - signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(getElement()); + signatureAlgorithmSpi = getSignatureAlgorithmSpi(algorithmURI, provider); + signatureAlgorithmSpi.engineGetContextFromElement(getElement()); } /** * Get a SignatureAlgorithmSpi object corresponding to the algorithmURI argument */ - private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI) + private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI, Provider provider) throws XMLSignatureException { try { - Class implementingClass = - algorithmHash.get(algorithmURI); + Class implementingClass = algorithmHash.get(algorithmURI); LOG.debug("Create URI \"{}\" class \"{}\"", algorithmURI, implementingClass); if (implementingClass == null) { - Object exArgs[] = { algorithmURI }; + Object[] exArgs = { algorithmURI }; throw new XMLSignatureException("algorithms.NoSuchAlgorithmNoEx", exArgs); } - @SuppressWarnings("deprecation") - SignatureAlgorithmSpi tmp = implementingClass.newInstance(); - return tmp; - } catch (IllegalAccessException | InstantiationException | NullPointerException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; + + if (provider != null) { + try { + Constructor 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); } } @@ -169,7 +207,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public byte[] sign() throws XMLSignatureException { - return signatureAlgorithm.engineSign(); + return signatureAlgorithmSpi.engineSign(); } /** @@ -179,7 +217,7 @@ public class SignatureAlgorithm extends Algorithm { * @return the result of the {@link java.security.Signature#getAlgorithm} method */ public String getJCEAlgorithmString() { - return signatureAlgorithm.engineGetJCEAlgorithmString(); + return signatureAlgorithmSpi.engineGetJCEAlgorithmString(); } /** @@ -188,7 +226,7 @@ public class SignatureAlgorithm extends Algorithm { * @return The Provider of this Signature Algorithm */ public String getJCEProviderName() { - return signatureAlgorithm.engineGetJCEProviderName(); + return signatureAlgorithmSpi.engineGetJCEProviderName(); } /** @@ -199,7 +237,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public void update(byte[] input) throws XMLSignatureException { - signatureAlgorithm.engineUpdate(input); + signatureAlgorithmSpi.engineUpdate(input); } /** @@ -210,7 +248,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public void update(byte input) throws XMLSignatureException { - signatureAlgorithm.engineUpdate(input); + signatureAlgorithmSpi.engineUpdate(input); } /** @@ -222,8 +260,8 @@ public class SignatureAlgorithm extends Algorithm { * @param len * @throws XMLSignatureException */ - public void update(byte buf[], int offset, int len) throws XMLSignatureException { - signatureAlgorithm.engineUpdate(buf, offset, len); + public void update(byte[] buf, int offset, int len) throws XMLSignatureException { + signatureAlgorithmSpi.engineUpdate(buf, offset, len); } /** @@ -234,7 +272,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public void initSign(Key signingKey) throws XMLSignatureException { - signatureAlgorithm.engineInitSign(signingKey); + signatureAlgorithmSpi.engineInitSign(signingKey); } /** @@ -247,7 +285,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public void initSign(Key signingKey, SecureRandom secureRandom) throws XMLSignatureException { - signatureAlgorithm.engineInitSign(signingKey, secureRandom); + signatureAlgorithmSpi.engineInitSign(signingKey, secureRandom); } /** @@ -261,7 +299,7 @@ public class SignatureAlgorithm extends Algorithm { public void initSign( Key signingKey, AlgorithmParameterSpec algorithmParameterSpec ) throws XMLSignatureException { - signatureAlgorithm.engineInitSign(signingKey, algorithmParameterSpec); + signatureAlgorithmSpi.engineInitSign(signingKey, algorithmParameterSpec); } /** @@ -273,7 +311,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public void setParameter(AlgorithmParameterSpec params) throws XMLSignatureException { - signatureAlgorithm.engineSetParameter(params); + signatureAlgorithmSpi.engineSetParameter(params); } /** @@ -284,7 +322,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public void initVerify(Key verificationKey) throws XMLSignatureException { - signatureAlgorithm.engineInitVerify(verificationKey); + signatureAlgorithmSpi.engineInitVerify(verificationKey); } /** @@ -297,7 +335,7 @@ public class SignatureAlgorithm extends Algorithm { * @throws XMLSignatureException */ public boolean verify(byte[] signature) throws XMLSignatureException { - return signatureAlgorithm.engineVerify(signature); + return signatureAlgorithmSpi.engineVerify(signature); } /** @@ -330,7 +368,7 @@ public class SignatureAlgorithm extends Algorithm { // are we already registered? Class registeredClass = algorithmHash.get(algorithmURI); if (registeredClass != null) { - Object exArgs[] = { algorithmURI, registeredClass }; + Object[] exArgs = { algorithmURI, registeredClass }; throw new AlgorithmAlreadyRegisteredException( "algorithm.alreadyRegistered", exArgs ); @@ -341,7 +379,7 @@ public class SignatureAlgorithm extends Algorithm { ClassLoaderUtils.loadClass(implementingClass, SignatureAlgorithm.class); algorithmHash.put(algorithmURI, clazz); } catch (NullPointerException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; + Object[] exArgs = { algorithmURI, ex.getMessage() }; throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs); } } @@ -366,7 +404,7 @@ public class SignatureAlgorithm extends Algorithm { // are we already registered? Class registeredClass = algorithmHash.get(algorithmURI); if (registeredClass != null) { - Object exArgs[] = { algorithmURI, registeredClass }; + Object[] exArgs = { algorithmURI, registeredClass }; throw new AlgorithmAlreadyRegisteredException( "algorithm.alreadyRegistered", exArgs ); @@ -425,6 +463,9 @@ public class SignatureAlgorithm extends Algorithm { 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 ); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java index 7796a990160..a049733c0ad 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java @@ -22,8 +22,7 @@ */ package com.sun.org.apache.xml.internal.security.algorithms; -import java.security.Key; -import java.security.SecureRandom; +import java.security.*; import java.security.spec.AlgorithmParameterSpec; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; @@ -80,7 +79,7 @@ public abstract class SignatureAlgorithmSpi { * @param len * @throws XMLSignatureException */ - protected abstract void engineUpdate(byte buf[], int offset, int len) + protected abstract void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException; /** @@ -160,7 +159,10 @@ public abstract class SignatureAlgorithmSpi { * * @param element */ - protected void engineGetContextFromElement(Element element) { + protected void engineGetContextFromElement(Element element) throws XMLSignatureException { + } + + protected void engineAddContextToElement(Element element) throws XMLSignatureException { } /** @@ -172,6 +174,47 @@ public abstract class SignatureAlgorithmSpi { protected abstract void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException; - public void reset() { + 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); + } + } + } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java index 719af4c0508..63449eee9bb 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java @@ -20,6 +20,9 @@ * 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; @@ -50,7 +53,7 @@ public final class ECDSAUtils { * @see 6.4.1 DSA * @see 3.3. ECDSA Signatures */ - public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[], int rawLen) throws IOException { + 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"); } @@ -87,7 +90,7 @@ public final class ECDSAUtils { || asn1Bytes[offset + 2 + rLength] != 2) { throw new IOException("Invalid ASN.1 format of ECDSA signature"); } - byte xmldsigBytes[] = new byte[2 * rawLen]; + 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, @@ -108,7 +111,7 @@ public final class ECDSAUtils { * @see 6.4.1 DSA * @see 3.3. ECDSA Signatures */ - public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { + public static byte[] convertXMLDSIGtoASN1(byte[] xmldsigBytes) throws IOException { int rawLen = xmldsigBytes.length / 2; @@ -137,7 +140,7 @@ public final class ECDSAUtils { throw new IOException("Invalid XMLDSIG format of ECDSA signature"); } int offset; - byte asn1Bytes[]; + byte[] asn1Bytes; if (len < 128) { asn1Bytes = new byte[2 + 2 + j + 2 + l]; offset = 1; @@ -884,9 +887,9 @@ public final class ECDSAUtils { 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]; + 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); @@ -899,8 +902,8 @@ public final class ECDSAUtils { } int size = (elliptiCcurve.getField().getFieldSize() + 7) / 8; - byte affineXBytes[] = new byte[size]; - byte affineYBytes[] = new byte[size]; + 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)); @@ -917,7 +920,7 @@ public final class ECDSAUtils { if (i == 0) { return bytes; } else { - byte stripped[] = new byte[bytes.length - i]; + byte[] stripped = new byte[bytes.length - i]; System.arraycopy(bytes, i, stripped, 0, stripped.length); return stripped; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index 98e3dc35537..90302d47844 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -25,6 +25,7 @@ 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; @@ -49,18 +50,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { com.sun.org.slf4j.internal.LoggerFactory.getLogger(IntegrityHmac.class); /** Field macAlgorithm */ - private Mac macAlgorithm; + private final Mac macAlgorithm; - /** Field HMACOutputLength */ - private int HMACOutputLength; - private boolean HMACOutputLengthSet = false; - - /** - * Method engineGetURI - * - *{@inheritDoc} - */ - public abstract String engineGetURI(); + /** Field hmacOutputLength */ + private HMACOutputLength hmacOutputLength; /** * Returns the output length of the hash/digest. @@ -73,11 +66,15 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { * @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 = Mac.getInstance(algorithmID); + this.macAlgorithm = (provider == null) ? Mac.getInstance(algorithmID) : Mac.getInstance(algorithmID, provider); } catch (java.security.NoSuchAlgorithmException ex) { Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; @@ -97,12 +94,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { throw new XMLSignatureException("empty", new Object[]{"Incorrect method call"}); } - public void reset() { - HMACOutputLength = 0; - HMACOutputLengthSet = false; - this.macAlgorithm.reset(); - } - /** * Proxy method for {@link java.security.Signature#verify(byte[])} * which is executed on the internal {@link java.security.Signature} object. @@ -113,7 +104,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { */ protected boolean engineVerify(byte[] signature) throws XMLSignatureException { try { - if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + 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); @@ -140,7 +131,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { supplied = secretKey.getClass().getName(); } String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + Object[] exArgs = { supplied, needed }; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } @@ -148,16 +139,6 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { try { this.macAlgorithm.init(secretKey); } catch (InvalidKeyException ex) { - // reinstantiate Mac object to work around bug in JDK - // see: http://bugs.java.com/view_bug.do?bug_id=4953555 - Mac mac = this.macAlgorithm; - try { - this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm()); - } catch (Exception e) { - // this shouldn't occur, but if it does, restore previous Mac - LOG.debug("Exception when reinstantiating Mac: {}", e); - this.macAlgorithm = mac; - } throw new XMLSignatureException(ex); } } @@ -171,7 +152,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { */ protected byte[] engineSign() throws XMLSignatureException { try { - if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + 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); @@ -209,7 +190,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { supplied = secretKey.getClass().getName(); } String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + Object[] exArgs = { supplied, needed }; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } @@ -220,9 +201,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { } else { this.macAlgorithm.init(secretKey, algorithmParameterSpec); } - } catch (InvalidKeyException ex) { - throw new XMLSignatureException(ex); - } catch (InvalidAlgorithmParameterException ex) { + } catch (InvalidKeyException | InvalidAlgorithmParameterException ex) { throw new XMLSignatureException(ex); } } @@ -278,7 +257,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { * @param len * @throws XMLSignatureException */ - protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException { try { this.macAlgorithm.update(buf, offset, len); } catch (IllegalStateException ex) { @@ -307,21 +286,22 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { /** * Method engineSetHMACOutputLength * - * @param HMACOutputLength + * @param length + * @throws XMLSignatureException */ - protected void engineSetHMACOutputLength(int HMACOutputLength) { - this.HMACOutputLength = HMACOutputLength; - this.HMACOutputLengthSet = true; + @Override + protected void engineSetHMACOutputLength(int length) throws XMLSignatureException { + hmacOutputLength = new HMACOutputLength(length); } /** * Method engineGetContextFromElement * * @param element + * @throws XMLSignatureException */ - protected void engineGetContextFromElement(Element element) { - super.engineGetContextFromElement(element); - + @Override + protected void engineGetContextFromElement(Element element) throws XMLSignatureException { if (element == null) { throw new IllegalArgumentException("element null"); } @@ -330,8 +310,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { if (n != null) { String hmacLength = XMLUtils.getFullTextChildrenFromNode(n); if (hmacLength != null && !"".equals(hmacLength)) { - this.HMACOutputLength = Integer.parseInt(hmacLength); - this.HMACOutputLengthSet = true; + this.hmacOutputLength = new HMACOutputLength(Integer.parseInt(hmacLength)); } } } @@ -341,17 +320,18 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { * * @param element */ - public void engineAddContextToElement(Element element) { + @Override + protected void engineAddContextToElement(Element element) throws XMLSignatureException { if (element == null) { throw new IllegalArgumentException("null element"); } - if (this.HMACOutputLengthSet) { + if (hmacOutputLength != null) { Document doc = element.getOwnerDocument(); Element HMElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); Text HMText = - doc.createTextNode("" + this.HMACOutputLength); + doc.createTextNode("" + hmacOutputLength.length); HMElem.appendChild(HMText); XMLUtils.addReturnToElement(element); @@ -374,15 +354,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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; } @@ -402,15 +388,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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; } @@ -430,15 +422,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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; } @@ -458,15 +456,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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; } @@ -486,15 +490,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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; } @@ -514,15 +524,21 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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; } @@ -542,17 +558,45 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { 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); + } + } + } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java index 4648ee1c2a5..e24455a355c 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java @@ -23,11 +23,10 @@ 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.NoSuchAlgorithmException; import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; +import java.security.Provider; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; @@ -37,17 +36,22 @@ 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 java.security.spec.MGF1ParameterSpec; +import java.security.spec.PSSParameterSpec; 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); - /** {@inheritDoc} */ - public abstract String engineGetURI(); - /** Field algorithm */ - private Signature signatureAlgorithm; + private final Signature signatureAlgorithm; /** * Constructor SignatureRSA @@ -55,23 +59,29 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { * @throws XMLSignatureException */ public SignatureBaseRSA() throws XMLSignatureException { - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + this(null); + } + public SignatureBaseRSA(Provider provider) throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); LOG.debug("Created SignatureRSA using {}", algorithmID); - String provider = JCEMapper.getProviderId(); + try { if (provider == null) { - this.signatureAlgorithm = Signature.getInstance(algorithmID); + 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 (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { + Object[] exArgs = {algorithmID, ex.getLocalizedMessage()}; throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); } } @@ -97,33 +107,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** {@inheritDoc} */ protected void engineInitVerify(Key publicKey) 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 { - this.signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { - // reinstantiate Signature object to work around bug in JDK - // see: http://bugs.java.com/view_bug.do?bug_id=4953555 - Signature sig = this.signatureAlgorithm; - try { - this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); - } catch (Exception e) { - // this shouldn't occur, but if it does, restore previous - // Signature - LOG.debug("Exception when reinstantiating Signature: {}", e); - this.signatureAlgorithm = sig; - } - throw new XMLSignatureException(ex); - } + engineInitVerify(publicKey, this.signatureAlgorithm); } /** {@inheritDoc} */ @@ -138,26 +122,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** {@inheritDoc} */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) 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) { - this.signatureAlgorithm.initSign((PrivateKey) privateKey); - } else { - this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); - } - } catch (InvalidKeyException ex) { - throw new XMLSignatureException(ex); - } + engineInitSign(privateKey, secureRandom, this.signatureAlgorithm); } /** {@inheritDoc} */ @@ -184,7 +149,7 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { } /** {@inheritDoc} */ - protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException { try { this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { @@ -229,7 +194,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1; } @@ -249,7 +219,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA224(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224; } @@ -269,7 +244,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA256(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; } @@ -289,7 +269,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA384(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; } @@ -309,7 +294,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA512(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; } @@ -329,7 +319,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSARIPEMD160(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; } @@ -349,7 +344,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSAMD5(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5; } @@ -369,7 +369,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA1MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1; } @@ -389,7 +394,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA224MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1; } @@ -409,7 +419,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA256MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1; } @@ -429,7 +444,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA384MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1; } @@ -449,7 +469,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA512MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1; } @@ -469,7 +494,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA3_224MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1; } @@ -489,7 +519,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA3_256MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1; } @@ -509,7 +544,12 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA3_384MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1; } @@ -529,9 +569,155 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { super(); } + public SignatureRSASHA3_512MGF1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1; } } + + public static class SignatureRSASSAPSS extends SignatureBaseRSA { + PSSParameterSpec pssParameterSpec; + + public enum DigestAlgorithm { + SHA256("SHA-256", "http://www.w3.org/2001/04/xmlenc#sha256", 32), + SHA384("SHA-384", "http://www.w3.org/2001/04/xmldsig-more#sha384", 48), + SHA512("SHA-512", "http://www.w3.org/2001/04/xmlenc#sha512", 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); + } + + } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java index db41d7d17df..0f9f8463252 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java @@ -24,10 +24,10 @@ package com.sun.org.apache.xml.internal.security.algorithms.implementations; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; import java.security.Key; -import java.security.PrivateKey; -import java.security.PublicKey; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Provider; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; @@ -50,7 +50,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureDSA.class); /** Field algorithm */ - private Signature signatureAlgorithm; + private final Signature signatureAlgorithm; /** size of Q */ private int size; @@ -70,22 +70,29 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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); - String provider = JCEMapper.getProviderId(); try { if (provider == null) { - this.signatureAlgorithm = Signature.getInstance(algorithmID); + 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); + this.signatureAlgorithm = Signature.getInstance(algorithmID, provider); } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (java.security.NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { + Object[] exArgs = {algorithmID, ex.getLocalizedMessage()}; throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); } } @@ -112,13 +119,10 @@ public class SignatureDSA extends SignatureAlgorithmSpi { LOG.debug("Called DSA.verify() on " + XMLUtils.encodeToString(signature)); } - byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature, - size/8); + byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature, size / 8); return this.signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException(ex); - } catch (IOException ex) { + } catch (SignatureException | IOException ex) { throw new XMLSignatureException(ex); } } @@ -127,33 +131,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * {@inheritDoc} */ protected void engineInitVerify(Key publicKey) 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 { - this.signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { - // reinstantiate Signature object to work around bug in JDK - // see: http://bugs.java.com/view_bug.do?bug_id=4953555 - Signature sig = this.signatureAlgorithm; - try { - this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); - } catch (Exception e) { - // this shouldn't occur, but if it does, restore previous - // Signature - LOG.debug("Exception when reinstantiating Signature: {}", e); - this.signatureAlgorithm = sig; - } - throw new XMLSignatureException(ex); - } + engineInitVerify(publicKey, this.signatureAlgorithm); size = ((DSAKey)publicKey).getParams().getQ().bitLength(); } @@ -162,12 +140,10 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ protected byte[] engineSign() throws XMLSignatureException { try { - byte jcebytes[] = this.signatureAlgorithm.sign(); + byte[] jcebytes = this.signatureAlgorithm.sign(); - return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size/8); - } catch (IOException ex) { - throw new XMLSignatureException(ex); - } catch (SignatureException ex) { + return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size / 8); + } catch (IOException | SignatureException ex) { throw new XMLSignatureException(ex); } } @@ -177,26 +153,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) 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) { - this.signatureAlgorithm.initSign((PrivateKey) privateKey); - } else { - this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); - } - } catch (InvalidKeyException ex) { - throw new XMLSignatureException(ex); - } + engineInitSign(privateKey, secureRandom, this.signatureAlgorithm); size = ((DSAKey)privateKey).getParams().getQ().bitLength(); } @@ -232,7 +189,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { /** * {@inheritDoc} */ - protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException { try { this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { @@ -287,6 +244,11 @@ public class SignatureDSA extends SignatureAlgorithmSpi { super(); } + public SHA256(Provider provider) throws XMLSignatureException { + super(provider); + } + + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java index 8c2931bb9f9..381ead9ec2e 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java @@ -20,18 +20,13 @@ * 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.InvalidKeyException; -import java.security.Key; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; +import java.security.*; import java.security.interfaces.ECPrivateKey; import java.security.spec.AlgorithmParameterSpec; @@ -49,11 +44,7 @@ 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); - /** {@inheritDoc} */ - public abstract String engineGetURI(); - - /** Field algorithm */ - private Signature signatureAlgorithm; + private final Signature signatureAlgorithm; /** Length for each integer in signature */ private int signIntLen = -1; @@ -72,7 +63,7 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { * @see 6.4.1 DSA * @see 3.3. ECDSA Signatures */ - public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[], int rawLen) throws IOException { + public static byte[] convertASN1toXMLDSIG(byte[] asn1Bytes, int rawLen) throws IOException { return ECDSAUtils.convertASN1toXMLDSIG(asn1Bytes, rawLen); } @@ -89,7 +80,7 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { * @see 6.4.1 DSA * @see 3.3. ECDSA Signatures */ - public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { + public static byte[] convertXMLDSIGtoASN1(byte[] xmldsigBytes) throws IOException { return ECDSAUtils.convertXMLDSIGtoASN1(xmldsigBytes); } @@ -99,24 +90,29 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { * @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); - String provider = JCEMapper.getProviderId(); + try { if (provider == null) { - this.signatureAlgorithm = Signature.getInstance(algorithmID); + 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 (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { + } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); } } @@ -141,53 +137,22 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { } return this.signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException(ex); - } catch (IOException ex) { + } catch (SignatureException | IOException ex) { throw new XMLSignatureException(ex); } } /** {@inheritDoc} */ protected void engineInitVerify(Key publicKey) 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 { - this.signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { - // reinstantiate Signature object to work around bug in JDK - // see: http://bugs.java.com/view_bug.do?bug_id=4953555 - Signature sig = this.signatureAlgorithm; - try { - this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); - } catch (Exception e) { - // this shouldn't occur, but if it does, restore previous - // Signature - LOG.debug("Exception when reinstantiating Signature: {}", e); - this.signatureAlgorithm = sig; - } - throw new XMLSignatureException(ex); - } + engineInitVerify(publicKey, signatureAlgorithm); } /** {@inheritDoc} */ protected byte[] engineSign() throws XMLSignatureException { try { - byte jcebytes[] = this.signatureAlgorithm.sign(); + byte[] jcebytes = this.signatureAlgorithm.sign(); return SignatureECDSA.convertASN1toXMLDSIG(jcebytes, signIntLen); - } catch (SignatureException ex) { - throw new XMLSignatureException(ex); - } catch (IOException ex) { + } catch (SignatureException | IOException ex) { throw new XMLSignatureException(ex); } } @@ -195,31 +160,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { /** {@inheritDoc} */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) 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 (privateKey instanceof ECPrivateKey) { - ECPrivateKey ecKey = (ECPrivateKey)privateKey; - signIntLen = (ecKey.getParams().getCurve().getField().getFieldSize() + 7) / 8; - // If not ECPrivateKey, signIntLen remains -1 - } - if (secureRandom == null) { - this.signatureAlgorithm.initSign((PrivateKey) privateKey); - } else { - this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); - } - } catch (InvalidKeyException ex) { - throw new XMLSignatureException(ex); + 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} */ @@ -246,7 +192,7 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { } /** {@inheritDoc} */ - protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + protected void engineUpdate(byte[] buf, int offset, int len) throws XMLSignatureException { try { this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { @@ -291,7 +237,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { super(); } + public SignatureECDSASHA1(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; } @@ -311,7 +262,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { super(); } + public SignatureECDSASHA224(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224; } @@ -332,7 +288,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { super(); } + public SignatureECDSASHA256(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256; } @@ -353,7 +314,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { super(); } + public SignatureECDSASHA384(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384; } @@ -374,7 +340,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { super(); } + public SignatureECDSASHA512(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512; } @@ -394,7 +365,12 @@ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { super(); } + public SignatureECDSARIPEMD160(Provider provider) throws XMLSignatureException { + super(provider); + } + /** {@inheritDoc} */ + @Override public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java index c797cbc4c5d..91b788b4755 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java @@ -62,7 +62,7 @@ public class CanonicalizationException extends XMLSecurityException { * @param msgID * @param exArgs */ - public CanonicalizationException(String msgID, Object exArgs[]) { + public CanonicalizationException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -89,13 +89,13 @@ public class CanonicalizationException extends XMLSecurityException { * @param exArgs */ public CanonicalizationException( - Exception originalException, String msgID, Object exArgs[] + Exception originalException, String msgID, Object[] exArgs ) { super(originalException, msgID, exArgs); } @Deprecated - public CanonicalizationException(String msgID, Object exArgs[], Exception originalException) { + public CanonicalizationException(String msgID, Object[] exArgs, Exception originalException) { this(originalException, msgID, exArgs); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java index 1f33ee135c2..71e2d976b57 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java @@ -22,8 +22,6 @@ */ package com.sun.org.apache.xml.internal.security.c14n; -import java.io.ByteArrayInputStream; -import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -38,17 +36,14 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicaliz 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 com.sun.org.apache.xml.internal.security.utils.XMLUtils; -import org.w3c.dom.Document; import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; /** * */ -public class Canonicalizer { +public final class Canonicalizer { /** The output encoding of canonicalized data */ public static final String ENCODING = StandardCharsets.UTF_8.name(); @@ -97,10 +92,9 @@ public class Canonicalizer { "http://santuario.apache.org/c14n/physical"; private static Map> canonicalizerHash = - new ConcurrentHashMap>(); + new ConcurrentHashMap<>(); private final CanonicalizerSpi canonicalizerSpi; - private boolean secureValidation; /** * Constructor Canonicalizer @@ -112,13 +106,9 @@ public class Canonicalizer { try { Class implementingClass = canonicalizerHash.get(algorithmURI); - - @SuppressWarnings("deprecation") - CanonicalizerSpi tmp = implementingClass.newInstance(); - canonicalizerSpi = tmp; - canonicalizerSpi.reset = true; + canonicalizerSpi = JavaUtils.newInstanceWithEmptyConstructor(implementingClass); } catch (Exception e) { - Object exArgs[] = { algorithmURI }; + Object[] exArgs = { algorithmURI }; throw new InvalidCanonicalizerException( e, "signature.Canonicalizer.UnknownCanonicalizer", exArgs ); @@ -155,7 +145,7 @@ public class Canonicalizer { canonicalizerHash.get(algorithmURI); if (registeredClass != null) { - Object exArgs[] = { algorithmURI, registeredClass }; + Object[] exArgs = { algorithmURI, registeredClass }; throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs); } @@ -181,7 +171,7 @@ public class Canonicalizer { Class registeredClass = canonicalizerHash.get(algorithmURI); if (registeredClass != null) { - Object exArgs[] = { algorithmURI, registeredClass }; + Object[] exArgs = { algorithmURI, registeredClass }; throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs); } @@ -222,73 +212,33 @@ public class Canonicalizer { ); } - /** - * Method getURI - * - * @return the URI defined for this c14n instance. - */ - public final String getURI() { - return canonicalizerSpi.engineGetURI(); - } - - /** - * Method getIncludeComments - * - * @return true if the c14n respect the comments. - */ - public boolean getIncludeComments() { - return canonicalizerSpi.engineGetIncludeComments(); - } - /** * 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 >a<...>/a<}. * * @param inputBytes - * @return the result of the canonicalization. + * @param writer OutputStream to write the canonicalization result + * @param secureValidation Whether secure validation is enabled * @throws CanonicalizationException * @throws java.io.IOException - * @throws javax.xml.parsers.ParserConfigurationException - * @throws org.xml.sax.SAXException + * @throws XMLParserException */ - public byte[] canonicalize(byte[] inputBytes) - throws javax.xml.parsers.ParserConfigurationException, - java.io.IOException, org.xml.sax.SAXException, CanonicalizationException { - Document document = null; - try (InputStream bais = new ByteArrayInputStream(inputBytes)) { - InputSource in = new InputSource(bais); - - /* - * Text from the spec: - * - * The input octet stream MUST contain a well-formed XML document, - * but the input need not be validated. However, the attribute - * value normalization and entity reference resolution MUST be - * performed in accordance with the behaviors of a validating - * XML processor. As well, nodes for default attributes (declared - * in the ATTLIST with an AttValue but not specified) are created - * in each element. Thus, the declarations in the document type - * declaration are used to help create the canonical form, even - * though the document type declaration is not retained in the - * canonical form. - */ - document = XMLUtils.read(in, secureValidation); - } - return this.canonicalizeSubtree(document); + 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 - * @return the result of the c14n. + * @param writer OutputStream to write the canonicalization result * * @throws CanonicalizationException */ - public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return canonicalizerSpi.engineCanonicalizeSubTree(node); + public void canonicalizeSubtree(Node node, OutputStream writer) throws CanonicalizationException { + canonicalizerSpi.engineCanonicalizeSubTree(node, writer); } /** @@ -296,13 +246,12 @@ public class Canonicalizer { * * @param node * @param inclusiveNamespaces - * @return the result of the c14n. + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces) + public void canonicalizeSubtree(Node node, String inclusiveNamespaces, OutputStream writer) throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces); + canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, writer); } /** @@ -310,57 +259,25 @@ public class Canonicalizer { * * @param node * @param inclusiveNamespaces - * @return the result of the c14n. + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces, boolean propagateDefaultNamespace) + public void canonicalizeSubtree(Node node, String inclusiveNamespaces, + boolean propagateDefaultNamespace, OutputStream writer) throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, propagateDefaultNamespace); - } - - /** - * Canonicalizes an XPath node set. The {@code xpathNodeSet} is treated - * as a list of XPath nodes, not as a list of subtrees. - * - * @param xpathNodeSet - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet) - throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); - } - - /** - * Canonicalizes an XPath node set. The {@code xpathNodeSet} is treated - * as a list of XPath nodes, not as a list of subtrees. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the result of the c14n. - * @throws CanonicalizationException - */ - public byte[] canonicalizeXPathNodeSet( - NodeList xpathNodeSet, String inclusiveNamespaces - ) throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return - canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); + canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, propagateDefaultNamespace, writer); } /** * Canonicalizes an XPath node set. * * @param xpathNodeSet - * @return the result of the c14n. + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet) + public void canonicalizeXPathNodeSet(Set xpathNodeSet, OutputStream writer) throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); + canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, writer); } /** @@ -368,48 +285,13 @@ public class Canonicalizer { * * @param xpathNodeSet * @param inclusiveNamespaces - * @return the result of the c14n. + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] canonicalizeXPathNodeSet( - Set xpathNodeSet, String inclusiveNamespaces + public void canonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces, OutputStream writer ) throws CanonicalizationException { - canonicalizerSpi.secureValidation = secureValidation; - return - canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); - } - - /** - * Sets the writer where the canonicalization ends. ByteArrayOutputStream - * if none is set. - * @param os - */ - public void setWriter(OutputStream os) { - canonicalizerSpi.setWriter(os); - } - - /** - * Returns the name of the implementing {@link CanonicalizerSpi} class - * - * @return the name of the implementing {@link CanonicalizerSpi} class - */ - public String getImplementingCanonicalizerClass() { - return canonicalizerSpi.getClass().getName(); - } - - /** - * Set the canonicalizer behaviour to not reset. - */ - public void notReset() { - canonicalizerSpi.reset = false; - } - - public boolean isSecureValidation() { - return secureValidation; - } - - public void setSecureValidation(boolean secureValidation) { - this.secureValidation = secureValidation; + canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces, writer); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java index 9599e07a504..6d31f04c0cb 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java @@ -26,11 +26,10 @@ 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; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; /** * Base class which all Canonicalization algorithms extend. @@ -38,61 +37,25 @@ import org.xml.sax.InputSource; */ public abstract class CanonicalizerSpi { - /** Reset the writer after a c14n */ - protected boolean reset = false; - protected boolean secureValidation; - /** * Method canonicalize * * @param inputBytes - * @return the c14n bytes. + * @param writer OutputStream to write the canonicalization result + * @param secureValidation Whether secure validation is enabled * - * @throws CanonicalizationException + * @throws XMLParserException * @throws java.io.IOException * @throws javax.xml.parsers.ParserConfigurationException - * @throws org.xml.sax.SAXException */ - public byte[] engineCanonicalize(byte[] inputBytes) - throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, - org.xml.sax.SAXException, CanonicalizationException { + 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)) { - InputSource in = new InputSource(bais); - - document = XMLUtils.read(in, secureValidation); + document = XMLUtils.read(bais, secureValidation); } - return this.engineCanonicalizeSubTree(document); - } - - /** - * Method engineCanonicalizeXPathNodeSet - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) - throws CanonicalizationException { - return this.engineCanonicalizeXPathNodeSet( - XMLUtils.convertNodelistToSet(xpathNodeSet) - ); - } - - /** - * Method engineCanonicalizeXPathNodeSet - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { - return this.engineCanonicalizeXPathNodeSet( - XMLUtils.convertNodelistToSet(xpathNodeSet), inclusiveNamespaces - ); + this.engineCanonicalizeSubTree(document, writer); } /** @@ -101,20 +64,14 @@ public abstract class CanonicalizerSpi { */ public abstract String engineGetURI(); - /** - * Returns true if comments are included - * @return true if comments are included - */ - public abstract boolean engineGetIncludeComments(); - /** * C14n a nodeset * * @param xpathNodeSet - * @return the c14n bytes + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + public abstract void engineCanonicalizeXPathNodeSet(Set xpathNodeSet, OutputStream writer) throws CanonicalizationException; /** @@ -122,21 +79,21 @@ public abstract class CanonicalizerSpi { * * @param xpathNodeSet * @param inclusiveNamespaces - * @return the c14n bytes + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public abstract byte[] engineCanonicalizeXPathNodeSet( - Set xpathNodeSet, String inclusiveNamespaces + public abstract void engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces, OutputStream writer ) throws CanonicalizationException; /** * C14n a node tree. * * @param rootNode - * @return the c14n bytes + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode) + public abstract void engineCanonicalizeSubTree(Node rootNode, OutputStream writer) throws CanonicalizationException; /** @@ -144,10 +101,10 @@ public abstract class CanonicalizerSpi { * * @param rootNode * @param inclusiveNamespaces - * @return the c14n bytes + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + public abstract void engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces, OutputStream writer) throws CanonicalizationException; /** @@ -156,26 +113,12 @@ public abstract class CanonicalizerSpi { * @param rootNode * @param inclusiveNamespaces * @param propagateDefaultNamespace If true the default namespace will be propagated to the c14n-ized root element - * @return the c14n bytes + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public abstract byte[] engineCanonicalizeSubTree( - Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace) + public abstract void engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer) throws CanonicalizationException; - /** - * Sets the writer where the canonicalization ends. ByteArrayOutputStream if - * none is set. - * @param os - */ - public abstract void setWriter(OutputStream os); - - public boolean isSecureValidation() { - return secureValidation; - } - - public void setSecureValidation(boolean secureValidation) { - this.secureValidation = secureValidation; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java index 09d5e93b39a..810b90fa831 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java @@ -54,7 +54,7 @@ public class InvalidCanonicalizerException extends XMLSecurityException { * @param msgID * @param exArgs */ - public InvalidCanonicalizerException(String msgID, Object exArgs[]) { + public InvalidCanonicalizerException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -81,7 +81,7 @@ public class InvalidCanonicalizerException extends XMLSecurityException { * @param exArgs */ public InvalidCanonicalizerException( - Exception originalException, String msgID, Object exArgs[] + Exception originalException, String msgID, Object[] exArgs ) { super(originalException, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java index 6f652c41e65..3afc194fc77 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java @@ -22,11 +22,7 @@ */ package com.sun.org.apache.xml.internal.security.c14n.helper; -import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; /** * Temporary swapped static functions from the normalizer Section @@ -36,7 +32,6 @@ public final class C14nHelper { /** * Constructor C14nHelper - * */ private C14nHelper() { // don't allow instantiation @@ -86,70 +81,4 @@ public final class C14nHelper { return namespaceValue.indexOf(':') > 0; } - /** - * This method throws an exception if the Attribute value contains - * a relative URI. - * - * @param attr - * @throws CanonicalizationException - */ - public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException { - if (attr == null) { - return; - } - - String nodeAttrName = attr.getNodeName(); - boolean definesDefaultNS = "xmlns".equals(nodeAttrName); - boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); - - if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) { - String parentName = attr.getOwnerElement().getTagName(); - String attrValue = attr.getValue(); - Object exArgs[] = { parentName, nodeAttrName, attrValue }; - - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs - ); - } - } - - /** - * This method throws a CanonicalizationException if the supplied Document - * is not able to be traversed using a TreeWalker. - * - * @param document - * @throws CanonicalizationException - */ - public static void checkTraversability(Document document) - throws CanonicalizationException { - if (!document.isSupported("Traversal", "2.0")) { - Object exArgs[] = {document.getImplementation().getClass().getName() }; - - throw new CanonicalizationException( - "c14n.Canonicalizer.TraversalNotSupported", exArgs - ); - } - } - - /** - * This method throws a CanonicalizationException if the supplied Element - * contains any relative namespaces. - * - * @param ctxNode - * @throws CanonicalizationException - * @see C14nHelper#assertNotRelativeNS(Attr) - */ - public static void checkForRelativeNamespace(Element ctxNode) - throws CanonicalizationException { - if (ctxNode != null) { - NamedNodeMap attributes = ctxNode.getAttributes(); - - int length = attributes.getLength(); - for (int i = 0; i < length; i++) { - C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); - } - } else { - throw new CanonicalizationException("Called checkForRelativeNamespace() on null"); - } - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java index 17f5ffa3cfb..867faad7a8d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java @@ -36,7 +36,4 @@ public class Canonicalizer11_OmitComments extends Canonicalizer20010315 { return Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS; } - public final boolean engineGetIncludeComments() { - return false; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java index 51f9bd611b0..b4ded12429f 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java @@ -36,7 +36,4 @@ public class Canonicalizer11_WithComments extends Canonicalizer20010315 { return Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS; } - public final boolean engineGetIncludeComments() { - return true; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java index a2459351265..1ed26fea60b 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java @@ -29,10 +29,9 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import javax.xml.parsers.ParserConfigurationException; - 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; @@ -41,7 +40,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import org.xml.sax.SAXException; /** * Implements Canonical @@ -82,10 +80,10 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { * * @param xpathNodeSet * @param inclusiveNamespaces - * @return none it always fails + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException always */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + public void engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces, OutputStream writer) throws CanonicalizationException { /** $todo$ well, should we throw UnsupportedOperationException ? */ @@ -97,10 +95,10 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { * * @param rootNode * @param inclusiveNamespaces - * @return none it always fails + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + public void engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces, OutputStream writer) throws CanonicalizationException { /** $todo$ well, should we throw UnsupportedOperationException ? */ @@ -112,11 +110,11 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { * * @param rootNode * @param inclusiveNamespaces - * @return none it always fails + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree( - Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace) + public void engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer) throws CanonicalizationException { /** $todo$ well, should we throw UnsupportedOperationException ? */ @@ -126,8 +124,8 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { /** * Output the Attr[]s for the given element. *
- * The code of this method is a copy of {@link #outputAttributes(Element, - * NameSpaceSymbTable, Map)}, + * The code of this method is a copy of + * {@link #outputAttributes(Element, NameSpaceSymbTable, Map)}, * 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. @@ -135,17 +133,18 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { * @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 cache) + Map cache, OutputStream writer) throws CanonicalizationException, DOMException, IOException { if (!element.hasAttributes() && !firstCall) { return; } // result will contain the attrs which have to be output - SortedSet result = new TreeSet(COMPARE); + SortedSet result = new TreeSet<>(COMPARE); if (element.hasAttributes()) { NamedNodeMap attrs = element.getAttributes(); @@ -168,7 +167,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { //Render the ns definition result.add((Attr)n); if (C14nHelper.namespaceIsRelative(attribute)) { - Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() }; throw new CanonicalizationException( "c14n.Canonicalizer.RelativeNamespace", exArgs ); @@ -187,7 +186,6 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { firstCall = false; } - OutputStream writer = getWriter(); //we output all Attrs which are available for (Attr attr : result) { outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); @@ -204,16 +202,17 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { * @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 cache) + Map 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 result = new TreeSet(COMPARE); + SortedSet result = new TreeSet<>(COMPARE); if (element.hasAttributes()) { NamedNodeMap attrs = element.getAttributes(); @@ -253,7 +252,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { if (n != null) { result.add((Attr)n); if (C14nHelper.namespaceIsRelative(attribute)) { - Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() }; throw new CanonicalizationException( "c14n.Canonicalizer.RelativeNamespace", exArgs ); @@ -292,7 +291,6 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ns.getUnrenderedNodes(result); } - OutputStream writer = getWriter(); //we output all Attrs which are available for (Attr attr : result) { outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); @@ -300,7 +298,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { } protected void circumventBugIfNeeded(XMLSignatureInput input) - throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + throws XMLParserException, IOException { if (!input.isNeedsToBeExpanded()) { return; } @@ -339,7 +337,7 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { String NName = e.getPrefix(); String NValue = e.getNamespaceURI(); String Name; - if (NName == null || NName.equals("")) { + if (NName == null || NName.isEmpty()) { NName = "xmlns"; Name = "xmlns"; } else { diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java index 072940e5bfd..b7c543e583a 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java @@ -24,14 +24,15 @@ 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 javax.xml.parsers.ParserConfigurationException; 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; @@ -41,7 +42,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; -import org.xml.sax.SAXException; /** * Implements "
inclusiveNSSet; + private SortedSet inclusiveNSSet = Collections.emptySortedSet(); private boolean propagateDefaultNamespace = false; /** @@ -79,12 +79,12 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { * Method engineCanonicalizeSubTree * {@inheritDoc} * @param rootNode - * + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree(Node rootNode) + public void engineCanonicalizeSubTree(Node rootNode, OutputStream writer) throws CanonicalizationException { - return engineCanonicalizeSubTree(rootNode, "", null); + engineCanonicalizeSubTree(rootNode, "", null, writer); } /** @@ -92,13 +92,13 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { * {@inheritDoc} * @param rootNode * @param inclusiveNamespaces - * + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree( - Node rootNode, String inclusiveNamespaces + public void engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, OutputStream writer ) throws CanonicalizationException { - return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null); + engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null, writer); } /** @@ -107,14 +107,14 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { * @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 byte[] engineCanonicalizeSubTree( - Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace + public void engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer ) throws CanonicalizationException { this.propagateDefaultNamespace = propagateDefaultNamespace; - return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null); + engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null, writer); } /** @@ -122,28 +122,29 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { * @param rootNode * @param inclusiveNamespaces * @param excl A element to exclude from the c14n process. - * @return the rootNode c14n. + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree( - Node rootNode, String inclusiveNamespaces, Node excl + public void engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, Node excl, OutputStream writer ) throws CanonicalizationException{ inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); - return super.engineCanonicalizeSubTree(rootNode, excl); + super.engineCanonicalizeSubTree(rootNode, excl, writer); } /** * * @param rootNode * @param inclusiveNamespaces - * @return the rootNode c14n. + * @param writer OutputStream to write the canonicalization result + * @param secureValidation Whether secure validation is enabled * @throws CanonicalizationException */ - public byte[] engineCanonicalize( - XMLSignatureInput rootNode, String inclusiveNamespaces + public void engineCanonicalize( + XMLSignatureInput rootNode, String inclusiveNamespaces, OutputStream writer, boolean secureValidation ) throws CanonicalizationException { inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); - return super.engineCanonicalize(rootNode); + super.engineCanonicalize(rootNode, writer, secureValidation); } /** @@ -151,26 +152,27 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { * {@inheritDoc} * @param xpathNodeSet * @param inclusiveNamespaces + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeXPathNodeSet( - Set xpathNodeSet, String inclusiveNamespaces + public void engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces, OutputStream writer ) throws CanonicalizationException { inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); - return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); + super.engineCanonicalizeXPathNodeSet(xpathNodeSet, writer); } @Override protected void outputAttributesSubtree(Element element, NameSpaceSymbTable ns, - Map cache) + Map cache, OutputStream writer) throws CanonicalizationException, DOMException, IOException { // result will contain the attrs which have to be output - SortedSet result = new TreeSet(COMPARE); + SortedSet result = new TreeSet<>(COMPARE); // The prefix visibly utilized (in the attribute or in the name) in // the element - SortedSet visiblyUtilized = new TreeSet(); - if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + SortedSet visiblyUtilized = new TreeSet<>(); + if (!inclusiveNSSet.isEmpty()) { visiblyUtilized.addAll(inclusiveNSSet); } @@ -197,7 +199,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { && 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()}; + Object[] exArgs = {element.getTagName(), NName, attribute.getNodeValue()}; throw new CanonicalizationException( "c14n.Canonicalizer.RelativeNamespace", exArgs ); @@ -227,22 +229,18 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { } } - OutputStream writer = getWriter(); //we output all Attrs which are available for (Attr attr : result) { outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); } } - /** - * {@inheritDoc} - */ @Override protected void outputAttributes(Element element, NameSpaceSymbTable ns, - Map cache) + Map cache, OutputStream writer) throws CanonicalizationException, DOMException, IOException { // result will contain the attrs which have to be output - SortedSet result = new TreeSet(COMPARE); + SortedSet result = new TreeSet<>(COMPARE); // The prefix visibly utilized (in the attribute or in the name) in // the element @@ -250,8 +248,8 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { // It's the output selected. boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1; if (isOutputElement) { - visiblyUtilized = new TreeSet(); - if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized = new TreeSet<>(); + if (!inclusiveNSSet.isEmpty()) { visiblyUtilized.addAll(inclusiveNSSet); } } @@ -286,7 +284,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { if (n != null) { result.add((Attr)n); if (C14nHelper.namespaceIsRelative(attribute)) { - Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() }; throw new CanonicalizationException( "c14n.Canonicalizer.RelativeNamespace", exArgs ); @@ -297,7 +295,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { if (ns.addMapping(NName, NNodeValue, attribute) && C14nHelper.namespaceIsRelative(NNodeValue)) { // New definition check if it is relative - Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + Object[] exArgs = { element.getTagName(), NName, attribute.getNodeValue() }; throw new CanonicalizationException( "c14n.Canonicalizer.RelativeNamespace", exArgs ); @@ -332,7 +330,6 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { } } - OutputStream writer = getWriter(); //we output all Attrs which are available for (Attr attr : result) { outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); @@ -340,8 +337,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { } protected void circumventBugIfNeeded(XMLSignatureInput input) - throws CanonicalizationException, ParserConfigurationException, - IOException, SAXException { + throws XMLParserException, IOException { if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty()) { return; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java index 14271ed40e6..df9f88a8386 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java @@ -38,8 +38,4 @@ public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315 return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; } - /** {@inheritDoc} */ - public final boolean engineGetIncludeComments() { - return false; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java index c68f1ebb1a4..6b80e68525e 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java @@ -42,8 +42,4 @@ public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315 return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; } - /** {@inheritDoc} */ - public final boolean engineGetIncludeComments() { - return true; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java index 4e9184b7799..6615436467f 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java @@ -41,8 +41,4 @@ public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 { return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; } - /** {@inheritDoc} */ - public final boolean engineGetIncludeComments() { - return false; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java index 2a6addde88a..23dd3496da5 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java @@ -40,8 +40,4 @@ public class Canonicalizer20010315WithComments extends Canonicalizer20010315 { return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; } - /** {@inheritDoc} */ - public final boolean engineGetIncludeComments() { - return true; - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java index 5f6a524f0c0..d3b972c95f8 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java @@ -22,7 +22,6 @@ */ package com.sun.org.apache.xml.internal.security.c14n.implementations; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; @@ -34,15 +33,13 @@ import java.util.ListIterator; import java.util.Map; import java.util.Set; -import javax.xml.parsers.ParserConfigurationException; - 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.UnsyncByteArrayOutputStream; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; import org.w3c.dom.Comment; @@ -52,7 +49,6 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; -import org.xml.sax.SAXException; /** * Abstract base class for canonicalization algorithms. @@ -65,7 +61,10 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { 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(); + 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. @@ -83,25 +82,14 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { private static final byte[] AMP = {'&','a','m','p',';'}; private static final byte[] EQUALS_STR = {'=','\"'}; - 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; - + private boolean includeComments; private List nodeFilter; - private boolean includeComments; private Set xpathNodeSet; /** - * The node to be skipped/excluded from the DOM tree - * in subtree canonicalizations. + * The null xmlns definition. */ - private Node excludeNode; - private OutputStream writer = new ByteArrayOutputStream(); - - /** - * The null xmlns definition. - */ private Attr nullNode; /** @@ -109,7 +97,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * * @param includeComments */ - public CanonicalizerBase(boolean includeComments) { + protected CanonicalizerBase(boolean includeComments) { this.includeComments = includeComments; } @@ -117,73 +105,60 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * Method engineCanonicalizeSubTree * {@inheritDoc} * @param rootNode + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree(Node rootNode) + public void engineCanonicalizeSubTree(Node rootNode, OutputStream writer) throws CanonicalizationException { - return engineCanonicalizeSubTree(rootNode, (Node)null); + engineCanonicalizeSubTree(rootNode, (Node)null, writer); } /** * Method engineCanonicalizeXPathNodeSet * {@inheritDoc} * @param xpathNodeSet + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + public void engineCanonicalizeXPathNodeSet(Set xpathNodeSet, OutputStream writer) throws CanonicalizationException { this.xpathNodeSet = xpathNodeSet; - return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet)); + engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet), writer); } /** * Canonicalizes a Subtree node. * @param input the root of the subtree to canicalize - * @return The canonicalize stream. + * @param writer OutputStream to write the canonicalization result + * @param secureValidation Whether secure validation is enabled + * * @throws CanonicalizationException */ - public byte[] engineCanonicalize(XMLSignatureInput input) throws CanonicalizationException { + public void engineCanonicalize(XMLSignatureInput input, OutputStream writer, boolean secureValidation) throws CanonicalizationException { try { if (input.isExcludeComments()) { includeComments = false; } if (input.isOctetStream()) { - return engineCanonicalize(input.getBytes()); - } - if (input.isElement()) { - return engineCanonicalizeSubTree(input.getSubNode(), input.getExcludeNode()); + 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) { - return engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); + engineCanonicalizeXPathNodeSetInternal(input.getSubNode(), writer); } else { - return engineCanonicalizeXPathNodeSet(input.getNodeSet()); + engineCanonicalizeXPathNodeSet(input.getNodeSet(), writer); } } - return null; - } catch (ParserConfigurationException ex) { - throw new CanonicalizationException(ex); - } catch (IOException ex) { - throw new CanonicalizationException(ex); - } catch (SAXException ex) { + } catch (XMLParserException | IOException ex) { throw new CanonicalizationException(ex); } } - /** - * @param writer The writer to set. - */ - public void setWriter(OutputStream writer) { - this.writer = writer; - } - - protected OutputStream getWriter() { - return writer; - } - /** * Canonicalizes a Subtree node. * @@ -191,12 +166,11 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * the root of the subtree to canonicalize * @param excludeNode * a node to be excluded from the canonicalize operation - * @return The canonicalize stream. + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - protected byte[] engineCanonicalizeSubTree(Node rootNode, Node excludeNode) + protected void engineCanonicalizeSubTree(Node rootNode, Node excludeNode, OutputStream writer) throws CanonicalizationException { - this.excludeNode = excludeNode; try { NameSpaceSymbTable ns = new NameSpaceSymbTable(); int nodeLevel = NODE_BEFORE_DOCUMENT_ELEMENT; @@ -205,29 +179,8 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { getParentNameSpaces((Element)rootNode, ns); nodeLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - this.canonicalizeSubTree(rootNode, ns, rootNode, nodeLevel); - this.writer.flush(); - if (this.writer instanceof ByteArrayOutputStream) { - byte[] result = ((ByteArrayOutputStream)this.writer).toByteArray(); - if (reset) { - ((ByteArrayOutputStream)this.writer).reset(); - } else { - this.writer.close(); - } - return result; - } else if (this.writer instanceof UnsyncByteArrayOutputStream) { - byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray(); - if (reset) { - ((UnsyncByteArrayOutputStream)this.writer).reset(); - } else { - this.writer.close(); - } - return result; - } else { - this.writer.close(); - } - return null; - + this.canonicalizeSubTree(rootNode, ns, rootNode, nodeLevel, excludeNode, writer); + writer.flush(); } catch (UnsupportedEncodingException ex) { throw new CanonicalizationException(ex); } catch (IOException ex) { @@ -242,20 +195,21 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * @param currentNode * @param ns * @param endnode + * @param documentLevel + * @param excludeNode + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException * @throws IOException */ - protected final void canonicalizeSubTree( - Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel + 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; - final OutputStream writer = this.writer; - final Node excludeNode = this.excludeNode; - final boolean includeComments = this.includeComments; Map cache = new HashMap<>(); do { switch (currentNode.getNodeType()) { @@ -300,7 +254,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { String name = currentElement.getTagName(); UtfHelpper.writeByte(name, writer, cache); - outputAttributesSubtree(currentElement, ns, cache); + outputAttributesSubtree(currentElement, ns, cache, writer); writer.write('>'); sibling = currentNode.getFirstChild(); @@ -347,33 +301,11 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { } - private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) + private void engineCanonicalizeXPathNodeSetInternal(Node doc, OutputStream writer) throws CanonicalizationException { try { - this.canonicalizeXPathNodeSet(doc, doc); - this.writer.flush(); - if (this.writer instanceof ByteArrayOutputStream) { - byte[] sol = ((ByteArrayOutputStream)this.writer).toByteArray(); - if (reset) { - ((ByteArrayOutputStream)this.writer).reset(); - } else { - this.writer.close(); - } - return sol; - } else if (this.writer instanceof UnsyncByteArrayOutputStream) { - byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray(); - if (reset) { - ((UnsyncByteArrayOutputStream)this.writer).reset(); - } else { - this.writer.close(); - } - return result; - } else { - this.writer.close(); - } - return null; - } catch (UnsupportedEncodingException ex) { - throw new CanonicalizationException(ex); + this.canonicalizeXPathNodeSet(doc, doc, writer); + writer.flush(); } catch (IOException ex) { throw new CanonicalizationException(ex); } @@ -385,10 +317,11 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * * @param currentNode * @param endnode + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException * @throws IOException */ - protected final void canonicalizeXPathNodeSet(Node currentNode, Node endnode) + private void canonicalizeXPathNodeSet(Node currentNode, Node endnode, OutputStream writer) throws CanonicalizationException, IOException { if (isVisibleInt(currentNode) == -1) { return; @@ -422,7 +355,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { break; case Node.COMMENT_NODE : - if (this.includeComments && isVisibleDO(currentNode, ns.getLevel()) == 1) { + if (includeComments && isVisibleDO(currentNode, ns.getLevel()) == 1) { outputCommentToWriter((Comment) currentNode, writer, documentLevel); } break; @@ -468,7 +401,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { ns.push(); } - outputAttributes(currentElement, ns, cache); + outputAttributes(currentElement, ns, cache, writer); if (currentNodeIsVisible) { writer.write('>'); @@ -566,10 +499,8 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { } } } - if (this.xpathNodeSet != null && !this.xpathNodeSet.contains(currentNode)) { - return false; - } - return true; + + return this.xpathNodeSet == null || this.xpathNodeSet.contains(currentNode); } protected void handleParent(Element e, NameSpaceSymbTable ns) { @@ -592,7 +523,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { String NName = e.getPrefix(); String NValue = e.getNamespaceURI(); String Name; - if (NName == null || NName.equals("")) { + if (NName == null || NName.isEmpty()) { NName = XMLNS; Name = XMLNS; } else { @@ -609,7 +540,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * @param el * @param ns */ - protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) { + private void getParentNameSpaces(Element el, NameSpaceSymbTable ns) { Node n1 = el.getParentNode(); if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) { return; @@ -641,9 +572,11 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * @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 cache) + abstract void outputAttributes(Element element, NameSpaceSymbTable ns, + Map cache, OutputStream writer) throws CanonicalizationException, DOMException, IOException; /** @@ -652,13 +585,15 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * @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 cache) + abstract void outputAttributesSubtree(Element element, NameSpaceSymbTable ns, + Map cache, OutputStream writer) throws CanonicalizationException, DOMException, IOException; abstract void circumventBugIfNeeded(XMLSignatureInput input) - throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; + throws XMLParserException, IOException; /** * Outputs an Attribute to the internal Writer. @@ -834,7 +769,7 @@ public abstract class CanonicalizerBase extends CanonicalizerSpi { * @param writer writer where to write the things * @throws IOException */ - protected static final void outputTextToWriter( + private static final void outputTextToWriter( final String text, final OutputStream writer ) throws IOException { final int length = text.length(); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java index 7cda2c37519..4b2333938f5 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java @@ -29,10 +29,9 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import javax.xml.parsers.ParserConfigurationException; - 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; @@ -41,7 +40,6 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.ProcessingInstruction; -import org.xml.sax.SAXException; /** * Serializes the physical representation of the subtree. All the attributes @@ -67,10 +65,10 @@ public class CanonicalizerPhysical extends CanonicalizerBase { * * @param xpathNodeSet * @param inclusiveNamespaces - * @return none it always fails + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException always */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + public void engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces, OutputStream writer) throws CanonicalizationException { /** $todo$ well, should we throw UnsupportedOperationException ? */ @@ -82,10 +80,10 @@ public class CanonicalizerPhysical extends CanonicalizerBase { * * @param rootNode * @param inclusiveNamespaces - * @return none it always fails + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + public void engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces, OutputStream writer) throws CanonicalizationException { /** $todo$ well, should we throw UnsupportedOperationException ? */ @@ -97,11 +95,11 @@ public class CanonicalizerPhysical extends CanonicalizerBase { * * @param rootNode * @param inclusiveNamespaces - * @return none it always fails + * @param writer OutputStream to write the canonicalization result * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree( - Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace) + public void engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace, OutputStream writer) throws CanonicalizationException { /** $todo$ well, should we throw UnsupportedOperationException ? */ @@ -111,8 +109,8 @@ public class CanonicalizerPhysical extends CanonicalizerBase { /** * Output the Attr[]s for the given element. *
- * The code of this method is a copy of {@link #outputAttributes(Element, - * NameSpaceSymbTable, Map)}, + * The code of this method is a copy of + * {@link #outputAttributes(Element, NameSpaceSymbTable, Map)}, * 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. @@ -120,15 +118,16 @@ public class CanonicalizerPhysical extends CanonicalizerBase { * @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 cache) + Map cache, OutputStream writer) throws CanonicalizationException, DOMException, IOException { if (element.hasAttributes()) { // result will contain all the attrs declared directly on that element - SortedSet result = new TreeSet(COMPARE); + SortedSet result = new TreeSet<>(COMPARE); NamedNodeMap attrs = element.getAttributes(); int attrsLength = attrs.getLength(); @@ -138,7 +137,6 @@ public class CanonicalizerPhysical extends CanonicalizerBase { result.add(attribute); } - OutputStream writer = getWriter(); //we output all Attrs which are available for (Attr attr : result) { outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); @@ -148,15 +146,16 @@ public class CanonicalizerPhysical extends CanonicalizerBase { @Override protected void outputAttributes(Element element, NameSpaceSymbTable ns, - Map cache) + Map 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 CanonicalizationException, ParserConfigurationException, IOException, SAXException { + throws XMLParserException, IOException { // nothing to do } @@ -170,11 +169,6 @@ public class CanonicalizerPhysical extends CanonicalizerBase { return Canonicalizer.ALGO_ID_C14N_PHYSICAL; } - /** {@inheritDoc} */ - public final boolean engineGetIncludeComments() { - return true; - } - @Override protected void outputPItoWriter(ProcessingInstruction currentPI, OutputStream writer, int position) throws IOException { diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java index 603630d45f3..2fc853fe690 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java @@ -38,6 +38,9 @@ import org.w3c.dom.Node; */ 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(); @@ -51,16 +54,19 @@ public class NameSpaceSymbTable { private SymbMap symb; /**The stacks for removing the definitions when doing pop.*/ - private List level; + private final List level = new ArrayList<>(); private boolean cloned = true; /** * Default constractor **/ public NameSpaceSymbTable() { - level = new ArrayList<>(); //Insert the default binding for xmlns. - symb = (SymbMap) initialMap.clone(); + try { + symb = initialMap.clone(); + } catch (CloneNotSupportedException e) { + LOG.error("Error cloning the initial map"); + } } /** @@ -74,7 +80,7 @@ public class NameSpaceSymbTable { NameSpaceSymbEntry n = it.next(); //put them rendered? if (!n.rendered && n.n != null) { - n = (NameSpaceSymbEntry) n.clone(); + n = n.clone(); needsClone(); symb.put(n.prefix, n); n.lastrendered = n.uri; @@ -132,7 +138,11 @@ public class NameSpaceSymbTable { final void needsClone() { if (!cloned) { level.set(level.size() - 1, symb); - symb = (SymbMap) symb.clone(); + try { + symb = symb.clone(); + } catch (CloneNotSupportedException e) { + LOG.error("Error cloning the symbol map"); + } cloned = true; } } @@ -155,7 +165,7 @@ public class NameSpaceSymbTable { return null; } // Mark this entry as render. - entry = (NameSpaceSymbEntry) entry.clone(); + entry = entry.clone(); needsClone(); symb.put(prefix, entry); entry.rendered = true; @@ -223,7 +233,7 @@ public class NameSpaceSymbTable { if (ob != null && uri.equals(ob.uri)) { if (!ob.rendered) { - ob = (NameSpaceSymbEntry) ob.clone(); + ob = ob.clone(); needsClone(); symb.put(prefix, ob); ob.lastrendered = uri; @@ -282,10 +292,13 @@ public class NameSpaceSymbTable { **/ class NameSpaceSymbEntry implements Cloneable { - String prefix; + final String prefix; /**The URI that the prefix defines */ - String uri; + 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; @@ -293,9 +306,6 @@ class NameSpaceSymbEntry implements Cloneable { /**This prefix-URI has been already render or not.*/ boolean rendered = false; - /**The attribute to include.*/ - Attr n; - NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) { this.uri = name; this.rendered = rendered; @@ -304,9 +314,9 @@ class NameSpaceSymbEntry implements Cloneable { } /** {@inheritDoc} */ - public Object clone() { + public NameSpaceSymbEntry clone() { //NOPMD try { - return super.clone(); + return (NameSpaceSymbEntry)super.clone(); } catch (CloneNotSupportedException e) { return null; } @@ -370,7 +380,7 @@ class SymbMap implements Cloneable { */ protected void rehash(int newCapacity) { int oldCapacity = keys.length; - String oldKeys[] = keys; + String[] oldKeys = keys; NameSpaceSymbEntry oldVals[] = entries; keys = new String[newCapacity]; @@ -390,18 +400,14 @@ class SymbMap implements Cloneable { return entries[index(key)]; } - protected Object clone() { - try { - 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); + @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; - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - return null; + return copy; } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java index f4f6d1a10bf..34b7a53d923 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java @@ -118,42 +118,6 @@ public final class UtfHelpper { } } - @Deprecated - public static void writeCharToUtf8(final char c, final OutputStream out) throws IOException { - if (c < 0x80) { - out.write(c); - return; - } - if (c >= 0xD800 && c <= 0xDBFF || c >= 0xDC00 && c <= 0xDFFF) { - //No Surrogates in sun java - out.write(0x3f); - return; - } - int bias; - int write; - char ch; - if (c > 0x07FF) { - ch = (char)(c>>>12); - write = 0xE0; - if (ch > 0) { - write |= ch & 0x0F; - } - out.write(write); - write = 0x80; - bias = 0x3F; - } else { - write = 0xC0; - bias = 0x1F; - } - ch = (char)(c>>>6); - if (ch > 0) { - write |= ch & bias; - } - out.write(write); - out.write(0x80 | ((c) & 0x3F)); - - } - public static void writeStringToUtf8( final String str, final OutputStream out ) throws IOException { @@ -247,7 +211,7 @@ public final class UtfHelpper { continue; } if (!expanded) { - byte newResult[] = new byte[6*length]; + byte[] newResult = new byte[6*length]; System.arraycopy(result, 0, newResult, 0, out); result = newResult; expanded = true; @@ -292,7 +256,7 @@ public final class UtfHelpper { } } if (expanded) { - byte newResult[] = new byte[out]; + byte[] newResult = new byte[out]; System.arraycopy(result, 0, newResult, 0, out); result = newResult; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/XmlAttrStack.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/XmlAttrStack.java index f163e7f8a11..71b84139bee 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/XmlAttrStack.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/XmlAttrStack.java @@ -41,17 +41,18 @@ class XmlAttrStack { private static final com.sun.org.slf4j.internal.Logger LOG = com.sun.org.slf4j.internal.LoggerFactory.getLogger(XmlAttrStack.class); - static class XmlsStackElement { + private static class XmlsStackElement { int level; boolean rendered = false; - List nodes = new ArrayList<>(); + final List nodes = new ArrayList<>(); } private int currentLevel = 0; private int lastlevel = 0; private XmlsStackElement cur; - private List levels = new ArrayList<>(); - private boolean c14n11; + + private final List levels = new ArrayList<>(); + private final boolean c14n11; public XmlAttrStack(boolean c14n11) { this.c14n11 = c14n11; @@ -120,7 +121,7 @@ class XmlAttrStack { Iterator it = e.nodes.iterator(); while (it.hasNext() && successiveOmitted) { Attr n = it.next(); - if (n.getLocalName().equals("base") && !e.rendered) { + if ("base".equals(n.getLocalName()) && !e.rendered) { baseAttrs.add(n); } else if (!loa.containsKey(n.getName())) { loa.put(n.getName(), n); @@ -133,7 +134,7 @@ class XmlAttrStack { Attr baseAttr = null; while (it.hasNext()) { Attr n = it.next(); - if (n.getLocalName().equals("base")) { + if ("base".equals(n.getLocalName())) { base = n.getValue(); baseAttr = n; break; @@ -222,7 +223,7 @@ class XmlAttrStack { tquery = bquery; } } else { - if (rpath.startsWith("/")) { + if (rpath.charAt(0) == '/') { tpath = removeDotSegments(rpath); } else { if (bauthority != null && bpath.length() == 0) { @@ -263,7 +264,7 @@ class XmlAttrStack { // If the input buffer starts with a root slash "/" then move this // character to the output buffer. if (input.charAt(0) == '/') { - output.append("/"); + output.append('/'); input = input.substring(1); } @@ -282,7 +283,7 @@ class XmlAttrStack { printStep("2A", output.toString(), input); } else if (input.startsWith("../")) { input = input.substring(3); - if (!output.toString().equals("/")) { + if (!"/".equals(output.toString())) { output.append("../"); } printStep("2A", output.toString(), input); @@ -292,7 +293,7 @@ class XmlAttrStack { } else if (input.startsWith("/./")) { input = input.substring(2); printStep("2B", output.toString(), input); - } else if (input.equals("/.")) { + } else if ("/.".equals(input)) { // FIXME: what is complete path segment? input = input.replaceFirst("/.", "/"); printStep("2B", output.toString(), input); @@ -309,7 +310,7 @@ class XmlAttrStack { } else if (input.startsWith("/../")) { input = input.substring(3); if (output.length() == 0) { - output.append("/"); + output.append('/'); } else if (output.toString().endsWith("../")) { output.append(".."); } else if (output.toString().endsWith("..")) { @@ -326,11 +327,11 @@ class XmlAttrStack { } } printStep("2C", output.toString(), input); - } else if (input.equals("/..")) { + } else if ("/..".equals(input)) { // FIXME: what is complete path segment? input = input.replaceFirst("/..", "/"); if (output.length() == 0) { - output.append("/"); + output.append('/'); } else if (output.toString().endsWith("../")) { output.append(".."); } else if (output.toString().endsWith("..")) { @@ -352,11 +353,11 @@ class XmlAttrStack { // only of ".." and if the output buffer does not contain only // the root slash "/", then move the ".." to the output buffer // else delte it.; otherwise, - } else if (input.equals(".")) { + } else if (".".equals(input)) { input = ""; printStep("2D", output.toString(), input); - } else if (input.equals("..")) { - if (!output.toString().equals("/")) { + } else if ("..".equals(input)) { + if (!"/".equals(output.toString())) { output.append(".."); } input = ""; @@ -392,7 +393,7 @@ class XmlAttrStack { // then append a slash "/". The output buffer is returned as the result // of remove_dot_segments if (output.toString().endsWith("..")) { - output.append("/"); + output.append('/'); printStep("3 ", output.toString(), input); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java index 0ed06e6e7ea..211060881d8 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java @@ -51,7 +51,7 @@ public class AlgorithmAlreadyRegisteredException extends XMLSecurityException { * @param msgID * @param exArgs */ - public AlgorithmAlreadyRegisteredException(String msgID, Object exArgs[]) { + public AlgorithmAlreadyRegisteredException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -78,7 +78,7 @@ public class AlgorithmAlreadyRegisteredException extends XMLSecurityException { * @param exArgs */ public AlgorithmAlreadyRegisteredException( - Exception originalException, String msgID, Object exArgs[] + Exception originalException, String msgID, Object[] exArgs ) { super(originalException, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java index 38608165db5..e4b550bb045 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java @@ -53,7 +53,7 @@ public class Base64DecodingException extends XMLSecurityException { * @param msgID * @param exArgs */ - public Base64DecodingException(String msgID, Object exArgs[]) { + public Base64DecodingException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -79,7 +79,7 @@ public class Base64DecodingException extends XMLSecurityException { * @param msgID * @param exArgs */ - public Base64DecodingException(Exception originalException, String msgID, Object exArgs[]) { + public Base64DecodingException(Exception originalException, String msgID, Object[] exArgs) { super(originalException, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java index 69725930e6c..98764012ea7 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java @@ -38,7 +38,7 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; * Usage in the Java source is: *
  * {
- *    Object exArgs[] = { Constants._TAG_TRANSFORMS, "BadElement" };
+ *    Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
  *
  *    throw new XMLSecurityException("xml.WrongElement", exArgs);
  * }
@@ -49,7 +49,7 @@ import com.sun.org.apache.xml.internal.security.utils.I18n;
  * try {
  *    ...
  * } catch (Exception oldEx) {
- *    Object exArgs[] = { Constants._TAG_TRANSFORMS, "BadElement" };
+ *    Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
  *
  *    throw new XMLSecurityException("xml.WrongElement", exArgs, oldEx);
  * }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java
index 4a0f45cde4f..7d17fe867e1 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java
@@ -39,7 +39,7 @@ import com.sun.org.apache.xml.internal.security.utils.I18n;
  * Usage in the Java source is:
  * 
  * {
- *    Object exArgs[] = { Constants._TAG_TRANSFORMS, "BadElement" };
+ *    Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
  *
  *    throw new XMLSecurityException("xml.WrongElement", exArgs);
  * }
@@ -50,7 +50,7 @@ import com.sun.org.apache.xml.internal.security.utils.I18n;
  * try {
  *    ...
  * } catch (Exception oldEx) {
- *    Object exArgs[] = { Constants._TAG_TRANSFORMS, "BadElement" };
+ *    Object[] exArgs = { Constants._TAG_TRANSFORMS, "BadElement" };
  *
  *    throw new XMLSecurityException("xml.WrongElement", exArgs, oldEx);
  * }
@@ -92,7 +92,7 @@ public class XMLSecurityRuntimeException extends RuntimeException {
      * @param msgID
      * @param exArgs
      */
-    public XMLSecurityRuntimeException(String msgID, Object exArgs[]) {
+    public XMLSecurityRuntimeException(String msgID, Object[] exArgs) {
         super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
 
         this.msgID = msgID;
@@ -130,7 +130,7 @@ public class XMLSecurityRuntimeException extends RuntimeException {
      * @param exArgs
      * @param originalException
      */
-    public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) {
+    public XMLSecurityRuntimeException(String msgID, Object[] exArgs, Exception originalException) {
         super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException);
 
         this.msgID = msgID;
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java
deleted file mode 100644
index df3680ab3b6..00000000000
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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;
-
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
-public class ContentHandlerAlreadyRegisteredException extends XMLSecurityException {
-
-    /**
-     *
-     */
-    private static final long serialVersionUID = 1L;
-
-    /**
-     * Constructor ContentHandlerAlreadyRegisteredException
-     *
-     */
-    public ContentHandlerAlreadyRegisteredException() {
-        super();
-    }
-
-    /**
-     * Constructor ContentHandlerAlreadyRegisteredException
-     *
-     * @param msgID
-     */
-    public ContentHandlerAlreadyRegisteredException(String msgID) {
-        super(msgID);
-    }
-
-    /**
-     * Constructor ContentHandlerAlreadyRegisteredException
-     *
-     * @param msgID
-     * @param exArgs
-     */
-    public ContentHandlerAlreadyRegisteredException(String msgID, Object exArgs[]) {
-        super(msgID, exArgs);
-    }
-
-    /**
-     * Constructor ContentHandlerAlreadyRegisteredException
-     *
-     * @param originalException
-     * @param msgID
-     */
-    public ContentHandlerAlreadyRegisteredException(Exception originalException, String msgID) {
-        super(originalException, msgID);
-    }
-
-    @Deprecated
-    public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) {
-        this(originalException, msgID);
-    }
-
-    /**
-     * Constructor ContentHandlerAlreadyRegisteredException
-     *
-     * @param originalException
-     * @param msgID
-     * @param exArgs
-     */
-    public ContentHandlerAlreadyRegisteredException(
-        Exception originalException, String msgID, Object exArgs[]
-    ) {
-        super(originalException, msgID, exArgs);
-    }
-
-    @Deprecated
-    public ContentHandlerAlreadyRegisteredException(String msgID, Object[] exArgs, Exception originalException) {
-        this(originalException, msgID, exArgs);
-    }
-
-}
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java
index f87058a1fdb..519df28b814 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java
@@ -810,7 +810,6 @@ public class KeyInfo extends SignatureElementProxy {
         Iterator it = KeyResolver.iterator();
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
-            keyResolver.setSecureValidation(secureValidation);
             Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null) {
@@ -818,7 +817,7 @@ public class KeyInfo extends SignatureElementProxy {
                     for (StorageResolver storage : storageResolvers) {
                         PublicKey pk =
                             keyResolver.engineLookupAndResolvePublicKey(
-                                (Element) currentChild, uri, storage
+                                (Element) currentChild, uri, storage, secureValidation
                             );
 
                         if (pk != null) {
@@ -841,7 +840,6 @@ public class KeyInfo extends SignatureElementProxy {
     PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException {
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
             LOG.debug("Try {}", keyResolver.getClass().getName());
-            keyResolver.setSecureValidation(secureValidation);
             Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null)      {
@@ -849,7 +847,7 @@ public class KeyInfo extends SignatureElementProxy {
                     for (StorageResolver storage : storageResolvers) {
                         PublicKey pk =
                             keyResolver.engineLookupAndResolvePublicKey(
-                                (Element) currentChild, uri, storage
+                                (Element) currentChild, uri, storage, secureValidation
                             );
 
                         if (pk != null) {
@@ -911,7 +909,6 @@ public class KeyInfo extends SignatureElementProxy {
         Iterator it = KeyResolver.iterator();
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
-            keyResolver.setSecureValidation(secureValidation);
             X509Certificate cert = applyCurrentResolver(uri, keyResolver);
             if (cert != null) {
                 return cert;
@@ -929,7 +926,7 @@ public class KeyInfo extends SignatureElementProxy {
                 for (StorageResolver storage : storageResolvers) {
                     X509Certificate cert =
                         keyResolver.engineLookupResolveX509Certificate(
-                            (Element) currentChild, uri, storage
+                            (Element) currentChild, uri, storage, secureValidation
                         );
 
                     if (cert != null) {
@@ -957,7 +954,6 @@ public class KeyInfo extends SignatureElementProxy {
         String uri = this.getBaseURI();
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
             LOG.debug("Try {}", keyResolver.getClass().getName());
-            keyResolver.setSecureValidation(secureValidation);
             X509Certificate cert = applyCurrentResolver(uri, keyResolver);
             if (cert != null) {
                 return cert;
@@ -1004,7 +1000,6 @@ public class KeyInfo extends SignatureElementProxy {
         Iterator it = KeyResolver.iterator();
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
-            keyResolver.setSecureValidation(secureValidation);
 
             Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
@@ -1013,7 +1008,7 @@ public class KeyInfo extends SignatureElementProxy {
                     for (StorageResolver storage : storageResolvers) {
                         SecretKey sk =
                             keyResolver.engineLookupAndResolveSecretKey(
-                                (Element) currentChild, uri, storage
+                                (Element) currentChild, uri, storage, secureValidation
                             );
 
                         if (sk != null) {
@@ -1037,7 +1032,6 @@ public class KeyInfo extends SignatureElementProxy {
     SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
             LOG.debug("Try {}", keyResolver.getClass().getName());
-            keyResolver.setSecureValidation(secureValidation);
             Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null)      {
@@ -1045,7 +1039,7 @@ public class KeyInfo extends SignatureElementProxy {
                     for (StorageResolver storage : storageResolvers) {
                         SecretKey sk =
                             keyResolver.engineLookupAndResolveSecretKey(
-                                (Element) currentChild, uri, storage
+                                (Element) currentChild, uri, storage, secureValidation
                             );
 
                         if (sk != null) {
@@ -1094,7 +1088,6 @@ public class KeyInfo extends SignatureElementProxy {
         Iterator it = KeyResolver.iterator();
         while (it.hasNext()) {
             KeyResolverSpi keyResolver = it.next();
-            keyResolver.setSecureValidation(secureValidation);
 
             Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
@@ -1104,7 +1097,7 @@ public class KeyInfo extends SignatureElementProxy {
                     // since they cannot return private keys
                     PrivateKey pk =
                         keyResolver.engineLookupAndResolvePrivateKey(
-                            (Element) currentChild, uri, null
+                            (Element) currentChild, uri, null, secureValidation
                         );
 
                     if (pk != null) {
@@ -1126,7 +1119,6 @@ public class KeyInfo extends SignatureElementProxy {
     PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException {
         for (KeyResolverSpi keyResolver : internalKeyResolvers) {
             LOG.debug("Try {}", keyResolver.getClass().getName());
-            keyResolver.setSecureValidation(secureValidation);
             Node currentChild = getFirstChild();
             String uri = this.getBaseURI();
             while (currentChild != null) {
@@ -1135,7 +1127,7 @@ public class KeyInfo extends SignatureElementProxy {
                     // since they cannot return private keys
                     PrivateKey pk =
                         keyResolver.engineLookupAndResolvePrivateKey(
-                            (Element) currentChild, uri, null
+                            (Element) currentChild, uri, null, secureValidation
                         );
 
                     if (pk != null) {
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java
deleted file mode 100644
index 235854eede7..00000000000
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * 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;
-
-import java.io.PrintStream;
-import java.security.PublicKey;
-
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-import com.sun.org.apache.xml.internal.security.keys.content.KeyName;
-import com.sun.org.apache.xml.internal.security.keys.content.KeyValue;
-import com.sun.org.apache.xml.internal.security.keys.content.MgmtData;
-import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
-
-/**
- * Utility class for {@code com.sun.org.apache.xml.internal.security.keys} package.
- *
- */
-public final class KeyUtils {
-
-    private KeyUtils() {
-        // no instantiation
-    }
-
-    /**
-     * Method prinoutKeyInfo
-     *
-     * @param ki
-     * @param os
-     * @throws XMLSecurityException
-     */
-    public static void prinoutKeyInfo(KeyInfo ki, PrintStream os)
-        throws XMLSecurityException {
-
-        for (int i = 0; i < ki.lengthKeyName(); i++) {
-            KeyName x = ki.itemKeyName(i);
-
-            os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\"");
-        }
-
-        for (int i = 0; i < ki.lengthKeyValue(); i++) {
-            KeyValue x = ki.itemKeyValue(i);
-            PublicKey pk = x.getPublicKey();
-
-            os.println("KeyValue Nr. " + i);
-            os.println(pk);
-        }
-
-        for (int i = 0; i < ki.lengthMgmtData(); i++) {
-            MgmtData x = ki.itemMgmtData(i);
-
-            os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\"");
-        }
-
-        for (int i = 0; i < ki.lengthX509Data(); i++) {
-            X509Data x = ki.itemX509Data(i);
-
-            os.println("X509Data(" + i + ")=\"" + (x.containsCertificate()
-                ? "Certificate " : "") + (x.containsIssuerSerial()
-                ? "IssuerSerial " : "") + "\"");
-        }
-    }
-}
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java
index d3a98e45945..6a727b2c719 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java
@@ -41,7 +41,7 @@ import org.w3c.dom.Element;
 public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent {
 
     /** JCA algorithm key types supported by this implementation. */
-    private static final String supportedKeyTypes[] = { "RSA", "DSA", "EC"};
+    private static final String[] supportedKeyTypes = { "RSA", "DSA", "EC"};
 
     /**
      * Constructor DEREncodedKeyValue
@@ -120,9 +120,7 @@ public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyIn
                 if (publicKey != null) {
                     return publicKey;
                 }
-            } catch (NoSuchAlgorithmException e) { //NOPMD
-                // Do nothing, try the next type
-            } catch (InvalidKeySpecException e) { //NOPMD
+            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { //NOPMD
                 // Do nothing, try the next type
             }
         }
@@ -140,11 +138,8 @@ public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyIn
             KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm());
             X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class);
             return keySpec.getEncoded();
-        } catch (NoSuchAlgorithmException e) {
-            Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
-            throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
-        } catch (InvalidKeySpecException e) {
-            Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
+        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
+            Object[] exArgs = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
             throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
         }
     }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java
index 6ba4ed2488c..06aeae25fa7 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java
@@ -71,7 +71,7 @@ public class X509Data extends SignatureElementProxy implements KeyInfoContent {
         }
         if (sibling == null || sibling.getNodeType() != Node.ELEMENT_NODE) {
             /* No Elements found */
-            Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
+            Object[] exArgs = { "Elements", Constants._TAG_X509DATA };
             throw new XMLSecurityException("xml.WrongContent", exArgs);
         }
     }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java
index 0e3c5185ab6..95697892df8 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java
@@ -90,7 +90,7 @@ public class DSAKeyValue extends SignatureElementProxy implements KeyValueConten
             this.addBigIntegerElement(params.getG(), Constants._TAG_G);
             this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y);
         } else {
-            Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
+            Object[] exArgs = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
 
             throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
         }
@@ -115,12 +115,9 @@ public class DSAKeyValue extends SignatureElementProxy implements KeyValueConten
                     )
                 );
             KeyFactory dsaFactory = KeyFactory.getInstance("DSA");
-            PublicKey pk = dsaFactory.generatePublic(pkspec);
 
-            return pk;
-        } catch (NoSuchAlgorithmException ex) {
-            throw new XMLSecurityException(ex);
-        } catch (InvalidKeySpecException ex) {
+            return dsaFactory.generatePublic(pkspec);
+        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
             throw new XMLSecurityException(ex);
         }
     }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/ECKeyValue.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/ECKeyValue.java
index ab591ebb455..0517aa4f711 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/ECKeyValue.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/ECKeyValue.java
@@ -180,7 +180,7 @@ public class ECKeyValue extends Signature11ElementProxy implements KeyValueConte
                     uri = curElem.getAttributeNS(null, "URI");
                 }
                 // strip off "urn:oid"
-                if (uri.startsWith("urn:oid:")) {
+                if (uri != null && uri.startsWith("urn:oid:")) {
                     String oid = uri.substring("urn:oid:".length());
                     ecParams = getECParameterSpec(oid);
                     if (ecParams == null) {
@@ -204,11 +204,7 @@ public class ECKeyValue extends Signature11ElementProxy implements KeyValueConte
 
             ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams);
             return KeyFactory.getInstance("EC").generatePublic(spec);
-        } catch (NoSuchAlgorithmException ex) {
-            throw new XMLSecurityException(ex);
-        } catch (InvalidKeySpecException ex) {
-            throw new XMLSecurityException(ex);
-        } catch (MarshalException ex) {
+        } catch (NoSuchAlgorithmException | InvalidKeySpecException | MarshalException ex) {
             throw new XMLSecurityException(ex);
         }
     }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java
index 9f80c99aa58..5025dcd345f 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java
@@ -86,7 +86,7 @@ public class RSAKeyValue extends SignatureElementProxy implements KeyValueConten
                 ((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT
             );
         } else {
-            Object exArgs[] = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() };
+            Object[] exArgs = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() };
 
             throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
         }
@@ -109,9 +109,7 @@ public class RSAKeyValue extends SignatureElementProxy implements KeyValueConten
             PublicKey pk = rsaFactory.generatePublic(rsaKeyspec);
 
             return pk;
-        } catch (NoSuchAlgorithmException ex) {
-            throw new XMLSecurityException(ex);
-        } catch (InvalidKeySpecException ex) {
+        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
             throw new XMLSecurityException(ex);
         }
     }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java
index af6a5a85359..56844e472ff 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java
@@ -100,18 +100,11 @@ public class XMLX509Certificate extends SignatureElementProxy implements XMLX509
      * @throws XMLSecurityException
      */
     public X509Certificate getX509Certificate() throws XMLSecurityException {
-        byte certbytes[] = this.getCertificateBytes();
+        byte[] certbytes = this.getCertificateBytes();
         try (InputStream is = new ByteArrayInputStream(certbytes)) {
             CertificateFactory certFact =
                 CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
-            X509Certificate cert =
-                (X509Certificate) certFact.generateCertificate(is);
-
-            if (cert != null) {
-                return cert;
-            }
-
-            return null;
+            return (X509Certificate) certFact.generateCertificate(is);
         } catch (CertificateException | IOException ex) {
             throw new XMLSecurityException(ex);
         }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java
index fc5b04001bd..502a9a4dc82 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java
@@ -117,17 +117,17 @@ public class XMLX509Digest extends Signature11ElementProxy implements XMLX509Dat
     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);
+            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);
-                }
+            MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
+            return md.digest(cert.getEncoded());
+        } catch (Exception e) {
+            Object[] exArgs = {jcaDigestAlgorithm};
+            throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
+        }
 
     }
 
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java
index f49d31de3da..197d417c00e 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java
@@ -112,7 +112,7 @@ public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataCont
         throws XMLSecurityException {
 
         if (cert.getVersion() < 3) {
-            Object exArgs[] = { cert.getVersion() };
+            Object[] exArgs = { cert.getVersion() };
             throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs);
         }
 
@@ -133,7 +133,7 @@ public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataCont
          * OCTET STRING, and the next two bytes are the tag and length of
          * the ski OCTET STRING.
          */
-        byte skidValue[] = new byte[extensionValue.length - 4];
+        byte[] skidValue = new byte[extensionValue.length - 4];
 
         System.arraycopy(extensionValue, 4, skidValue, 0, skidValue.length);
 
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java
index 1b7c97a9303..7aa9a30128a 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java
@@ -22,14 +22,17 @@
  */
 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 javax.crypto.SecretKey;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
 
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver;
 import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver;
@@ -44,8 +47,6 @@ import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations
 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
@@ -56,20 +57,9 @@ public class KeyResolver {
     private static final com.sun.org.slf4j.internal.Logger LOG =
         com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyResolver.class);
 
-    /** Field resolverVector */
-    private static List resolverVector = new CopyOnWriteArrayList();
+    private static List resolverList = new CopyOnWriteArrayList<>();
 
-    /** Field resolverSpi */
-    private final KeyResolverSpi resolverSpi;
-
-    /**
-     * Constructor.
-     *
-     * @param keyResolverSpi a KeyResolverSpi instance
-     */
-    private KeyResolver(KeyResolverSpi keyResolverSpi) {
-        resolverSpi = keyResolverSpi;
-    }
+    private static final AtomicBoolean defaultResolversAdded = new AtomicBoolean();
 
     /**
      * Method length
@@ -77,7 +67,7 @@ public class KeyResolver {
      * @return the length of resolvers registered
      */
     public static int length() {
-        return resolverVector.size();
+        return resolverList.size();
     }
 
     /**
@@ -86,35 +76,36 @@ public class KeyResolver {
      * @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
+        Element element, String baseURI, StorageResolver storage, boolean secureValidation
     ) throws KeyResolverException {
-        for (KeyResolver resolver : resolverVector) {
+        for (KeyResolverSpi resolver : resolverList) {
             if (resolver == null) {
-                Object exArgs[] = {
-                                   element != null
-                                       && element.getNodeType() == Node.ELEMENT_NODE
-                                       ? element.getTagName() : "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.resolveX509Certificate(element, baseURI, storage);
+            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"
-                          };
+        Object[] exArgs = {
+                element != null && element.getNodeType() == Node.ELEMENT_NODE
+                        ? element.getTagName() : "null"
+        };
 
         throw new KeyResolverException("utils.resolver.noClass", exArgs);
     }
@@ -125,35 +116,36 @@ public class KeyResolver {
      * @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
+        Element element, String baseURI, StorageResolver storage, boolean secureValidation
     ) throws KeyResolverException {
-        for (KeyResolver resolver : resolverVector) {
+        for (KeyResolverSpi resolver : resolverList) {
             if (resolver == null) {
-                Object exArgs[] = {
-                                   element != null
-                                       && element.getNodeType() == Node.ELEMENT_NODE
-                                       ? element.getTagName() : "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.resolvePublicKey(element, baseURI, storage);
+            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"
-                          };
+        Object[] exArgs = {
+                element != null && element.getNodeType() == Node.ELEMENT_NODE
+                        ? element.getTagName() : "null"
+        };
 
         throw new KeyResolverException("utils.resolver.noClass", exArgs);
     }
@@ -168,20 +160,18 @@ public class KeyResolver {
      * underlying collection is a CopyOnWriteArrayList.
      *
      * @param className
-     * @param globalResolver Whether the KeyResolverSpi is a global resolver or not
      * @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, boolean globalResolver)
-        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+    public static void register(String className) throws
+            ClassNotFoundException, IllegalAccessException,
+            InstantiationException, InvocationTargetException {
         JavaUtils.checkRegisterPermission();
-        @SuppressWarnings("deprecation")
         KeyResolverSpi keyResolverSpi =
-            (KeyResolverSpi) ClassLoaderUtils.loadClass(className, KeyResolver.class).newInstance();
-        keyResolverSpi.setGlobalResolver(globalResolver);
+            (KeyResolverSpi) JavaUtils.newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class));
         register(keyResolverSpi, false);
     }
 
@@ -195,31 +185,24 @@ public class KeyResolver {
      * underlying collection is a CopyOnWriteArrayList.
      *
      * @param className
-     * @param globalResolver Whether the KeyResolverSpi is a global resolver 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 registerAtStart(String className, boolean globalResolver) {
+    public static void registerAtStart(String className) {
         JavaUtils.checkRegisterPermission();
         KeyResolverSpi keyResolverSpi = null;
         Exception ex = null;
         try {
-            @SuppressWarnings("deprecation")
-            KeyResolverSpi tmp = (KeyResolverSpi) ClassLoaderUtils.loadClass(className, KeyResolver.class).newInstance();
-            keyResolverSpi = tmp;
-            keyResolverSpi.setGlobalResolver(globalResolver);
+            keyResolverSpi = (KeyResolverSpi) JavaUtils.newInstanceWithEmptyConstructor(
+                    ClassLoaderUtils.loadClass(className, KeyResolver.class));
             register(keyResolverSpi, true);
-        } catch (ClassNotFoundException e) {
-            ex = e;
-        } catch (IllegalAccessException e) {
-            ex = e;
-        } catch (InstantiationException e) {
+        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
             ex = e;
         }
 
         if (ex != null) {
             throw (IllegalArgumentException) new
-            IllegalArgumentException("Invalid KeyResolver class name").initCause(ex);
+                    IllegalArgumentException("Invalid KeyResolver class name").initCause(ex);
         }
     }
 
@@ -242,11 +225,10 @@ public class KeyResolver {
         boolean start
     ) {
         JavaUtils.checkRegisterPermission();
-        KeyResolver resolver = new KeyResolver(keyResolverSpi);
         if (start) {
-            resolverVector.add(0, resolver);
+            resolverList.add(0, keyResolverSpi);
         } else {
-            resolverVector.add(resolver);
+            resolverList.add(keyResolverSpi);
         }
     }
 
@@ -267,134 +249,48 @@ public class KeyResolver {
      *    caller does not have permission to register the key resolver
      */
     public static void registerClassNames(List classNames)
-        throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+        throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
         JavaUtils.checkRegisterPermission();
-        List keyResolverList = new ArrayList<>(classNames.size());
+        List keyResolverList = new ArrayList<>(classNames.size());
         for (String className : classNames) {
-            @SuppressWarnings("deprecation")
-            KeyResolverSpi keyResolverSpi =
-                (KeyResolverSpi)ClassLoaderUtils.loadClass(className, KeyResolver.class).newInstance();
-            keyResolverSpi.setGlobalResolver(false);
-            keyResolverList.add(new KeyResolver(keyResolverSpi));
+            KeyResolverSpi keyResolverSpi = (KeyResolverSpi)JavaUtils
+                    .newInstanceWithEmptyConstructor(ClassLoaderUtils.loadClass(className, KeyResolver.class));
+            keyResolverList.add(keyResolverSpi);
         }
-        resolverVector.addAll(keyResolverList);
+        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 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());
 
-        List keyResolverList = new ArrayList<>();
-        keyResolverList.add(new KeyResolver(new RSAKeyValueResolver()));
-        keyResolverList.add(new KeyResolver(new DSAKeyValueResolver()));
-        keyResolverList.add(new KeyResolver(new X509CertificateResolver()));
-        keyResolverList.add(new KeyResolver(new X509SKIResolver()));
-        keyResolverList.add(new KeyResolver(new RetrievalMethodResolver()));
-        keyResolverList.add(new KeyResolver(new X509SubjectNameResolver()));
-        keyResolverList.add(new KeyResolver(new X509IssuerSerialResolver()));
-        keyResolverList.add(new KeyResolver(new DEREncodedKeyValueResolver()));
-        keyResolverList.add(new KeyResolver(new KeyInfoReferenceResolver()));
-        keyResolverList.add(new KeyResolver(new X509DigestResolver()));
-        keyResolverList.add(new KeyResolver(new ECKeyValueResolver()));
-
-        resolverVector.addAll(keyResolverList);
-    }
-
-    /**
-     * Method resolvePublicKey
-     *
-     * @param element
-     * @param baseURI
-     * @param storage
-     * @return resolved public key from the registered from the elements
-     *
-     * @throws KeyResolverException
-     */
-    public PublicKey resolvePublicKey(
-        Element element, String baseURI, StorageResolver storage
-    ) throws KeyResolverException {
-        return resolverSpi.engineLookupAndResolvePublicKey(element, baseURI, storage);
-    }
-
-    /**
-     * Method resolveX509Certificate
-     *
-     * @param element
-     * @param baseURI
-     * @param storage
-     * @return resolved X509certificate key from the registered from the elements
-     *
-     * @throws KeyResolverException
-     */
-    public X509Certificate resolveX509Certificate(
-        Element element, String baseURI, StorageResolver storage
-    ) throws KeyResolverException {
-        return resolverSpi.engineLookupResolveX509Certificate(element, baseURI, storage);
-    }
-
-    /**
-     * @param element
-     * @param baseURI
-     * @param storage
-     * @return resolved SecretKey key from the registered from the elements
-     * @throws KeyResolverException
-     */
-    public SecretKey resolveSecretKey(
-        Element element, String baseURI, StorageResolver storage
-    ) throws KeyResolverException {
-        return resolverSpi.engineLookupAndResolveSecretKey(element, baseURI, storage);
-    }
-
-    /**
-     * Method setProperty
-     *
-     * @param key
-     * @param value
-     */
-    public void setProperty(String key, String value) {
-        resolverSpi.engineSetProperty(key, value);
-    }
-
-    /**
-     * Method getProperty
-     *
-     * @param key
-     * @return the property set for this resolver
-     */
-    public String getProperty(String key) {
-        return resolverSpi.engineGetProperty(key);
-    }
-
-
-    /**
-     * Method understandsProperty
-     *
-     * @param propertyToTest
-     * @return true if the resolver understands property propertyToTest
-     */
-    public boolean understandsProperty(String propertyToTest) {
-        return resolverSpi.understandsProperty(propertyToTest);
-    }
-
-
-    /**
-     * Method resolverClassName
-     *
-     * @return the name of the resolver.
-     */
-    public String resolverClassName() {
-        return resolverSpi.getClass().getName();
+            resolverList.addAll(keyResolverList);
+        }
     }
 
     /**
      * Iterate over the KeyResolverSpi instances
      */
     static class ResolverIterator implements Iterator {
-        List res;
-        Iterator it;
+        private List res;
+        private Iterator it;
 
-        public ResolverIterator(List list) {
+        public ResolverIterator(List list) {
             res = list;
             it = res.iterator();
         }
@@ -404,12 +300,12 @@ public class KeyResolver {
         }
 
         public KeyResolverSpi next() {
-            KeyResolver resolver = it.next();
+            KeyResolverSpi resolver = it.next();
             if (resolver == null) {
                 throw new RuntimeException("utils.resolver.noClass");
             }
 
-            return resolver.resolverSpi;
+            return resolver;
         }
 
         public void remove() {
@@ -418,6 +314,6 @@ public class KeyResolver {
     }
 
     public static Iterator iterator() {
-        return new ResolverIterator(resolverVector);
+        return new ResolverIterator(resolverList);
     }
 }
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java
index f8f97137433..7027550e20e 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java
@@ -58,7 +58,7 @@ public class KeyResolverException extends XMLSecurityException {
      * @param msgID
      * @param exArgs
      */
-    public KeyResolverException(String msgID, Object exArgs[]) {
+    public KeyResolverException(String msgID, Object[] exArgs) {
         super(msgID, exArgs);
     }
 
@@ -84,7 +84,7 @@ public class KeyResolverException extends XMLSecurityException {
      * @param msgID
      * @param exArgs
      */
-    public KeyResolverException(Exception originalException, String msgID, Object exArgs[]) {
+    public KeyResolverException(Exception originalException, String msgID, Object[] exArgs) {
         super(originalException, msgID, exArgs);
     }
 
diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java
index ca28a788c7a..821044d070f 100644
--- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java
+++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java
@@ -28,19 +28,17 @@ import java.io.InputStream;
 import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.cert.X509Certificate;
-import java.util.HashMap;
 
 import javax.crypto.SecretKey;
-import javax.xml.parsers.ParserConfigurationException;
 
 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;
-import org.xml.sax.SAXException;
 
 /**
- * This class is an abstract class for a child KeyInfo 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
@@ -48,23 +46,11 @@ import org.xml.sax.SAXException;
  *  <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
  *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
  * 
+ * + * Extensions of this class must be thread-safe. */ public abstract class KeyResolverSpi { - /** Field properties */ - protected java.util.Map properties; - - protected boolean globalResolver = false; - - protected boolean secureValidation; - - /** - * Set whether secure validation is enabled or not. The default is false. - */ - public void setSecureValidation(boolean secureValidation) { - this.secureValidation = secureValidation; - } - /** * This method returns whether the KeyResolverSpi is able to perform the requested action. * @@ -73,9 +59,7 @@ public abstract class KeyResolverSpi { * @param storage * @return whether the KeyResolverSpi is able to perform the requested action. */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { - throw new UnsupportedOperationException(); - } + protected abstract boolean engineCanResolve(Element element, String baseURI, StorageResolver storage); /** * Method engineResolvePublicKey @@ -83,15 +67,14 @@ public abstract class KeyResolverSpi { * @param element * @param baseURI * @param storage + * @param secureValidation * @return resolved public key from the registered from the element. * * @throws KeyResolverException */ - public PublicKey engineResolvePublicKey( - Element element, String baseURI, StorageResolver storage - ) throws KeyResolverException { - throw new UnsupportedOperationException(); - } + protected abstract PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation + ) throws KeyResolverException; /** * Method engineLookupAndResolvePublicKey @@ -99,33 +82,18 @@ public abstract class KeyResolverSpi { * @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 + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, baseURI, storage)) { + if (!engineCanResolve(element, baseURI, storage)) { return null; } - return tmp.engineResolvePublicKey(element, baseURI, storage); - } - - private KeyResolverSpi cloneIfNeeded() throws KeyResolverException { - if (globalResolver) { - try { - @SuppressWarnings("deprecation") - KeyResolverSpi tmp = getClass().newInstance(); - return tmp; - } catch (InstantiationException e) { - throw new KeyResolverException(e, ""); - } catch (IllegalAccessException e) { - throw new KeyResolverException(e, ""); - } - } - return this; + return engineResolvePublicKey(element, baseURI, storage, secureValidation); } /** @@ -134,15 +102,14 @@ public abstract class KeyResolverSpi { * @param element * @param baseURI * @param storage + * @param secureValidation * @return resolved X509Certificate key from the registered from the elements * * @throws KeyResolverException */ - public X509Certificate engineResolveX509Certificate( - Element element, String baseURI, StorageResolver storage - ) throws KeyResolverException{ - throw new UnsupportedOperationException(); - } + protected abstract X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation + ) throws KeyResolverException; /** * Method engineLookupResolveX509Certificate @@ -150,18 +117,18 @@ public abstract class KeyResolverSpi { * @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 + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, baseURI, storage)) { + if (!engineCanResolve(element, baseURI, storage)) { return null; } - return tmp.engineResolveX509Certificate(element, baseURI, storage); + return engineResolveX509Certificate(element, baseURI, storage, secureValidation); } /** @@ -170,15 +137,14 @@ public abstract class KeyResolverSpi { * @param element * @param baseURI * @param storage + * @param secureValidation * @return resolved SecretKey key from the registered from the elements * * @throws KeyResolverException */ - public SecretKey engineResolveSecretKey( - Element element, String baseURI, StorageResolver storage - ) throws KeyResolverException{ - throw new UnsupportedOperationException(); - } + protected abstract SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation + ) throws KeyResolverException; /** * Method engineLookupAndResolveSecretKey @@ -186,87 +152,55 @@ public abstract class KeyResolverSpi { * @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 + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, baseURI, storage)) { + if (!engineCanResolve(element, baseURI, storage)) { return null; } - return tmp.engineResolveSecretKey(element, baseURI, storage); + 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 + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - // This method was added later, it has no equivalent - // engineResolvePrivateKey() in the old API. - // We cannot throw UnsupportedOperationException because - // KeyResolverSpi implementations who don't know about - // this method would stop the search too early. - return null; - } - - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (properties == null) { - properties = new HashMap<>(); - } - properties.put(key, value); - } - - /** - * Method engineGetProperty - * - * @param key - * @return obtain the property appointed by key - */ - public String engineGetProperty(String key) { - if (properties == null) { + if (!engineCanResolve(element, baseURI, storage)) { return null; } - - return properties.get(key); + return engineResolvePrivateKey(element, baseURI, storage, secureValidation); } - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understood the property - */ - public boolean understandsProperty(String propertyToTest) { - if (properties == null) { - return false; - } - - return properties.get(propertyToTest) != null; - } - - public void setGlobalResolver(boolean globalResolver) { - this.globalResolver = globalResolver; - } - - /** * Parses a byte array and returns the parsed Element. * @@ -278,12 +212,10 @@ public abstract class KeyResolverSpi { try (InputStream is = new ByteArrayInputStream(bytes)) { Document doc = XMLUtils.read(is, secureValidation); return doc.getDocumentElement(); - } catch (SAXException ex) { + } catch (XMLParserException ex) { throw new KeyResolverException(ex); } catch (IOException ex) { throw new KeyResolverException(ex); - } catch (ParserConfigurationException ex) { - throw new KeyResolverException(ex); } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java index 80c4e0a1a20..82f675aadcd 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java @@ -47,21 +47,16 @@ 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}}. */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + /** {@inheritDoc} */ + @Override + protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE); } - /** {{@inheritDoc}}. */ - public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - - LOG.debug("Can I resolve {}", element.getTagName()); - - if (!engineCanResolve(element, baseURI, storage)) { - return null; - } - try { DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI); return derKeyValue.getPublicKey(); @@ -72,24 +67,33 @@ public class DEREncodedKeyValueResolver extends KeyResolverSpi { return null; } - /** {{@inheritDoc}}. */ - public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { return null; } - /** {{@inheritDoc}}. */ - public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected SecretKey engineResolveSecretKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { return null; } - /** {{@inheritDoc}}. */ - public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + /** {@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; + } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java index 4e0266d1231..7d83d50b520 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java @@ -22,6 +22,7 @@ */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -38,17 +39,17 @@ 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); + } - /** - * Method engineResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) { if (element == null) { return null; @@ -84,15 +85,25 @@ public class DSAKeyValueResolver extends KeyResolverSpi { /** {@inheritDoc} */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) { return null; } /** {@inheritDoc} */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + @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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/ECKeyValueResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/ECKeyValueResolver.java index d3c1268e07b..484000b8a43 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/ECKeyValueResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/ECKeyValueResolver.java @@ -22,6 +22,7 @@ */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -38,17 +39,17 @@ 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); + } - /** - * Method engineResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) { if (element == null) { return null; @@ -82,15 +83,25 @@ public class ECKeyValueResolver extends KeyResolverSpi { /** {@inheritDoc} */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) { return null; } /** {@inheritDoc} */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + @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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java index 15a73b7379f..fb32875c1b1 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java @@ -42,6 +42,7 @@ 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; @@ -56,23 +57,18 @@ 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}}. */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + /** {@inheritDoc} */ + @Override + protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE); } - /** {{@inheritDoc}}. */ - public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - - LOG.debug("Can I resolve {}", element.getTagName()); - - if (!engineCanResolve(element, baseURI, storage)) { - return null; - } - try { - KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation); if (referent != null) { return referent.getPublicKey(); } @@ -83,18 +79,12 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { return null; } - /** {{@inheritDoc}}. */ - public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - - LOG.debug("Can I resolve {}", element.getTagName()); - - if (!engineCanResolve(element, baseURI, storage)) { - return null; - } - try { - KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation); if (referent != null) { return referent.getX509Certificate(); } @@ -105,18 +95,13 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { return null; } - /** {{@inheritDoc}}. */ - public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected SecretKey engineResolveSecretKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - LOG.debug("Can I resolve {}", element.getTagName()); - - if (!engineCanResolve(element, baseURI, storage)) { - return null; - } - try { - KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation); if (referent != null) { return referent.getSecretKey(); } @@ -127,18 +112,13 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { return null; } - /** {{@inheritDoc}}. */ - public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + public PrivateKey engineResolvePrivateKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - LOG.debug("Can I resolve " + element.getTagName()); - - if (!engineCanResolve(element, baseURI, storage)) { - return null; - } - try { - KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage, secureValidation); if (referent != null) { return referent.getPrivateKey(); } @@ -155,10 +135,12 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { * @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) 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(); @@ -166,7 +148,7 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { Element referentElement = null; try { - referentElement = obtainReferenceElement(resource); + referentElement = obtainReferenceElement(resource, secureValidation); } catch (Exception e) { LOG.debug("XMLSecurityException", e); return null; @@ -177,7 +159,7 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { return null; } - validateReference(referentElement); + validateReference(referentElement, secureValidation); KeyInfo referent = new KeyInfo(referentElement, baseURI); referent.addStorageResolver(storage); @@ -188,12 +170,13 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { * Validate the Element referred to by the KeyInfoReference. * * @param referentElement + * @param secureValidation * * @throws XMLSecurityException */ - private void validateReference(Element referentElement) 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()) }; + Object[] exArgs = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) }; throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs); } @@ -222,14 +205,15 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { */ private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation) throws XMLSecurityException { - ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); - return resRes.resolve(uri, baseURI, secureValidation); + 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 @@ -237,20 +221,20 @@ public class KeyInfoReferenceResolver extends KeyResolverSpi { * @throws SAXException * @throws KeyResolverException */ - private Element obtainReferenceElement(XMLSignatureInput resource) + private Element obtainReferenceElement(XMLSignatureInput resource, boolean secureValidation) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException { Element e; - if (resource.isElement()){ + 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, this.secureValidation); + byte[] inputBytes = resource.getBytes(); + e = getDocFromBytes(inputBytes, secureValidation); } return e; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java index d935e08c83c..20ecdbee0a5 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java @@ -56,8 +56,8 @@ 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 KeyStore keyStore; - private char[] password; + private final KeyStore keyStore; + private final char[] password; /** * Constructor. @@ -67,81 +67,42 @@ public class PrivateKeyResolver extends KeyResolverSpi { this.password = password; } - /** - * 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. - */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { - if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA) - || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { - return true; - } - - return false; + /** {@inheritDoc} */ + @Override + protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA) + || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); } - /** - * Method engineLookupAndResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { return null; } - /** - * Method engineResolveSecretKey - * - * @param element - * @param baseURI - * @param storage - * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained - * - * @throws KeyResolverException - */ - public SecretKey engineResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { return null; } - /** - * Method engineResolvePrivateKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained - * @throws KeyResolverException - */ - public PrivateKey engineLookupAndResolvePrivateKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + public PrivateKey engineResolvePrivateKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { PrivateKey privKey = resolveX509Data(element, baseURI); @@ -162,7 +123,6 @@ public class PrivateKeyResolver extends KeyResolverSpi { } } - LOG.debug("I can't"); return null; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java index b29a6c49b1c..6c21cf0130e 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java @@ -22,6 +22,7 @@ */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -39,10 +40,17 @@ 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} */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) { if (element == null) { return null; @@ -77,15 +85,25 @@ public class RSAKeyValueResolver extends KeyResolverSpi { } /** {@inheritDoc} */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) { return null; } /** {@inheritDoc} */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + @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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java index 7b21151e105..3683ddb406d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java @@ -25,6 +25,7 @@ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementation 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; @@ -35,8 +36,6 @@ import java.util.List; import java.util.ListIterator; import java.util.Set; -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.content.RetrievalMethod; @@ -45,15 +44,16 @@ 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; -import org.xml.sax.SAXException; /** * The RetrievalMethodResolver can retrieve public keys and certificates from @@ -70,20 +70,17 @@ public class RetrievalMethodResolver extends KeyResolverSpi { private static final com.sun.org.slf4j.internal.Logger LOG = com.sun.org.slf4j.internal.LoggerFactory.getLogger(RetrievalMethodResolver.class); - /** - * Method engineResolvePublicKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage - ) { - if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { - return null; - } + /** {@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); @@ -96,57 +93,44 @@ public class RetrievalMethodResolver extends KeyResolverSpi { return cert.getPublicKey(); } return null; - } - Element e = obtainReferenceElement(resource, secureValidation); + } + 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; - } - } + // 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); + 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); - } catch (ParserConfigurationException e) { - LOG.debug("ParserConfigurationException", e); - } catch (SAXException e) { - LOG.debug("SAXException", e); } return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage) { - if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { - 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(); @@ -177,17 +161,13 @@ public class RetrievalMethodResolver extends KeyResolverSpi { } } - return resolveCertificate(e, baseURI, storage); + 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); - } catch (ParserConfigurationException e) { - LOG.debug("ParserConfigurationException", e); - } catch (SAXException e) { - LOG.debug("SAXException", e); } return null; } @@ -201,15 +181,15 @@ public class RetrievalMethodResolver extends KeyResolverSpi { * @throws KeyResolverException */ private static X509Certificate resolveCertificate( - Element e, String baseURI, StorageResolver storage + Element e, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - if (LOG.isDebugEnabled()) { - LOG.debug("Now we have a {" + e.getNamespaceURI() + "}" - + e.getLocalName() + " Element"); - } // An element has been provided if (e != null) { - return KeyResolver.getX509Certificate(e, baseURI, storage); + if (LOG.isDebugEnabled()) { + LOG.debug("Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + return KeyResolver.getX509Certificate(e, baseURI, storage, secureValidation); } return null; } @@ -219,35 +199,35 @@ public class RetrievalMethodResolver extends KeyResolverSpi { * @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 + Element e, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - if (LOG.isDebugEnabled()) { - LOG.debug("Now we have a {" + e.getNamespaceURI() + "}" - + e.getLocalName() + " Element"); - } // An element has been provided if (e != null) { - return KeyResolver.getPublicKey(e, baseURI, storage); + 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, ParserConfigurationException, - IOException, SAXException, KeyResolverException { + throws CanonicalizationException, XMLParserException, IOException, KeyResolverException { Element e; - if (resource.isElement()){ + 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(); + 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); @@ -257,7 +237,7 @@ public class RetrievalMethodResolver extends KeyResolverSpi { private static X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException { - byte inputBytes[] = resource.getBytes(); + byte[] inputBytes = resource.getBytes(); // if the resource stores a raw certificate, we have to handle it CertificateFactory certFact = CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); @@ -277,8 +257,8 @@ public class RetrievalMethodResolver extends KeyResolverSpi { Attr uri = rm.getURIAttr(); // Apply the transforms Transforms transforms = rm.getTransforms(); - ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); - XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + ResourceResolverContext resContext = new ResourceResolverContext(uri, baseURI, secureValidation); + XMLSignatureInput resource = ResourceResolver.resolve(resContext); if (transforms != null) { LOG.debug("We have Transforms"); resource = transforms.performTransforms(resource); @@ -286,15 +266,18 @@ public class RetrievalMethodResolver extends KeyResolverSpi { return resource; } - /** - * Method engineResolveSecretKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java index bd393669c9e..f8b60402349 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java @@ -44,8 +44,8 @@ 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 KeyStore keyStore; - private char[] password; + private final KeyStore keyStore; + private final char[] password; /** * Constructor. @@ -55,59 +55,32 @@ public class SecretKeyResolver extends KeyResolverSpi this.password = password; } - /** - * 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. - */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + /** {@inheritDoc} */ + @Override + protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); } - /** - * Method engineLookupAndResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { return null; } - /** - * Method engineResolveSecretKey - * - * @param element - * @param baseURI - * @param storage - * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained - * - * @throws KeyResolverException - */ - public SecretKey engineResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { LOG.debug("Can I resolve {}?", element.getTagName()); @@ -127,18 +100,11 @@ public class SecretKeyResolver extends KeyResolverSpi return null; } - /** - * Method engineResolvePrivateKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained - * @throws KeyResolverException - */ - public PrivateKey engineLookupAndResolvePrivateKey( - Element element, String baseURI, StorageResolver storage - ) throws KeyResolverException { + /** {@inheritDoc} */ + @Override + protected PrivateKey engineResolvePrivateKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation + ) { return null; } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java index e09f11c288f..6d543808354 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java @@ -37,13 +37,11 @@ import org.w3c.dom.Element; * Resolves a single Key based on the KeyName. */ public class SingleKeyResolver extends KeyResolverSpi { - private static final com.sun.org.slf4j.internal.Logger LOG = - com.sun.org.slf4j.internal.LoggerFactory.getLogger(SingleKeyResolver.class); - private String keyName; - private PublicKey publicKey; - private PrivateKey privateKey; - private SecretKey secretKey; + private final String keyName; + private final PublicKey publicKey; + private final PrivateKey privateKey; + private final SecretKey secretKey; /** * Constructor. @@ -53,6 +51,8 @@ public class SingleKeyResolver extends KeyResolverSpi { public SingleKeyResolver(String keyName, PublicKey publicKey) { this.keyName = keyName; this.publicKey = publicKey; + privateKey = null; + secretKey = null; } /** @@ -63,6 +63,8 @@ public class SingleKeyResolver extends KeyResolverSpi { public SingleKeyResolver(String keyName, PrivateKey privateKey) { this.keyName = keyName; this.privateKey = privateKey; + publicKey = null; + secretKey = null; } /** @@ -73,110 +75,67 @@ public class SingleKeyResolver extends KeyResolverSpi { public SingleKeyResolver(String keyName, SecretKey secretKey) { this.keyName = keyName; this.secretKey = secretKey; + publicKey = null; + privateKey = null; } - /** - * 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. - */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + /** {@inheritDoc} */ + @Override + protected boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); } - /** - * Method engineLookupAndResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); - - if (publicKey != null - && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + if (publicKey != null) { String name = element.getFirstChild().getNodeValue(); if (keyName.equals(name)) { return publicKey; } } - LOG.debug("I can't"); return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { return null; } - /** - * Method engineResolveSecretKey - * - * @param element - * @param baseURI - * @param storage - * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained - * - * @throws KeyResolverException - */ - public SecretKey engineResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); - - if (secretKey != null - && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + if (secretKey != null) { String name = element.getFirstChild().getNodeValue(); if (keyName.equals(name)) { return secretKey; } } - LOG.debug("I can't"); return null; } - /** - * Method engineResolvePrivateKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained - * @throws KeyResolverException - */ - public PrivateKey engineLookupAndResolvePrivateKey( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + public PrivateKey engineResolvePrivateKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); - if (privateKey != null - && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + if (privateKey != null) { String name = element.getFirstChild().getNodeValue(); if (keyName.equals(name)) { return privateKey; } } - LOG.debug("I can't"); return null; } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java index 5f71f1b7979..0be1e5bf4f5 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java @@ -22,6 +22,7 @@ */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -44,21 +45,20 @@ public class X509CertificateResolver extends KeyResolverSpi { private static final com.sun.org.slf4j.internal.Logger LOG = com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509CertificateResolver.class); - /** - * Method engineResolvePublicKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@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.engineLookupResolveX509Certificate(element, baseURI, storage); + this.engineResolveX509Certificate(element, baseURI, storage, secureValidation); if (cert != null) { return cert.getPublicKey(); @@ -67,17 +67,10 @@ public class X509CertificateResolver extends KeyResolverSpi { return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { try { @@ -87,7 +80,7 @@ public class X509CertificateResolver extends KeyResolverSpi { Element el = XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0); if (el != null) { - return engineLookupResolveX509Certificate(el, baseURI, storage); + return engineResolveX509Certificate(el, baseURI, storage, secureValidation); } return null; } @@ -107,15 +100,18 @@ public class X509CertificateResolver extends KeyResolverSpi { } } - /** - * Method engineResolveSecretKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java index 9534ba4fbf4..9826ea3b9c8 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java @@ -22,6 +22,7 @@ */ 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; @@ -50,8 +51,9 @@ 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}}. */ - public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + /** {@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); @@ -64,11 +66,12 @@ public class X509DigestResolver extends KeyResolverSpi { } } - /** {{@inheritDoc}}. */ - public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, baseURI, storage); + X509Certificate cert = this.engineResolveX509Certificate(element, baseURI, storage, secureValidation); if (cert != null) { return cert.getPublicKey(); @@ -77,16 +80,11 @@ public class X509DigestResolver extends KeyResolverSpi { return null; } - /** {{@inheritDoc}}. */ - public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { - LOG.debug("Can I resolve {}", element.getTagName()); - - if (!engineCanResolve(element, baseURI, storage)) { - return null; - } - try { return resolveCertificate(element, baseURI, storage); } catch (XMLSecurityException e) { @@ -96,8 +94,9 @@ public class X509DigestResolver extends KeyResolverSpi { return null; } - /** {{@inheritDoc}}. */ - public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + /** {@inheritDoc} */ + @Override + protected SecretKey engineResolveSecretKey(Element element, String baseURI, StorageResolver storage, boolean secureValidation) throws KeyResolverException { return null; } @@ -162,11 +161,18 @@ public class X509DigestResolver extends KeyResolverSpi { */ private void checkStorage(StorageResolver storage) throws KeyResolverException { if (storage == null) { - Object exArgs[] = { Constants._TAG_X509DIGEST }; + 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; + } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java index 6d70abacfe1..177adff8c26 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java @@ -22,6 +22,7 @@ */ 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; @@ -33,8 +34,8 @@ import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerS 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.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.Element; public class X509IssuerSerialResolver extends KeyResolverSpi { @@ -42,14 +43,29 @@ 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} */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { X509Certificate cert = - this.engineLookupResolveX509Certificate(element, baseURI, storage); + this.engineResolveX509Certificate(element, baseURI, storage, secureValidation); if (cert != null) { return cert.getPublicKey(); @@ -59,19 +75,15 @@ public class X509IssuerSerialResolver extends KeyResolverSpi { } /** {@inheritDoc} */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); X509Data x509data = null; try { x509data = new X509Data(element, baseURI); - } catch (XMLSignatureException ex) { - LOG.debug("I can't"); - return null; } catch (XMLSecurityException ex) { - LOG.debug("I can't"); return null; } @@ -80,7 +92,7 @@ public class X509IssuerSerialResolver extends KeyResolverSpi { } try { if (storage == null) { - Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; + Object[] exArgs = { Constants._TAG_X509ISSUERSERIAL }; KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); @@ -121,8 +133,17 @@ public class X509IssuerSerialResolver extends KeyResolverSpi { } /** {@inheritDoc} */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + @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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java index 5eb2df82594..c2d8f9cef60 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java @@ -22,6 +22,7 @@ */ 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; @@ -43,21 +44,26 @@ public class X509SKIResolver extends KeyResolverSpi { com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SKIResolver.class); - /** - * Method engineResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + /** {@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.engineLookupResolveX509Certificate(element, baseURI, storage); + this.engineResolveX509Certificate(element, baseURI, storage, secureValidation); if (cert != null) { return cert.getPublicKey(); @@ -66,36 +72,20 @@ public class X509SKIResolver extends KeyResolverSpi { return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); - if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { - LOG.debug("I can't"); - return null; - } - /** Field _x509childObject[] */ - XMLX509SKI x509childObject[] = null; - - Element x509childNodes[] = null; - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); - + Element[] x509childNodes = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); if (!(x509childNodes != null && x509childNodes.length > 0)) { - LOG.debug("I can't"); return null; } + try { if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SKI }; + Object[] exArgs = { Constants._TAG_X509SKI }; KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); @@ -104,7 +94,7 @@ public class X509SKIResolver extends KeyResolverSpi { throw ex; } - x509childObject = new XMLX509SKI[x509childNodes.length]; + XMLX509SKI[] x509childObject = new XMLX509SKI[x509childNodes.length]; for (int i = 0; i < x509childNodes.length; i++) { x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI); @@ -130,16 +120,18 @@ public class X509SKIResolver extends KeyResolverSpi { return null; } - /** - * Method engineResolveSecretKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java index 2d56b846f4d..f90ff896711 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java @@ -22,6 +22,7 @@ */ 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; @@ -42,22 +43,26 @@ 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); - /** - * Method engineResolvePublicKey - * - * @param element - * @param baseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String baseURI, StorageResolver storage + return x509childNodes != null && x509childNodes.length > 0; + } + + /** {@inheritDoc} */ + @Override + protected PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { X509Certificate cert = - this.engineLookupResolveX509Certificate(element, baseURI, storage); + this.engineResolveX509Certificate(element, baseURI, storage, secureValidation); if (cert != null) { return cert.getPublicKey(); @@ -66,37 +71,20 @@ public class X509SubjectNameResolver extends KeyResolverSpi { return null; } - /** - * Method engineResolveX509Certificate - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String baseURI, StorageResolver storage + /** {@inheritDoc} */ + @Override + protected X509Certificate engineResolveX509Certificate( + Element element, String baseURI, StorageResolver storage, boolean secureValidation ) throws KeyResolverException { - LOG.debug("Can I resolve {}?", element.getTagName()); - Element[] x509childNodes = null; - XMLX509SubjectName x509childObject[] = null; - - if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { - LOG.debug("I can't"); - return null; - } - x509childNodes = + Element[] x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME); - if (!(x509childNodes != null && x509childNodes.length > 0)) { - LOG.debug("I can't"); return null; } try { if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; + Object[] exArgs = { Constants._TAG_X509SUBJECTNAME }; KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); @@ -105,7 +93,7 @@ public class X509SubjectNameResolver extends KeyResolverSpi { throw ex; } - x509childObject = new XMLX509SubjectName[x509childNodes.length]; + XMLX509SubjectName[] x509childObject = new XMLX509SubjectName[x509childNodes.length]; for (int i = 0; i < x509childNodes.length; i++) { x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI); @@ -139,16 +127,18 @@ public class X509SubjectNameResolver extends KeyResolverSpi { } } - /** - * Method engineResolveSecretKey - * {@inheritDoc} - * @param element - * @param baseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String baseURI, StorageResolver storage + /** {@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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java index de0f4b4dfef..2da744cad8c 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java @@ -42,13 +42,7 @@ public class StorageResolver { com.sun.org.slf4j.internal.LoggerFactory.getLogger(StorageResolver.class); /** Field storageResolvers */ - private List storageResolvers; - - /** - * Constructor StorageResolver - * - */ - public StorageResolver() {} + private final List storageResolvers = new ArrayList<>(); /** * Constructor StorageResolver @@ -59,18 +53,6 @@ public class StorageResolver { this.add(resolver); } - /** - * Method addResolver - * - * @param resolver - */ - public void add(StorageResolverSpi resolver) { - if (storageResolvers == null) { - storageResolvers = new ArrayList<>(); - } - this.storageResolvers.add(resolver); - } - /** * Constructor StorageResolver * @@ -80,6 +62,24 @@ public class StorageResolver { 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 * @@ -93,15 +93,6 @@ public class StorageResolver { } } - /** - * Constructor StorageResolver - * - * @param x509certificate - */ - public StorageResolver(X509Certificate x509certificate) { - this.add(x509certificate); - } - /** * Method addCertificate * @@ -126,10 +117,10 @@ public class StorageResolver { static class StorageResolverIterator implements Iterator { /** Field resolvers */ - Iterator resolvers = null; + private final Iterator resolvers; /** Field currentResolver */ - Iterator currentResolver = null; + private Iterator currentResolver; /** * Constructor StorageResolverIterator diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java index fed418b9da4..3a7ca7009f4 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java @@ -59,7 +59,7 @@ public class StorageResolverException extends XMLSecurityException { * @param msgID * @param exArgs */ - public StorageResolverException(String msgID, Object exArgs[]) { + public StorageResolverException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -85,7 +85,7 @@ public class StorageResolverException extends XMLSecurityException { * @param msgID * @param exArgs */ - public StorageResolverException(Exception originalException, String msgID, Object exArgs[]) { + public StorageResolverException(Exception originalException, String msgID, Object[] exArgs) { super(originalException, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java deleted file mode 100644 index 37be2b67792..00000000000 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * 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.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException; -import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; -import com.sun.org.apache.xml.internal.security.utils.XMLUtils; - -/** - * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s - * which reside as files in a single directory available to the - * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - */ -public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi { - - private static final com.sun.org.slf4j.internal.Logger LOG = - com.sun.org.slf4j.internal.LoggerFactory.getLogger( - CertsInFilesystemDirectoryResolver.class - ); - - /** Field merlinsCertificatesDir */ - private String merlinsCertificatesDir; - - /** Field certs */ - private List certs = new ArrayList<>(); - - /** - * @param directoryName - * @throws StorageResolverException - */ - public CertsInFilesystemDirectoryResolver(String directoryName) - throws StorageResolverException { - this.merlinsCertificatesDir = directoryName; - - this.readCertsFromHarddrive(); - } - - /** - * Method readCertsFromHarddrive - * - * @throws StorageResolverException - */ - private void readCertsFromHarddrive() throws StorageResolverException { - - File certDir = new File(this.merlinsCertificatesDir); - List al = new ArrayList<>(); - String[] names = certDir.list(); - - if (names != null) { - for (int i = 0; i < names.length; i++) { - String currentFileName = names[i]; - - if (currentFileName.endsWith(".crt")) { - al.add(names[i]); - } - } - } - - CertificateFactory cf = null; - - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException ex) { - throw new StorageResolverException(ex); - } - - for (int i = 0; i < al.size(); i++) { - String filename = certDir.getAbsolutePath() + File.separator + al.get(i); - boolean added = false; - String dn = null; - - try (InputStream inputStream = Files.newInputStream(Paths.get(filename))) { - X509Certificate cert = - (X509Certificate) cf.generateCertificate(inputStream); - - //add to ArrayList - cert.checkValidity(); - this.certs.add(cert); - - dn = cert.getSubjectX500Principal().getName(); - added = true; - } catch (FileNotFoundException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not add certificate from file " + filename, ex); - } - } catch (CertificateNotYetValidException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not add certificate from file " + filename, ex); - } - } catch (CertificateExpiredException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not add certificate from file " + filename, ex); - } - } catch (CertificateException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not add certificate from file " + filename, ex); - } - } catch (IOException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not add certificate from file " + filename, ex); - } - } - - if (added) { - LOG.debug("Added certificate: {}", dn); - } - } - } - - /** {@inheritDoc} */ - public Iterator getIterator() { - return new FilesystemIterator(this.certs); - } - - /** - * Class FilesystemIterator - */ - private static class FilesystemIterator implements Iterator { - - /** Field certs */ - private List certs; - - /** Field i */ - private int i; - - /** - * Constructor FilesystemIterator - * - * @param certs - */ - public FilesystemIterator(List certs) { - this.certs = certs; - this.i = 0; - } - - /** {@inheritDoc} */ - public boolean hasNext() { - return this.i < this.certs.size(); - } - - /** {@inheritDoc} */ - public Certificate next() { - return this.certs.get(this.i++); - } - - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException("Can't remove keys from KeyStore"); - } - } - - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { - - CertsInFilesystemDirectoryResolver krs = - new CertsInFilesystemDirectoryResolver( - "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); - - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = (X509Certificate) i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert); - - System.out.println(); - System.out.println("Base64(SKI())= \"" - + XMLUtils.encodeToString(ski) + "\""); - System.out.println("cert.getSerialNumber()= \"" - + cert.getSerialNumber().toString() + "\""); - System.out.println("cert.getSubjectX500Principal().getName()= \"" - + cert.getSubjectX500Principal().getName() + "\""); - System.out.println("cert.getIssuerX500Principal().getName()= \"" - + cert.getIssuerX500Principal().getName() + "\""); - } - } -} diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java index ab73de3c1a6..6f7ff7deb92 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java @@ -25,8 +25,11 @@ 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; @@ -38,8 +41,11 @@ import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; */ 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 KeyStore keyStore; + private final KeyStore keyStore; /** * Constructor KeyStoreResolver @@ -67,14 +73,9 @@ public class KeyStoreResolver extends StorageResolverSpi { */ static class KeyStoreIterator implements Iterator { - /** Field keyStore */ - KeyStore keyStore = null; + private final List certs; - /** Field aliases */ - Enumeration aliases = null; - - /** Field nextCert */ - Certificate nextCert = null; + private int i; /** * Constructor KeyStoreIterator @@ -82,45 +83,37 @@ public class KeyStoreResolver extends StorageResolverSpi { * @param keyStore */ public KeyStoreIterator(KeyStore keyStore) { + + List tmpCerts = new ArrayList<>(); try { - this.keyStore = keyStore; - this.aliases = this.keyStore.aliases(); + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + Certificate cert = keyStore.getCertificate(alias); + if (cert != null) { + tmpCerts.add(cert); + } + } } catch (KeyStoreException ex) { - // empty Enumeration - this.aliases = new Enumeration() { - public boolean hasMoreElements() { - return false; - } - public String nextElement() { - return null; - } - }; + LOG.debug("Error reading certificates: {}", ex.getMessage()); } + + certs = Collections.unmodifiableList(tmpCerts); + this.i = 0; } /** {@inheritDoc} */ public boolean hasNext() { - if (nextCert == null) { - nextCert = findNextCert(); - } - - return nextCert != null; + return this.i < this.certs.size(); } /** {@inheritDoc} */ public Certificate next() { - if (nextCert == null) { - // maybe caller did not call hasNext() - nextCert = findNextCert(); - - if (nextCert == null) { - throw new NoSuchElementException(); - } + if (hasNext()) { + return this.certs.get(this.i++); } - Certificate ret = nextCert; - nextCert = null; - return ret; + throw new NoSuchElementException(); } /** @@ -130,24 +123,6 @@ public class KeyStoreResolver extends StorageResolverSpi { throw new UnsupportedOperationException("Can't remove keys from KeyStore"); } - // Find the next entry that contains a certificate and return it. - // In particular, this skips over entries containing symmetric keys. - private Certificate findNextCert() { - while (this.aliases.hasMoreElements()) { - String alias = this.aliases.nextElement(); - try { - Certificate cert = this.keyStore.getCertificate(alias); - if (cert != null) { - return cert; - } - } catch (KeyStoreException ex) { - return null; - } - } - - return null; - } - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java index 73ccae3ed21..2b57b3c4e2c 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java @@ -36,7 +36,7 @@ import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; public class SingleCertificateResolver extends StorageResolverSpi { /** Field certificate */ - private X509Certificate certificate; + private final X509Certificate certificate; /** * @param x509cert the single {@link X509Certificate} @@ -56,10 +56,10 @@ public class SingleCertificateResolver extends StorageResolverSpi { static class InternalIterator implements Iterator { /** Field alreadyReturned */ - boolean alreadyReturned = false; + private boolean alreadyReturned; /** Field certificate */ - X509Certificate certificate = null; + private final X509Certificate certificate; /** * Constructor InternalIterator diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParser.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParser.java new file mode 100644 index 00000000000..0942b6b296f --- /dev/null +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParser.java @@ -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.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 { + + Document parse(InputStream inputStream, boolean disallowDocTypeDeclarations) throws XMLParserException; + +} \ No newline at end of file diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParserException.java similarity index 59% rename from src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java rename to src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParserException.java index feab4333fab..946e519dcf9 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParserException.java @@ -20,72 +20,64 @@ * specific language governing permissions and limitations * under the License. */ -package com.sun.org.apache.xml.internal.security.keys.keyresolver; +package com.sun.org.apache.xml.internal.security.parser; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -public class InvalidKeyResolverException extends XMLSecurityException { - +public class XMLParserException extends XMLSecurityException { /** * */ private static final long serialVersionUID = 1L; /** - * Constructor InvalidKeyResolverException + * Constructor XMLParserException * */ - public InvalidKeyResolverException() { + public XMLParserException() { super(); } /** - * Constructor InvalidKeyResolverException + * Constructor XMLParserException * * @param msgID */ - public InvalidKeyResolverException(String msgID) { + public XMLParserException(String msgID) { super(msgID); } /** - * Constructor InvalidKeyResolverException + * Constructor XMLParserException * * @param msgID * @param exArgs */ - public InvalidKeyResolverException(String msgID, Object exArgs[]) { + public XMLParserException(String msgID, Object[] exArgs) { super(msgID, exArgs); } /** - * Constructor InvalidKeyResolverException + * Constructor XMLParserException * * @param originalException * @param msgID */ - public InvalidKeyResolverException(Exception originalException, String msgID) { + public XMLParserException(Exception originalException, String msgID) { super(originalException, msgID); } - @Deprecated - public InvalidKeyResolverException(String msgID, Exception originalException) { - this(originalException, msgID); - } - /** - * Constructor InvalidKeyResolverException + * Constructor XMLParserException * * @param originalException * @param msgID * @param exArgs */ - public InvalidKeyResolverException(Exception originalException, String msgID, Object exArgs[]) { + public XMLParserException( + Exception originalException, String msgID, Object[] exArgs + ) { super(originalException, msgID, exArgs); } - @Deprecated - public InvalidKeyResolverException(String msgID, Object[] exArgs, Exception originalException) { - this(originalException, msgID, exArgs); - } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParserImpl.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParserImpl.java new file mode 100644 index 00000000000..908ca000b08 --- /dev/null +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/parser/XMLParserImpl.java @@ -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.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 { + + private static int parserPoolSize = + AccessController.doPrivileged( + (PrivilegedAction) () -> Integer.getInteger("com.sun.org.apache.xml.internal.security.parser.pool-size", 20)); + + private static final Map> DOCUMENT_BUILDERS = + Collections.synchronizedMap(new WeakHashMap>()); + + private static final Map> 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 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 getDocumentBuilderQueue(boolean disallowDocTypeDeclarations, ClassLoader loader) throws ParserConfigurationException { + Map> docBuilderCache = + disallowDocTypeDeclarations ? DOCUMENT_BUILDERS_DISALLOW_DOCTYPE : DOCUMENT_BUILDERS; + Queue queue = docBuilderCache.get(loader); + if (queue == null) { + queue = new ArrayBlockingQueue<>(parserPoolSize); + docBuilderCache.put(loader, queue); + } + + return queue; + } + + private static DocumentBuilder getDocumentBuilder(boolean disallowDocTypeDeclarations, Queue 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 queue) { + if (queue != null) { + db.reset(); + queue.offer(db); + } + } + + private static ClassLoader getContextClassLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } + }); + } + return Thread.currentThread().getContextClassLoader(); + } + + private static ClassLoader getClassLoader(final Class clazz) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { + return clazz.getClassLoader(); + } + }); + } + return clazz.getClassLoader(); + } +} \ No newline at end of file diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml index b95f6f088b0..603d49e0ad5 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml @@ -250,8 +250,8 @@ RequiredKey="RSA" JCEName="SHA1withRSA"/> - @@ -547,7 +556,9 @@ + RequirementLevel="OPTIONAL" + RequiredKey="DH" + JCEName="DH"/> resolverProperties; /** Field perManifestResolvers */ - private List perManifestResolvers; + private List perManifestResolvers; private boolean secureValidation; @@ -137,14 +134,14 @@ public class Manifest extends SignatureElementProxy { int le = this.referencesEl.length; if (le == 0) { // At least one Reference must be present. Bad. - Object exArgs[] = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST }; + 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 }; + Object[] exArgs = { le, referenceCount }; throw new XMLSecurityException("signature.tooManyReferences", exArgs); } @@ -320,13 +317,13 @@ public class Manifest extends SignatureElementProxy { ); } LOG.debug("verify {} References", referencesEl.length); - LOG.debug("I am {} requested to follow nested Manifests", (followManifests - ? "" : "not")); + 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 }; + Object[] exArgs = { referencesEl.length, referenceCount }; throw new XMLSecurityException("signature.tooManyReferences", exArgs); } @@ -405,16 +402,14 @@ public class Manifest extends SignatureElementProxy { manifestReferences = referencedManifest.getVerificationResults(); } catch (IOException ex) { throw new ReferenceNotInitializedException(ex); - } catch (ParserConfigurationException ex) { - throw new ReferenceNotInitializedException(ex); - } catch (SAXException ex) { + } catch (XMLParserException ex) { throw new ReferenceNotInitializedException(ex); } } verificationResults.add(new VerifiedReference(currentRefVerified, currentRef.getURI(), manifestReferences)); } catch (ReferenceNotInitializedException ex) { - Object exArgs[] = { currentRef.getURI() }; + Object[] exArgs = { currentRef.getURI() }; throw new MissingResourceFailureException( ex, currentRef, "signature.Verification.Reference.NoInput", exArgs @@ -436,7 +431,7 @@ public class Manifest extends SignatureElementProxy { */ public boolean getVerificationResult(int index) throws XMLSecurityException { if (index < 0 || index > this.getLength() - 1) { - Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) }; + Object[] exArgs = { Integer.toString(index), Integer.toString(this.getLength()) }; Exception e = new IndexOutOfBoundsException( I18n.translate("signature.Verification.IndexOutOfBounds", exArgs) @@ -453,7 +448,7 @@ public class Manifest extends SignatureElementProxy { } } - return ((ArrayList)verificationResults).get(index).isValid(); + return verificationResults.get(index).isValid(); } /** @@ -470,10 +465,10 @@ public class Manifest extends SignatureElementProxy { * Adds Resource Resolver for retrieving resources at specified {@code URI} attribute * in {@code reference} element * - * @param resolver {@link ResourceResolver} can provide the implementation subclass of + * @param resolver {@link ResourceResolverSpi} can provide the implementation subclass of * {@link ResourceResolverSpi} for retrieving resource. */ - public void addResourceResolver(ResourceResolver resolver) { + public void addResourceResolver(ResourceResolverSpi resolver) { if (resolver == null) { return; } @@ -483,28 +478,11 @@ public class Manifest extends SignatureElementProxy { this.perManifestResolvers.add(resolver); } - /** - * Adds Resource Resolver for retrieving resources at specified {@code URI} attribute - * in {@code reference} element - * - * @param resolverSpi the implementation subclass of {@link ResourceResolverSpi} for - * retrieving the resource. - */ - public void addResourceResolver(ResourceResolverSpi resolverSpi) { - if (resolverSpi == null) { - return; - } - if (perManifestResolvers == null) { - perManifestResolvers = new ArrayList<>(); - } - perManifestResolvers.add(new ResourceResolver(resolverSpi)); - } - /** * Get the Per-Manifest Resolver List * @return the per-manifest Resolver List */ - public List getPerManifestResolvers() { + public List getPerManifestResolvers() { return perManifestResolvers; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java index 584af2e20aa..73f458be39d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java @@ -64,14 +64,14 @@ public class MissingResourceFailureException extends XMLSignatureException { * @param exArgs * @see #getReference */ - public MissingResourceFailureException(Reference reference, String msgID, Object exArgs[]) { + public MissingResourceFailureException(Reference reference, String msgID, Object[] exArgs) { super(msgID, exArgs); this.uninitializedReference = reference; } @Deprecated - public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) { + public MissingResourceFailureException(String msgID, Object[] exArgs, Reference reference) { this(reference, msgID, exArgs); } @@ -108,7 +108,7 @@ public class MissingResourceFailureException extends XMLSignatureException { * @see #getReference */ public MissingResourceFailureException( - Exception originalException, Reference reference, String msgID, Object exArgs[] + Exception originalException, Reference reference, String msgID, Object[] exArgs ) { super(originalException, msgID, exArgs); @@ -117,7 +117,7 @@ public class MissingResourceFailureException extends XMLSignatureException { @Deprecated public MissingResourceFailureException( - String msgID, Object exArgs[], Exception originalException, Reference reference + String msgID, Object[] exArgs, Exception originalException, Reference reference ) { this(originalException, reference, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java index f716e35f185..4faf1077c28 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java @@ -26,6 +26,7 @@ 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; @@ -33,7 +34,6 @@ 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.c14n.InvalidCanonicalizerException; 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; @@ -50,6 +50,7 @@ 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; @@ -140,6 +141,19 @@ public class Reference extends SignatureElementProxy { private ReferenceData referenceData; + private static final Set TRANSFORM_ALGORITHMS; + + static { + Set 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 * @@ -151,7 +165,6 @@ public class Reference extends SignatureElementProxy { * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is * applied to the data * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong? - * @throws XMLSignatureException */ protected Reference( Document doc, String baseURI, String referenceURI, Manifest manifest, @@ -238,7 +251,7 @@ public class Reference extends SignatureElementProxy { transforms = new Transforms(el, this.baseURI); transforms.setSecureValidation(secureValidation); if (secureValidation && transforms.getLength() > MAXIMUM_TRANSFORM_COUNT) { - Object exArgs[] = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT }; + Object[] exArgs = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT }; throw new XMLSecurityException("signature.tooManyTransforms", exArgs); } @@ -246,12 +259,16 @@ public class Reference extends SignatureElementProxy { } digestMethodElem = el; - if (digestMethodElem == null) { + 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) { + if (digestValueElement == null || + !(Constants.SignatureSpecNS.equals(digestValueElement.getNamespaceURI()) + && Constants._TAG_DIGESTVALUE.equals(digestValueElement.getLocalName()))) { throw new XMLSecurityException("signature.Reference.NoDigestValue"); } this.manifest = manifest; @@ -272,12 +289,12 @@ public class Reference extends SignatureElementProxy { String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM); - if ("".equals(uri)) { + if (uri.isEmpty()) { return null; } if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) { - Object exArgs[] = { uri }; + Object[] exArgs = { uri }; throw new XMLSignatureException("signature.signatureAlgorithm", exArgs); } @@ -339,7 +356,7 @@ public class Reference extends SignatureElementProxy { } /** - * Return the {@code type} atttibute of the Reference indicate whether an + * Return the {@code type} attribute of the Reference indicate whether an * {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest} * element * @@ -359,11 +376,7 @@ public class Reference extends SignatureElementProxy { * {@code Object} */ public boolean typeIsReferenceToObject() { - if (Reference.OBJECT_URI.equals(this.getType())) { - return true; - } - - return false; + return Reference.OBJECT_URI.equals(this.getType()); } /** @@ -376,11 +389,7 @@ public class Reference extends SignatureElementProxy { * {@link Manifest} */ public boolean typeIsReferenceToManifest() { - if (Reference.MANIFEST_URI.equals(this.getType())) { - return true; - } - - return false; + return Reference.MANIFEST_URI.equals(this.getType()); } /** @@ -424,13 +433,11 @@ public class Reference extends SignatureElementProxy { Attr uriAttr = getElement().getAttributeNodeNS(null, Constants._ATT_URI); - ResourceResolver resolver = - ResourceResolver.getInstance( - uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation - ); - resolver.addProperties(this.manifest.getResolverProperties()); + ResourceResolverContext resolverContext = + new ResourceResolverContext(uriAttr, this.baseURI, + secureValidation, this.manifest.getResolverProperties()); - return resolver.resolve(uriAttr, this.baseURI, secureValidation); + return ResourceResolver.resolve(this.manifest.getPerManifestResolvers(), resolverContext); } catch (ResourceResolverException ex) { throw new ReferenceNotInitializedException(ex); } @@ -453,14 +460,6 @@ public class Reference extends SignatureElementProxy { } return output; - } catch (ResourceResolverException ex) { - throw new XMLSignatureException(ex); - } catch (CanonicalizationException ex) { - throw new XMLSignatureException(ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException(ex); - } catch (TransformationException ex) { - throw new XMLSignatureException(ex); } catch (XMLSecurityException ex) { throw new XMLSignatureException(ex); } @@ -499,32 +498,17 @@ public class Reference extends SignatureElementProxy { 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) - || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS) - || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS) - || uri.equals(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS) - || uri.equals(Transforms.TRANSFORM_C14N11_WITH_COMMENTS)) { + if (TRANSFORM_ALGORITHMS.contains(uri)) { break; } - output = t.performTransform(output, null); + output = t.performTransform(output, null, secureValidation); } output.setSourceURI(input.getSourceURI()); } return output; - } catch (IOException ex) { - throw new XMLSignatureException(ex); - } catch (ResourceResolverException ex) { - throw new XMLSignatureException(ex); - } catch (CanonicalizationException ex) { - throw new XMLSignatureException(ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException(ex); - } catch (TransformationException ex) { - throw new XMLSignatureException(ex); - } catch (XMLSecurityException ex) { + } catch (IOException | XMLSecurityException ex) { throw new XMLSignatureException(ex); } } @@ -575,10 +559,6 @@ public class Reference extends SignatureElementProxy { } return nodes.getHTMLRepresentation(inclusiveNamespaces); - } catch (TransformationException ex) { - throw new XMLSignatureException(ex); - } catch (InvalidTransformException ex) { - throw new XMLSignatureException(ex); } catch (XMLSecurityException ex) { throw new XMLSignatureException(ex); } @@ -634,7 +614,7 @@ public class Reference extends SignatureElementProxy { public Iterator iterator() { return new Iterator() { - Iterator sIterator = s.iterator(); + final Iterator sIterator = s.iterator(); @Override public boolean hasNext() { @@ -699,9 +679,7 @@ public class Reference extends SignatureElementProxy { try { XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null); return output.getBytes(); - } catch (IOException ex) { - throw new ReferenceNotInitializedException(ex); - } catch (CanonicalizationException ex) { + } catch (IOException | CanonicalizationException ex) { throw new ReferenceNotInitializedException(ex); } } @@ -727,10 +705,11 @@ public class Reference extends SignatureElementProxy { MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm(); mda.reset(); + XMLSignatureInput output = null; try (DigesterOutputStream diOs = new DigesterOutputStream(mda); OutputStream os = new UnsyncBufferedOutputStream(diOs)) { - XMLSignatureInput output = this.getContentsAfterTransformation(input, os); + output = this.getContentsAfterTransformation(input, os); this.transformsOutput = output; // if signing and c14n11 property == true explicitly add @@ -749,18 +728,20 @@ public class Reference extends SignatureElementProxy { } os.flush(); - if (output.getOctetStreamReal() != null) { - output.getOctetStreamReal().close(); - } - //this.getReferencedBytes(diOs); //mda.update(data); return diOs.getDigestValue(); - } catch (XMLSecurityException ex) { - throw new ReferenceNotInitializedException(ex); - } catch (IOException ex) { + } 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); + } } } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java index 7148d621c27..27c352ea5b9 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java @@ -61,7 +61,7 @@ public class ReferenceNotInitializedException extends XMLSignatureException { * @param msgID * @param exArgs */ - public ReferenceNotInitializedException(String msgID, Object exArgs[]) { + public ReferenceNotInitializedException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -87,7 +87,7 @@ public class ReferenceNotInitializedException extends XMLSignatureException { * @param msgID * @param exArgs */ - public ReferenceNotInitializedException(Exception originalException, String msgID, Object exArgs[]) { + public ReferenceNotInitializedException(Exception originalException, String msgID, Object[] exArgs) { super(originalException, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java index 0c1e3d25690..22f19b88cb7 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java @@ -64,10 +64,9 @@ public class SignatureProperties extends SignatureElementProxy { element.setIdAttributeNode(attr, true); } - int length = getLength(); - for (int i = 0; i < length; i++) { - Element propertyElem = - XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i); + 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); @@ -82,7 +81,7 @@ public class SignatureProperties extends SignatureElementProxy { */ public int getLength() { Element[] propertyElems = - XMLUtils.selectDsNodes(getElement(), Constants._TAG_SIGNATUREPROPERTY); + XMLUtils.selectDsNodes(getFirstChild(), Constants._TAG_SIGNATUREPROPERTY); return propertyElems.length; } @@ -98,7 +97,7 @@ public class SignatureProperties extends SignatureElementProxy { public SignatureProperty item(int i) throws XMLSignatureException { try { Element propertyElem = - XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i); + XMLUtils.selectDsNode(getFirstChild(), Constants._TAG_SIGNATUREPROPERTY, i); if (propertyElem == null) { return null; diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java index dfe0d2a03a5..6d4e4adf740 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java @@ -22,14 +22,13 @@ */ package com.sun.org.apache.xml.internal.security.signature; -import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; - +import java.security.Provider; +import java.security.spec.AlgorithmParameterSpec; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; -import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -39,10 +38,9 @@ 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; -import org.w3c.dom.Node; -import org.xml.sax.SAXException; /** * Handles {@code <ds:SignedInfo>} elements @@ -53,7 +51,7 @@ import org.xml.sax.SAXException; public class SignedInfo extends Manifest { /** Field signatureAlgorithm */ - private SignatureAlgorithm signatureAlgorithm; + private final SignatureAlgorithm signatureAlgorithm; /** Field c14nizedBytes */ private byte[] c14nizedBytes; @@ -88,7 +86,25 @@ public class SignedInfo extends Manifest { public SignedInfo( Document doc, String signatureMethodURI, String canonicalizationMethodURI ) throws XMLSecurityException { - this(doc, signatureMethodURI, 0, canonicalizationMethodURI); + 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); } /** @@ -105,6 +121,27 @@ public class SignedInfo extends Manifest { 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); @@ -117,9 +154,9 @@ public class SignedInfo extends Manifest { if (hMACOutputLength > 0) { this.signatureAlgorithm = - new SignatureAlgorithm(getDocument(), signatureMethodURI, hMACOutputLength); + new SignatureAlgorithm(getDocument(), signatureMethodURI, hMACOutputLength, provider); } else { - this.signatureAlgorithm = new SignatureAlgorithm(getDocument(), signatureMethodURI); + this.signatureAlgorithm = new SignatureAlgorithm(getDocument(), signatureMethodURI, provider, spec); } signatureMethod = this.signatureAlgorithm.getElement(); @@ -135,6 +172,12 @@ public class SignedInfo extends Manifest { */ 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? @@ -143,7 +186,7 @@ public class SignedInfo extends Manifest { addReturnToSelf(); this.signatureAlgorithm = - new SignatureAlgorithm(signatureMethodElem, null); + new SignatureAlgorithm(signatureMethodElem, null, provider); signatureMethod = this.signatureAlgorithm.getElement(); appendSelf(signatureMethod); @@ -163,7 +206,7 @@ public class SignedInfo extends Manifest { * Answer
*/ public SignedInfo(Element element, String baseURI) throws XMLSecurityException { - this(element, baseURI, true); + this(element, baseURI, true, null); } /** @@ -181,56 +224,45 @@ public class SignedInfo extends Manifest { public SignedInfo( Element element, String baseURI, boolean secureValidation ) throws XMLSecurityException { - // Parse the Reference children and Id attribute in the Manifest - super(reparseSignedInfoElem(element, secureValidation), baseURI, secureValidation); - - c14nMethod = XMLUtils.getNextElement(element.getFirstChild()); - signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling()); - this.signatureAlgorithm = - new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation); + this(element, baseURI, secureValidation, null); } - private static Element reparseSignedInfoElem(Element element, boolean secureValidation) - throws XMLSecurityException { - /* - * If a custom canonicalizationMethod is used, canonicalize - * ds:SignedInfo, reparse it into a new document - * and replace the original not-canonicalized ds:SignedInfo by - * the re-parsed canonicalized one. - */ - Element c14nMethod = XMLUtils.getNextElement(element.getFirstChild()); - String c14nMethodURI = - c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM); - if (!(c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS) || - c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) || - c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) || - c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) || - c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS) || - c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS))) { - // the c14n is not a secure one and can rewrite the URIs or like - // so reparse the SignedInfo to be sure - try { - Canonicalizer c14nizer = - Canonicalizer.getInstance(c14nMethodURI); - c14nizer.setSecureValidation(secureValidation); + /** + * 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 + * Question + * @see + * Answer + */ + public SignedInfo( + Element element, String baseURI, boolean secureValidation, Provider provider + ) throws XMLSecurityException { + super(element, baseURI, secureValidation); - byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element); - try (InputStream is = new ByteArrayInputStream(c14nizedBytes)) { - Document newdoc = XMLUtils.read(is, secureValidation); - Node imported = element.getOwnerDocument().importNode( - newdoc.getDocumentElement(), true); - element.getParentNode().replaceChild(imported, element); - return (Element) imported; - } - } catch (ParserConfigurationException ex) { - throw new XMLSecurityException(ex); - } catch (IOException ex) { - throw new XMLSecurityException(ex); - } catch (SAXException ex) { - throw new XMLSecurityException(ex); - } + 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); } - return element; + + 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); } /** @@ -265,19 +297,22 @@ public class SignedInfo extends Manifest { * @throws CanonicalizationException * @throws InvalidCanonicalizerException * @throws XMLSecurityException + * @throws IOException */ public byte[] getCanonicalizedOctetStream() - throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException { + throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException, IOException { if (this.c14nizedBytes == null) { Canonicalizer c14nizer = Canonicalizer.getInstance(this.getCanonicalizationMethodURI()); - c14nizer.setSecureValidation(isSecureValidation()); String inclusiveNamespaces = this.getInclusiveNamespaces(); - if (inclusiveNamespaces == null) { - this.c14nizedBytes = c14nizer.canonicalizeSubtree(getElement()); - } else { - this.c14nizedBytes = c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + if (inclusiveNamespaces == null) { + c14nizer.canonicalizeSubtree(getElement(), baos); + } else { + c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces, baos); + } + this.c14nizedBytes = baos.toByteArray(); } } @@ -297,14 +332,12 @@ public class SignedInfo extends Manifest { if (this.c14nizedBytes == null) { Canonicalizer c14nizer = Canonicalizer.getInstance(this.getCanonicalizationMethodURI()); - c14nizer.setSecureValidation(isSecureValidation()); - c14nizer.setWriter(os); String inclusiveNamespaces = this.getInclusiveNamespaces(); if (inclusiveNamespaces == null) { - c14nizer.canonicalizeSubtree(getElement()); + c14nizer.canonicalizeSubtree(getElement(), os); } else { - c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces); + c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces, os); } } else { try { @@ -374,8 +407,8 @@ public class SignedInfo extends Manifest { public String getInclusiveNamespaces() { String c14nMethodURI = getCanonicalizationMethodURI(); - if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") || - c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) { + 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; } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java index e4c04b109a4..e9cdaa1a1d9 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java @@ -25,15 +25,15 @@ package com.sun.org.apache.xml.internal.security.signature; import java.io.IOException; import java.io.OutputStream; import java.security.Key; +import java.security.Provider; import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.security.spec.AlgorithmParameterSpec; import javax.crypto.SecretKey; 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.keys.KeyInfo; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; @@ -44,7 +44,6 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.SignerOutputStream; 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.ResourceResolverSpi; import org.w3c.dom.Attr; import org.w3c.dom.Document; @@ -202,11 +201,15 @@ public final class XMLSignature extends SignatureElementProxy { public static final String ALGO_ID_SIGNATURE_ECDSA_RIPEMD160 = "http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160"; + /** Signature - Optional RSASSA-PSS */ + public static final String ALGO_ID_SIGNATURE_RSA_PSS = + Constants.XML_DSIG_NS_MORE_07_05 + "rsa-pss"; + private static final com.sun.org.slf4j.internal.Logger LOG = com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLSignature.class); /** ds:Signature.ds:SignedInfo element */ - private SignedInfo signedInfo; + private final SignedInfo signedInfo; /** ds:Signature.ds:KeyInfo */ private KeyInfo keyInfo; @@ -238,14 +241,32 @@ public final class XMLSignature extends SignatureElementProxy { */ public XMLSignature(Document doc, String baseURI, String signatureMethodURI) throws XMLSecurityException { - this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); + this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, null, null); + } + + /** + * This creates a new {@code ds:Signature} Element and adds an empty + * {@code ds:SignedInfo}. + * The {@code ds:SignedInfo} is initialized with the specified Signature + * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED + * by the spec. This method's main use is for creating a new signature. + * + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI signature algorithm to use. + * @param provider security provider to use. + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI, Provider provider) + throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, provider, null); } /** * Constructor XMLSignature * - * @param doc - * @param baseURI + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. * @param signatureMethodURI the Signature method to be used. * @param hmacOutputLength * @throws XMLSecurityException @@ -254,18 +275,35 @@ public final class XMLSignature extends SignatureElementProxy { int hmacOutputLength) throws XMLSecurityException { this( doc, baseURI, signatureMethodURI, hmacOutputLength, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, null, null ); } /** * Constructor XMLSignature * - * @param doc - * @param baseURI + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. * @param signatureMethodURI the Signature method to be used. - * @param canonicalizationMethodURI the canonicalization algorithm to be - * used to c14nize the SignedInfo element. + * @param hmacOutputLength + * @param provider security provider to use. + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI, + int hmacOutputLength, Provider provider) throws XMLSecurityException { + this( + doc, baseURI, signatureMethodURI, hmacOutputLength, + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, provider, null + ); + } + + /** + * Constructor XMLSignature + * + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI the Signature method to be used. + * @param canonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element. * @throws XMLSecurityException */ public XMLSignature( @@ -274,17 +312,37 @@ public final class XMLSignature extends SignatureElementProxy { String signatureMethodURI, String canonicalizationMethodURI ) throws XMLSecurityException { - this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI); + this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI, null, null); } /** * Constructor XMLSignature * - * @param doc - * @param baseURI - * @param signatureMethodURI + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI the Signature method to be used. + * @param canonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element. + * @param provider security provider to use. + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + String canonicalizationMethodURI, + Provider provider + ) throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI, provider, null); + } + + /** + * Constructor XMLSignature + * + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI the Signature method to be used. * @param hmacOutputLength - * @param canonicalizationMethodURI + * @param canonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element. * @throws XMLSecurityException */ public XMLSignature( @@ -293,6 +351,30 @@ public final class XMLSignature extends SignatureElementProxy { String signatureMethodURI, int hmacOutputLength, String canonicalizationMethodURI + ) throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI, null, null); + } + + /** + * Constructor XMLSignature + * + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI the Signature method to be used. + * @param hmacOutputLength + * @param canonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element. + * @param provider security provider to use. + * @param spec + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + int hmacOutputLength, + String canonicalizationMethodURI, + Provider provider, + AlgorithmParameterSpec spec ) throws XMLSecurityException { super(doc); @@ -311,7 +393,7 @@ public final class XMLSignature extends SignatureElementProxy { this.baseURI = baseURI; this.signedInfo = new SignedInfo( - getDocument(), signatureMethodURI, hmacOutputLength, canonicalizationMethodURI + getDocument(), signatureMethodURI, hmacOutputLength, canonicalizationMethodURI, provider, spec ); appendSelf(this.signedInfo); @@ -329,15 +411,25 @@ public final class XMLSignature extends SignatureElementProxy { * Creates a XMLSignature in a Document * @param doc * @param baseURI - * @param SignatureMethodElem - * @param CanonicalizationMethodElem + * @param signatureMethodElem + * @param canonicalizationMethodElem * @throws XMLSecurityException */ public XMLSignature( Document doc, String baseURI, - Element SignatureMethodElem, - Element CanonicalizationMethodElem + Element signatureMethodElem, + Element canonicalizationMethodElem + ) throws XMLSecurityException { + this(doc, baseURI, signatureMethodElem, canonicalizationMethodElem, null); + } + + public XMLSignature( + Document doc, + String baseURI, + Element signatureMethodElem, + Element canonicalizationMethodElem, + Provider provider ) throws XMLSecurityException { super(doc); @@ -355,7 +447,7 @@ public final class XMLSignature extends SignatureElementProxy { this.baseURI = baseURI; this.signedInfo = - new SignedInfo(getDocument(), SignatureMethodElem, CanonicalizationMethodElem); + new SignedInfo(getDocument(), signatureMethodElem, canonicalizationMethodElem, provider); appendSelf(this.signedInfo); addReturnToSelf(); @@ -379,7 +471,22 @@ public final class XMLSignature extends SignatureElementProxy { */ public XMLSignature(Element element, String baseURI) throws XMLSignatureException, XMLSecurityException { - this(element, baseURI, true); + this(element, baseURI, true, null); + } + + /** + * This will parse the element and construct the Java Objects. + * That will allow a user to validate the signature. + * + * @param element ds:Signature element that contains the whole signature + * @param baseURI URI to be prepended to all relative URIs + * @param provider security provider to use + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI, Provider provider) + throws XMLSignatureException, XMLSecurityException { + this(element, baseURI, true, provider); } /** @@ -393,20 +500,44 @@ public final class XMLSignature extends SignatureElementProxy { * @throws XMLSignatureException if the signature is badly formatted */ public XMLSignature(Element element, String baseURI, boolean secureValidation) + throws XMLSignatureException, XMLSecurityException { + this(element, baseURI, secureValidation, null); + } + + /** + * This will parse the element and construct the Java Objects. + * That will allow a user to validate the signature. + * + * @param element ds:Signature element that contains the whole signature + * @param baseURI URI to be prepended to all relative URIs + * @param secureValidation whether secure secureValidation is enabled or not + * @param provider security provider to use + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI, boolean secureValidation, Provider provider) throws XMLSignatureException, XMLSecurityException { super(element, baseURI); + if (!(Constants.SignatureSpecNS.equals(element.getNamespaceURI()) + && Constants._TAG_SIGNATURE.equals(element.getLocalName()))) { + Object[] exArgs = { element.getLocalName() }; + throw new XMLSignatureException("signature.Verification.InvalidElement", exArgs); + } + // check out SignedInfo child Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); // check to see if it is there - if (signedInfoElem == null) { - Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE }; + if (signedInfoElem == null || + !(Constants.SignatureSpecNS.equals(signedInfoElem.getNamespaceURI()) + && Constants._TAG_SIGNEDINFO.equals(signedInfoElem.getLocalName()))) { + Object[] exArgs = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE }; throw new XMLSignatureException("xml.WrongContent", exArgs); } // create a SignedInfo object from that element - this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation); + this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation, provider); // get signedInfoElem again in case it has changed signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); @@ -415,8 +546,10 @@ public final class XMLSignature extends SignatureElementProxy { XMLUtils.getNextElement(signedInfoElem.getNextSibling()); // check to see if it exists - if (signatureValueElement == null) { - Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE }; + if (signatureValueElement == null || + !(Constants.SignatureSpecNS.equals(signatureValueElement.getNamespaceURI()) + && Constants._TAG_SIGNATUREVALUE.equals(signatureValueElement.getLocalName()))) { + Object[] exArgs = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE }; throw new XMLSignatureException("xml.WrongContent", exArgs); } Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); @@ -429,17 +562,27 @@ public final class XMLSignature extends SignatureElementProxy { XMLUtils.getNextElement(signatureValueElement.getNextSibling()); // If it exists use it, but it's not mandatory + Element objectElem = null; if (keyInfoElem != null && Constants.SignatureSpecNS.equals(keyInfoElem.getNamespaceURI()) && Constants._TAG_KEYINFO.equals(keyInfoElem.getLocalName())) { this.keyInfo = new KeyInfo(keyInfoElem, baseURI); this.keyInfo.setSecureValidation(secureValidation); + objectElem = XMLUtils.getNextElement(keyInfoElem.getNextSibling()); + } else { + // If we have no KeyInfo + objectElem = keyInfoElem; } // - Element objectElem = - XMLUtils.getNextElement(signatureValueElement.getNextSibling()); while (objectElem != null) { + // Make sure it actually is an Object + if (!(Constants.SignatureSpecNS.equals(objectElem.getNamespaceURI()) + && Constants._TAG_OBJECT.equals(objectElem.getLocalName()))) { + Object[] exArgs = { objectElem.getLocalName() }; + throw new XMLSignatureException("signature.Verification.InvalidElement", exArgs); + } + Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); if (objectAttr != null) { objectElem.setIdAttributeNode(objectAttr, true); @@ -652,26 +795,11 @@ public final class XMLSignature extends SignatureElementProxy { this.setSignatureValueElement(sa.sign()); } catch (XMLSignatureException ex) { throw ex; - } catch (CanonicalizationException ex) { - throw new XMLSignatureException(ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException(ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException(ex); - } catch (IOException ex) { + } catch (XMLSecurityException | IOException ex) { throw new XMLSignatureException(ex); } } - /** - * Adds a {@link ResourceResolver} to enable the retrieval of resources. - * - * @param resolver - */ - public void addResourceResolver(ResourceResolver resolver) { - this.getSignedInfo().addResourceResolver(resolver); - } - /** * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources. * @@ -700,7 +828,7 @@ public final class XMLSignature extends SignatureElementProxy { return this.checkSignatureValue(cert.getPublicKey()); } - Object exArgs[] = { "Didn't get a certificate" }; + Object[] exArgs = { "Didn't get a certificate" }; throw new XMLSignatureException("empty", exArgs); } @@ -718,7 +846,7 @@ public final class XMLSignature extends SignatureElementProxy { //COMMENT: pk suggests it can only be a public key? //check to see if the key is not null if (pk == null) { - Object exArgs[] = { "Didn't get a key" }; + Object[] exArgs = { "Didn't get a key" }; throw new XMLSignatureException("empty", exArgs); } // all references inside the signedinfo need to be dereferenced and @@ -733,14 +861,14 @@ public final class XMLSignature extends SignatureElementProxy { SignatureAlgorithm sa = si.getSignatureAlgorithm(); LOG.debug("signatureMethodURI = {}", sa.getAlgorithmURI()); LOG.debug("jceSigAlgorithm = {}", sa.getJCEAlgorithmString()); - LOG.debug("jceSigProvider = {}", sa.getJCEProviderName()); LOG.debug("PublicKey = {}", pk); - byte sigBytes[] = null; + byte[] sigBytes = null; try (SignerOutputStream so = new SignerOutputStream(sa); OutputStream bos = new UnsyncBufferedOutputStream(so)) { sa.initVerify(pk); + LOG.debug("jceSigProvider = {}", sa.getJCEProviderName()); // Get the canonicalized (normalized) SignedInfo si.signInOctetStream(bos); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java index 1f80b9b027d..7d86ef05dc8 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java @@ -63,7 +63,7 @@ public class XMLSignatureException extends XMLSecurityException { * @param msgID * @param exArgs */ - public XMLSignatureException(String msgID, Object exArgs[]) { + public XMLSignatureException(String msgID, Object[] exArgs) { super(msgID, exArgs); } @@ -89,7 +89,7 @@ public class XMLSignatureException extends XMLSecurityException { * @param msgID * @param exArgs */ - public XMLSignatureException(Exception originalException, String msgID, Object exArgs[]) { + public XMLSignatureException(Exception originalException, String msgID, Object[] exArgs) { super(originalException, msgID, exArgs); } diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java index 416745959e6..a6b1c6cd170 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java @@ -27,24 +27,21 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import javax.xml.parsers.ParserConfigurationException; - import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerBase; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; +import com.sun.org.apache.xml.internal.security.parser.XMLParserException; import com.sun.org.apache.xml.internal.security.utils.JavaUtils; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; -import org.xml.sax.SAXException; /** * Class XMLSignatureInput @@ -191,13 +188,10 @@ public class XMLSignatureInput { * {@link XMLSignatureInput} constructor * * @return the node set - * @throws SAXException + * @throws XMLParserException * @throws IOException - * @throws ParserConfigurationException - * @throws CanonicalizationException */ - public Set getNodeSet() throws CanonicalizationException, ParserConfigurationException, - IOException, SAXException { + public Set getNodeSet() throws XMLParserException, IOException { return getNodeSet(false); } @@ -215,13 +209,10 @@ public class XMLSignatureInput { * @param circumvent * * @return the node set - * @throws SAXException + * @throws XMLParserException * @throws IOException - * @throws ParserConfigurationException - * @throws CanonicalizationException */ - public Set getNodeSet(boolean circumvent) throws ParserConfigurationException, - IOException, SAXException, CanonicalizationException { + public Set getNodeSet(boolean circumvent) throws XMLParserException, IOException { if (inputNodeSet != null) { return inputNodeSet; } @@ -229,12 +220,12 @@ public class XMLSignatureInput { if (circumvent) { XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode)); } - inputNodeSet = new LinkedHashSet(); + inputNodeSet = new LinkedHashSet<>(); XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments); return inputNodeSet; } else if (isOctetStream()) { convertToNodes(); - Set result = new LinkedHashSet(); + Set result = new LinkedHashSet<>(); XMLUtils.getSet(subNode, result, null, false); return result; } @@ -285,8 +276,13 @@ public class XMLSignatureInput { if (inputBytes != null) { return inputBytes; } - Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments(); - bytes = c14nizer.engineCanonicalize(this); + if (isOctetStream() || isElement() || isNodeSet()) { + Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments(); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + c14nizer.engineCanonicalize(this, baos, secureValidation); + bytes = baos.toByteArray(); + } + } return bytes; } @@ -333,7 +329,7 @@ public class XMLSignatureInput { /** * Determines if the object has been set up with a ByteArray * - * @return true is the object has been set up with an octet stream + * @return true if the object has been set up with an octet stream */ public boolean isByteArray() { return bytes != null && this.inputNodeSet == null && subNode == null; @@ -341,7 +337,7 @@ public class XMLSignatureInput { /** * Determines if the object has been set up with a pre-calculated digest. - * @return + * @return true if the object has been set up with a pre-calculated digest. */ public boolean isPreCalculatedDigest() { return preCalculatedDigest != null; @@ -407,11 +403,11 @@ public class XMLSignatureInput { + excludeComments +"/" + getSourceURI(); } try { - return "XMLSignatureInput/OctetStream/" + getBytes().length + byte[] bytes = getBytes(); + return "XMLSignatureInput/OctetStream/" + + (bytes != null ? bytes.length : 0) + " octets/" + getSourceURI(); - } catch (IOException iex) { - return "XMLSignatureInput/OctetStream//" + getSourceURI(); - } catch (CanonicalizationException cex) { + } catch (IOException | CanonicalizationException ex) { return "XMLSignatureInput/OctetStream//" + getSourceURI(); } } @@ -503,8 +499,7 @@ public class XMLSignatureInput { } else { c14nizer = new Canonicalizer20010315OmitComments(); } - c14nizer.setWriter(diOs); - c14nizer.engineCanonicalize(this); + c14nizer.engineCanonicalize(this, diOs, secureValidation); } else { byte[] buffer = new byte[4 * 1024]; int bytesread = 0; @@ -571,27 +566,11 @@ public class XMLSignatureInput { isNodeSet = b; } - void convertToNodes() throws CanonicalizationException, - ParserConfigurationException, IOException, SAXException { + private void convertToNodes() throws XMLParserException, IOException { // select all nodes, also the comments. try { Document doc = XMLUtils.read(this.getOctetStream(), secureValidation); this.subNode = doc; - } catch (SAXException ex) { - byte[] result = null; - // if a not-wellformed nodeset exists, put a container around it... - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - - baos.write("".getBytes(StandardCharsets.UTF_8)); - baos.write(this.getBytes()); - baos.write("".getBytes(StandardCharsets.UTF_8)); - - result = baos.toByteArray(); - } - try (InputStream is = new ByteArrayInputStream(result)) { - Document document = XMLUtils.read(is, secureValidation); - this.subNode = document.getDocumentElement().getFirstChild().getFirstChild(); - } } finally { if (this.inputOctetStreamProxy != null) { this.inputOctetStreamProxy.close(); diff --git a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java index a5a59c06d02..45c2508946d 100644 --- a/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java +++ b/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java @@ -56,7 +56,7 @@ public class XMLSignatureInputDebugger { "\n" + "\n" + "\n" - + "Caninical XML node set\n" + + "Canonical XML node set\n" + "