--- old/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java 2013-06-28 11:32:55.155624389 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/Init.java 2013-06-28 11:32:54.991629494 -0400 @@ -54,20 +54,20 @@ * of the files of this library. We ensure that this call is only executed once. */ public class Init { - + /** The namespace for CONF file **/ public static final String CONF_NS = "http://www.xmlsecurity.org/NS/#configuration"; /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(Init.class.getName()); /** Field alreadyInitialized */ private static boolean alreadyInitialized = false; - + /** * Method isInitialized - * @return true if the library is already initialized. + * @return true if the library is already initialized. */ public static synchronized final boolean isInitialized() { return Init.alreadyInitialized; @@ -81,12 +81,12 @@ if (alreadyInitialized) { return; } - - InputStream is = + + InputStream is = AccessController.doPrivileged( new PrivilegedAction() { public InputStream run() { - String cfile = + String cfile = System.getProperty("com.sun.org.apache.xml.internal.security.resource.config"); if (cfile == null) { return null; @@ -102,7 +102,7 @@ alreadyInitialized = true; } - + /** * Dynamically initialise the library by registering the default algorithms/implementations */ @@ -113,7 +113,7 @@ // method. // I18n.init("en", "US"); - + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Registering default algorithms"); } @@ -122,32 +122,32 @@ // Bind the default prefixes // ElementProxy.registerDefaultPrefixes(); - + // // Set the default Transforms // Transform.registerDefaultAlgorithms(); - + // // Set the default signature algorithms // SignatureAlgorithm.registerDefaultAlgorithms(); - + // // Set the default JCE algorithms // JCEMapper.registerDefaultAlgorithms(); - + // // Set the default c14n algorithms // Canonicalizer.registerDefaultAlgorithms(); - + // // Register the default resolvers // ResourceResolver.registerDefaultResolvers(); - + // // Register the default key resolvers // @@ -157,7 +157,7 @@ ex.printStackTrace(); } } - + /** * Initialise the library from a configuration file */ @@ -192,16 +192,16 @@ /* configure internationalization */ Attr langAttr = resource.getAttributeNode("defaultLanguageCode"); Attr countryAttr = resource.getAttributeNode("defaultCountryCode"); - String languageCode = + String languageCode = (langAttr == null) ? null : langAttr.getNodeValue(); - String countryCode = + String countryCode = (countryAttr == null) ? null : countryAttr.getNodeValue(); I18n.init(languageCode, countryCode); } if (tag.equals("CanonicalizationMethods")) { Element[] list = - XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod"); + XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod"); for (int i = 0; i < list.length; i++) { String uri = list[i].getAttributeNS(null, "URI"); @@ -220,7 +220,7 @@ } if (tag.equals("TransformAlgorithms")) { - Element[] tranElem = + Element[] tranElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm"); for (int i = 0; i < tranElem.length; i++) { @@ -245,7 +245,7 @@ if ("JCEAlgorithmMappings".equals(tag)) { Node algorithmsNode = ((Element)el).getElementsByTagName("Algorithms").item(0); if (algorithmsNode != null) { - Element[] algorithms = + Element[] algorithms = XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm"); for (int i = 0; i < algorithms.length; i++) { Element element = algorithms[i]; @@ -256,7 +256,7 @@ } if (tag.equals("SignatureAlgorithms")) { - Element[] sigElems = + Element[] sigElems = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm"); for (int i = 0; i < sigElems.length; i++) { @@ -281,7 +281,7 @@ } if (tag.equals("ResourceResolvers")) { - Element[]resolverElem = + Element[]resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); for (int i = 0; i < resolverElem.length; i++) { @@ -304,17 +304,17 @@ try { ResourceResolver.register(javaClass); } catch (Throwable e) { - log.log(java.util.logging.Level.WARNING, - "Cannot register:" + javaClass - + " perhaps some needed jars are not installed", + log.log(java.util.logging.Level.WARNING, + "Cannot register:" + javaClass + + " perhaps some needed jars are not installed", e ); } - } + } } if (tag.equals("KeyResolver")){ - Element[] resolverElem = + Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); List classNames = new ArrayList(resolverElem.length); for (int i = 0; i < resolverElem.length; i++) { @@ -345,7 +345,7 @@ log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:"); } - Element[] nl = + Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping"); for (int i = 0; i < nl.length; i++) { --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java 2013-06-28 11:32:55.923600484 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java 2013-06-28 11:32:55.735606336 -0400 @@ -2,82 +2,78 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * The Algorithm class which stores the Algorithm URI as a string. - * */ public abstract class Algorithm extends SignatureElementProxy { - /** - * - * @param doc - * @param algorithmURI is the URI of the algorithm as String - */ - public Algorithm(Document doc, String algorithmURI) { - - super(doc); - - this.setAlgorithmURI(algorithmURI); - } - - /** - * Constructor Algorithm - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public Algorithm(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Method getAlgorithmURI - * - * @return The URI of the alogrithm - */ - public String getAlgorithmURI() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); - } - - /** - * Sets the algorithm's URI as used in the signature. - * - * @param algorithmURI is the URI of the algorithm as String - */ - protected void setAlgorithmURI(String algorithmURI) { - - if ( (algorithmURI != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, - algorithmURI); - } - } + /** + * + * @param doc + * @param algorithmURI is the URI of the algorithm as String + */ + public Algorithm(Document doc, String algorithmURI) { + super(doc); + + this.setAlgorithmURI(algorithmURI); + } + + /** + * Constructor Algorithm + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Algorithm(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Method getAlgorithmURI + * + * @return The URI of the algorithm + */ + public String getAlgorithmURI() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + } + + /** + * Sets the algorithm's URI as used in the signature. + * + * @param algorithmURI is the URI of the algorithm as String + */ + protected void setAlgorithmURI(String algorithmURI) { + if (algorithmURI != null) { + this.constructionElement.setAttributeNS( + null, Constants._ATT_ALGORITHM, algorithmURI + ); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java 2013-06-28 11:32:56.611579069 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java 2013-06-28 11:32:56.443584298 -0400 @@ -36,14 +36,14 @@ public class JCEMapper { /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(JCEMapper.class.getName()); - private static Map algorithmsMap = + private static Map algorithmsMap = new ConcurrentHashMap(); private static String providerName = null; - + /** * Method register * @@ -53,133 +53,161 @@ public static void register(String id, Algorithm algorithm) { algorithmsMap.put(id, algorithm); } - + /** * This method registers the default algorithms. */ public static void registerDefaultAlgorithms() { algorithmsMap.put( - MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5, + MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5, new Algorithm("", "MD5", "MessageDigest") ); algorithmsMap.put( - MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160, + MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160, new Algorithm("", "RIPEMD160", "MessageDigest") ); algorithmsMap.put( - MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, + MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, new Algorithm("", "SHA-1", "MessageDigest") ); algorithmsMap.put( - MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256, + MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256, new Algorithm("", "SHA-256", "MessageDigest") ); algorithmsMap.put( - MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384, + MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384, new Algorithm("", "SHA-384", "MessageDigest") ); algorithmsMap.put( - MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512, + MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512, new Algorithm("", "SHA-512", "MessageDigest") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_DSA, + XMLSignature.ALGO_ID_SIGNATURE_DSA, new Algorithm("", "SHA1withDSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5, + XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5, new Algorithm("", "MD5withRSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160, + XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160, new Algorithm("", "RIPEMD160withRSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, new Algorithm("", "SHA1withRSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, new Algorithm("", "SHA256withRSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384, + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384, new Algorithm("", "SHA384withRSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, new Algorithm("", "SHA512withRSA", "Signature") ); algorithmsMap.put( - XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, new Algorithm("", "SHA1withECDSA", "Signature") ); algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, + new Algorithm("", "SHA256withECDSA", "Signature") + ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, + new Algorithm("", "SHA384withECDSA", "Signature") + ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, + new Algorithm("", "SHA512withECDSA", "Signature") + ); + algorithmsMap.put( XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, new Algorithm("", "HmacMD5", "Mac") ); algorithmsMap.put( - XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, + XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, new Algorithm("", "HMACRIPEMD160", "Mac") ); algorithmsMap.put( - XMLSignature.ALGO_ID_MAC_HMAC_SHA1, + XMLSignature.ALGO_ID_MAC_HMAC_SHA1, new Algorithm("", "HmacSHA1", "Mac") ); algorithmsMap.put( - XMLSignature.ALGO_ID_MAC_HMAC_SHA256, + XMLSignature.ALGO_ID_MAC_HMAC_SHA256, new Algorithm("", "HmacSHA256", "Mac") ); algorithmsMap.put( - XMLSignature.ALGO_ID_MAC_HMAC_SHA384, + XMLSignature.ALGO_ID_MAC_HMAC_SHA384, new Algorithm("", "HmacSHA384", "Mac") ); algorithmsMap.put( - XMLSignature.ALGO_ID_MAC_HMAC_SHA512, + XMLSignature.ALGO_ID_MAC_HMAC_SHA512, new Algorithm("", "HmacSHA512", "Mac") ); algorithmsMap.put( - XMLCipher.TRIPLEDES, + XMLCipher.TRIPLEDES, new Algorithm("DESede", "DESede/CBC/ISO10126Padding", "BlockEncryption", 192) ); algorithmsMap.put( - XMLCipher.AES_128, + XMLCipher.AES_128, new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 128) ); algorithmsMap.put( - XMLCipher.AES_192, + XMLCipher.AES_192, new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 192) ); algorithmsMap.put( - XMLCipher.AES_256, + XMLCipher.AES_256, new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256) ); algorithmsMap.put( - XMLCipher.RSA_v1dot5, + XMLCipher.AES_128_GCM, + new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 128) + ); + algorithmsMap.put( + XMLCipher.AES_192_GCM, + new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 192) + ); + algorithmsMap.put( + XMLCipher.AES_256_GCM, + new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 256) + ); + algorithmsMap.put( + XMLCipher.RSA_v1dot5, new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport") ); algorithmsMap.put( - XMLCipher.RSA_OAEP, + XMLCipher.RSA_OAEP, new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") ); algorithmsMap.put( - XMLCipher.DIFFIE_HELLMAN, + XMLCipher.RSA_OAEP_11, + new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") + ); + algorithmsMap.put( + XMLCipher.DIFFIE_HELLMAN, new Algorithm("", "", "KeyAgreement") ); algorithmsMap.put( - XMLCipher.TRIPLEDES_KeyWrap, + XMLCipher.TRIPLEDES_KeyWrap, new Algorithm("DESede", "DESedeWrap", "SymmetricKeyWrap", 192) ); algorithmsMap.put( - XMLCipher.AES_128_KeyWrap, + XMLCipher.AES_128_KeyWrap, new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 128) ); algorithmsMap.put( - XMLCipher.AES_192_KeyWrap, + XMLCipher.AES_192_KeyWrap, new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 192) ); algorithmsMap.put( - XMLCipher.AES_256_KeyWrap, + XMLCipher.AES_256_KeyWrap, new Algorithm("AES", "AESWrap", "SymmetricKeyWrap", 256) ); } @@ -201,7 +229,7 @@ } return null; } - + /** * Method getAlgorithmClassFromURI * @param algorithmURI @@ -235,7 +263,7 @@ } return 0; } - + /** * Method getJCEKeyAlgorithmFromURI * @@ -255,7 +283,7 @@ /** * Gets the default Provider for obtaining the security algorithms - * @return the default providerId. + * @return the default providerId. */ public static String getProviderId() { return providerName; @@ -263,7 +291,7 @@ /** * Sets the default Provider for obtaining the security algorithms - * @param provider the default providerId. + * @param provider the default providerId. */ public static void setProviderId(String provider) { providerName = provider; @@ -271,14 +299,14 @@ /** * Represents the Algorithm xml element - */ + */ public static class Algorithm { - + final String requiredKey; final String jceName; final String algorithmClass; final int keyLength; - + /** * Gets data from element * @param el @@ -293,19 +321,19 @@ keyLength = 0; } } - + public Algorithm(String requiredKey, String jceName) { this(requiredKey, jceName, null, 0); } - + public Algorithm(String requiredKey, String jceName, String algorithmClass) { this(requiredKey, jceName, algorithmClass, 0); } - + public Algorithm(String requiredKey, String jceName, int keyLength) { this(requiredKey, jceName, null, keyLength); } - + public Algorithm(String requiredKey, String jceName, String algorithmClass, int keyLength) { this.requiredKey = requiredKey; this.jceName = jceName; @@ -313,5 +341,5 @@ this.keyLength = keyLength; } } - + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java 2013-06-28 11:32:57.231559770 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java 2013-06-28 11:32:57.071564750 -0400 @@ -2,265 +2,254 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms; import java.security.MessageDigest; import java.security.NoSuchProviderException; -import java.util.HashMap; -import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import org.w3c.dom.Document; - /** * Digest Message wrapper & selector class. * *
  * MessageDigestAlgorithm.getInstance()
  * 
- * */ public class MessageDigestAlgorithm extends Algorithm { /** Message Digest - NOT RECOMMENDED MD5*/ - public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5"; - /** Digest - Required SHA1*/ - public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; - /** Message Digest - RECOMMENDED SHA256*/ - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - /** Message Digest - OPTIONAL SHA384*/ - public static final String ALGO_ID_DIGEST_SHA384 = Constants.MoreAlgorithmsSpecNS + "sha384"; - /** Message Digest - OPTIONAL SHA512*/ - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - /** Message Digest - OPTIONAL RIPEMD-160*/ - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; - - /** Field algorithm stores the actual {@link java.security.MessageDigest} */ - java.security.MessageDigest algorithm = null; - - /** - * Constructor for the brave who pass their own message digest algorithms and the corresponding URI. - * @param doc - * @param messageDigest - * @param algorithmURI - */ - private MessageDigestAlgorithm(Document doc, MessageDigest messageDigest, - String algorithmURI) { - - super(doc, algorithmURI); - - this.algorithm = messageDigest; - } - - static ThreadLocal> instances=new - ThreadLocal>() { - protected Map initialValue() { - return new HashMap(); - }; - }; - - /** - * Factory method for constructing a message digest algorithm by name. - * - * @param doc - * @param algorithmURI - * @return The MessageDigestAlgorithm element to attach in document and to digest - * @throws XMLSignatureException - */ - public static MessageDigestAlgorithm getInstance( - Document doc, String algorithmURI) throws XMLSignatureException { - MessageDigest md = getDigestInstance(algorithmURI); - return new MessageDigestAlgorithm(doc, md, algorithmURI); - } - -private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { - MessageDigest result= instances.get().get(algorithmURI); - if (result!=null) - return result; - String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); - - if (algorithmID == null) { - Object[] exArgs = { algorithmURI }; - throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); - } - - MessageDigest md; - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { + public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = + Constants.MoreAlgorithmsSpecNS + "md5"; + /** Digest - Required SHA1*/ + public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; + /** Message Digest - RECOMMENDED SHA256*/ + public static final String ALGO_ID_DIGEST_SHA256 = + EncryptionConstants.EncryptionSpecNS + "sha256"; + /** Message Digest - OPTIONAL SHA384*/ + public static final String ALGO_ID_DIGEST_SHA384 = + Constants.MoreAlgorithmsSpecNS + "sha384"; + /** Message Digest - OPTIONAL SHA512*/ + public static final String ALGO_ID_DIGEST_SHA512 = + EncryptionConstants.EncryptionSpecNS + "sha512"; + /** Message Digest - OPTIONAL RIPEMD-160*/ + public static final String ALGO_ID_DIGEST_RIPEMD160 = + EncryptionConstants.EncryptionSpecNS + "ripemd160"; + + /** Field algorithm stores the actual {@link java.security.MessageDigest} */ + private final MessageDigest algorithm; + + /** + * Constructor for the brave who pass their own message digest algorithms and the + * corresponding URI. + * @param doc + * @param algorithmURI + */ + private MessageDigestAlgorithm(Document doc, String algorithmURI) + throws XMLSignatureException { + super(doc, algorithmURI); + + algorithm = getDigestInstance(algorithmURI); + } + + /** + * Factory method for constructing a message digest algorithm by name. + * + * @param doc + * @param algorithmURI + * @return The MessageDigestAlgorithm element to attach in document and to digest + * @throws XMLSignatureException + */ + public static MessageDigestAlgorithm getInstance( + Document doc, String algorithmURI + ) throws XMLSignatureException { + return new MessageDigestAlgorithm(doc, algorithmURI); + } + + private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); + + if (algorithmID == null) { + Object[] exArgs = { algorithmURI }; + throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); + } + + MessageDigest md; + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { md = MessageDigest.getInstance(algorithmID); - } else { - md = MessageDigest.getInstance(algorithmID,provider); - } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; + } 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) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); } - instances.get().put(algorithmURI, md); + return md; -} + } - /** - * Returns the actual {@link java.security.MessageDigest} algorithm object - * - * @return the actual {@link java.security.MessageDigest} algorithm object - */ - public java.security.MessageDigest getAlgorithm() { - return this.algorithm; - } - - /** - * Proxy method for {@link java.security.MessageDigest#isEqual} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param digesta - * @param digestb - * @return the result of the {@link java.security.MessageDigest#isEqual} method - */ - public static boolean isEqual(byte[] digesta, byte[] digestb) { - return java.security.MessageDigest.isEqual(digesta, digestb); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest()} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#digest()} method - */ - public byte[] digest() { - return this.algorithm.digest(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest(byte[])} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method - */ - public byte[] digest(byte input[]) { - return this.algorithm.digest(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param buf - * @param offset - * @param len - * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method - * @throws java.security.DigestException - */ - public int digest(byte buf[], int offset, int len) - throws java.security.DigestException { - return this.algorithm.digest(buf, offset, len); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getAlgorithm} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method - */ - public String getJCEAlgorithmString() { - return this.algorithm.getAlgorithm(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getProvider} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getProvider} method - */ - public java.security.Provider getJCEProvider() { - return this.algorithm.getProvider(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getDigestLength} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getDigestLength} method - */ - public int getDigestLength() { - return this.algorithm.getDigestLength(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#reset} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - */ - public void reset() { - this.algorithm.reset(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte[])} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - */ - public void update(byte[] input) { - this.algorithm.update(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - */ - public void update(byte input) { - this.algorithm.update(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param buf - * @param offset - * @param len - */ - public void update(byte buf[], int offset, int len) { - this.algorithm.update(buf, offset, len); - } - - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DIGESTMETHOD; - } + /** + * Returns the actual {@link java.security.MessageDigest} algorithm object + * + * @return the actual {@link java.security.MessageDigest} algorithm object + */ + public java.security.MessageDigest getAlgorithm() { + return algorithm; + } + + /** + * Proxy method for {@link java.security.MessageDigest#isEqual} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param digesta + * @param digestb + * @return the result of the {@link java.security.MessageDigest#isEqual} method + */ + public static boolean isEqual(byte[] digesta, byte[] digestb) { + return java.security.MessageDigest.isEqual(digesta, digestb); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest()} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#digest()} method + */ + public byte[] digest() { + return algorithm.digest(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest(byte[])} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method + */ + public byte[] digest(byte input[]) { + return algorithm.digest(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param buf + * @param offset + * @param len + * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method + * @throws java.security.DigestException + */ + public int digest(byte buf[], int offset, int len) throws java.security.DigestException { + return algorithm.digest(buf, offset, len); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getAlgorithm} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method + */ + public String getJCEAlgorithmString() { + return algorithm.getAlgorithm(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getProvider} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getProvider} method + */ + public java.security.Provider getJCEProvider() { + return algorithm.getProvider(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getDigestLength} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getDigestLength} method + */ + public int getDigestLength() { + return algorithm.getDigestLength(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#reset} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + */ + public void reset() { + algorithm.reset(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte[])} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + */ + public void update(byte[] input) { + algorithm.update(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + */ + public void update(byte input) { + algorithm.update(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param buf + * @param offset + * @param len + */ + public void update(byte buf[], int offset, int len) { + algorithm.update(buf, offset, len); + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DIGESTMETHOD; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java 2013-06-28 11:32:57.867539974 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java 2013-06-28 11:32:57.691545452 -0400 @@ -42,7 +42,7 @@ import org.w3c.dom.Element; /** - * Allows selection of digital signature's algorithm, private keys, other + * Allows selection of digital signature's algorithm, private keys, other * security parameters, and algorithm's ID. * * @author Christian Geuer-Pollmann @@ -50,13 +50,13 @@ public class SignatureAlgorithm extends Algorithm { /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(SignatureAlgorithm.class.getName()); /** All available algorithm classes are registered here */ - private static Map> algorithmHash = + private static Map> algorithmHash = new ConcurrentHashMap>(); - + /** Field signatureAlgorithm */ private final SignatureAlgorithmSpi signatureAlgorithm; @@ -72,9 +72,9 @@ public SignatureAlgorithm(Document doc, String algorithmURI) throws XMLSecurityException { super(doc, algorithmURI); this.algorithmURI = algorithmURI; - + signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -90,12 +90,12 @@ ) throws XMLSecurityException { super(doc, algorithmURI); this.algorithmURI = algorithmURI; - + signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); - + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); + signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength); - ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement); + ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement); } /** @@ -108,7 +108,7 @@ public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException { this(element, baseURI, false); } - + /** * Constructor SignatureAlgorithm * @@ -120,38 +120,38 @@ public SignatureAlgorithm( Element element, String baseURI, boolean secureValidation ) throws XMLSecurityException { - super(element, baseURI); + super(element, baseURI); algorithmURI = this.getURI(); - + Attr attr = element.getAttributeNodeNS(null, "Id"); if (attr != null) { element.setIdAttributeNode(attr, true); } - + if (secureValidation && (XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(algorithmURI) || XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(algorithmURI))) { Object exArgs[] = { algorithmURI }; throw new XMLSecurityException("signature.signatureAlgorithm", exArgs); } - + signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** * Get a SignatureAlgorithmSpi object corresponding to the algorithmURI argument */ - private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI) + private static SignatureAlgorithmSpi getSignatureAlgorithmSpi(String algorithmURI) throws XMLSignatureException { try { - Class implementingClass = + Class implementingClass = algorithmHash.get(algorithmURI); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" + implementingClass + "\""); } - return implementingClass.newInstance(); + return implementingClass.newInstance(); } catch (IllegalAccessException ex) { Object exArgs[] = { algorithmURI, ex.getMessage() }; throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); @@ -237,12 +237,12 @@ * @param signingKey * @throws XMLSignatureException */ - public void initSign(Key signingKey) throws XMLSignatureException { + public void initSign(Key signingKey) throws XMLSignatureException { signatureAlgorithm.engineInitSign(signingKey); } /** - * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, + * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, * java.security.SecureRandom)} * which is executed on the internal {@link java.security.Signature} object. * @@ -290,14 +290,14 @@ public void initVerify(Key verificationKey) throws XMLSignatureException { signatureAlgorithm.engineInitVerify(verificationKey); } - + /** * Proxy method for {@link java.security.Signature#verify(byte[])} * which is executed on the internal {@link java.security.Signature} object. * * @param signature * @return true if if the signature is valid. - * + * * @throws XMLSignatureException */ public boolean verify(byte[] signature) throws XMLSignatureException { @@ -310,21 +310,21 @@ * @return the URI representation of Transformation algorithm */ public final String getURI() { - return _constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); } /** * Registers implementing class of the Transform algorithm with algorithmURI * * @param algorithmURI algorithmURI URI representation of Transform algorithm. - * @param implementingClass implementingClass the implementing class of + * @param implementingClass implementingClass the implementing class of * {@link SignatureAlgorithmSpi} * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered - * @throws XMLSignatureException + * @throws XMLSignatureException */ @SuppressWarnings("unchecked") public static void register(String algorithmURI, String implementingClass) - throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, + throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, XMLSignatureException { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); @@ -339,7 +339,7 @@ ); } try { - Class clazz = + Class clazz = (Class) ClassLoaderUtils.loadClass(implementingClass, SignatureAlgorithm.class); algorithmHash.put(algorithmURI, clazz); @@ -348,18 +348,18 @@ throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); } } - + /** * Registers implementing class of the Transform algorithm with algorithmURI * * @param algorithmURI algorithmURI URI representation of Transform algorithm. - * @param implementingClass implementingClass the implementing class of + * @param implementingClass implementingClass the implementing class of * {@link SignatureAlgorithmSpi} * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered - * @throws XMLSignatureException + * @throws XMLSignatureException */ public static void register(String algorithmURI, Class implementingClass) - throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, + throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, XMLSignatureException { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); @@ -375,14 +375,12 @@ } algorithmHash.put(algorithmURI, implementingClass); } - + /** * This method registers the default algorithms. */ public static void registerDefaultAlgorithms() { - algorithmHash.put( - XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class - ); + algorithmHash.put(SignatureDSA.URI, SignatureDSA.class); algorithmHash.put( XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class ); @@ -390,11 +388,11 @@ XMLSignature.ALGO_ID_MAC_HMAC_SHA1, IntegrityHmac.IntegrityHmacSHA1.class ); algorithmHash.put( - XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5, + XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5, SignatureBaseRSA.SignatureRSAMD5.class ); algorithmHash.put( - XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160, + XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160, SignatureBaseRSA.SignatureRSARIPEMD160.class ); algorithmHash.put( @@ -410,6 +408,15 @@ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class ); algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, SignatureECDSA.SignatureECDSASHA384.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class + ); + algorithmHash.put( XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class ); algorithmHash.put( --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java 2013-06-28 11:32:58.491520551 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java 2013-06-28 11:32:58.331525531 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms; @@ -27,157 +29,149 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public abstract class SignatureAlgorithmSpi { - /** - * Returns the URI representation of Transformation algorithm - * - * @return the URI representation of Transformation algorithm - */ - protected abstract String engineGetURI(); - - /** - * Proxy method for {@link java.security.Signature#getAlgorithm} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#getAlgorithm} method - */ - protected abstract String engineGetJCEAlgorithmString(); - - /** - * Method engineGetJCEProviderName - * - * @return the JCE ProviderName - */ - protected abstract String engineGetJCEProviderName(); - - /** - * Proxy method for {@link java.security.Signature#update(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected abstract void engineUpdate(byte[] input) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#update(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected abstract void engineUpdate(byte input) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#update(byte[], int, int)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param buf - * @param offset - * @param len - * @throws XMLSignatureException - */ - protected abstract void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signingKey - * @throws XMLSignatureException if this method is called on a MAC - */ - protected abstract void engineInitSign(Key signingKey) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signingKey - * @param secureRandom - * @throws XMLSignatureException if this method is called on a MAC - */ - protected abstract void engineInitSign( - Key signingKey, SecureRandom secureRandom) throws XMLSignatureException; - - /** - * Proxy method for {@link javax.crypto.Mac} - * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object. - * - * @param signingKey - * @param algorithmParameterSpec - * @throws XMLSignatureException if this method is called on a Signature - */ - protected abstract void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#sign()} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#sign()} method - * @throws XMLSignatureException - */ - protected abstract byte[] engineSign() throws XMLSignatureException; - - /** - * Method engineInitVerify - * - * @param verificationKey - * @throws XMLSignatureException - */ - protected abstract void engineInitVerify(Key verificationKey) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#verify(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signature - * @return true if the signature is correct - * @throws XMLSignatureException - */ - protected abstract boolean engineVerify(byte[] signature) - throws XMLSignatureException; - - /** - * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param params - * @throws XMLSignatureException - */ - protected abstract void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException; - - - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { - } - - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - * @throws XMLSignatureException - */ - protected abstract void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException; + /** + * Returns the URI representation of Transformation algorithm + * + * @return the URI representation of Transformation algorithm + */ + protected abstract String engineGetURI(); + + /** + * Proxy method for {@link java.security.Signature#getAlgorithm} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#getAlgorithm} method + */ + protected abstract String engineGetJCEAlgorithmString(); + + /** + * Method engineGetJCEProviderName + * + * @return the JCE ProviderName + */ + protected abstract String engineGetJCEProviderName(); + + /** + * Proxy method for {@link java.security.Signature#update(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected abstract void engineUpdate(byte[] input) throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#update(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected abstract void engineUpdate(byte input) throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#update(byte[], int, int)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param buf + * @param offset + * @param len + * @throws XMLSignatureException + */ + protected abstract void engineUpdate(byte buf[], int offset, int len) + throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signingKey + * @throws XMLSignatureException if this method is called on a MAC + */ + protected abstract void engineInitSign(Key signingKey) throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, + * java.security.SecureRandom)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signingKey + * @param secureRandom + * @throws XMLSignatureException if this method is called on a MAC + */ + protected abstract void engineInitSign(Key signingKey, SecureRandom secureRandom) + throws XMLSignatureException; + + /** + * Proxy method for {@link javax.crypto.Mac} + * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object. + * + * @param signingKey + * @param algorithmParameterSpec + * @throws XMLSignatureException if this method is called on a Signature + */ + protected abstract void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#sign()} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#sign()} method + * @throws XMLSignatureException + */ + protected abstract byte[] engineSign() throws XMLSignatureException; + + /** + * Method engineInitVerify + * + * @param verificationKey + * @throws XMLSignatureException + */ + protected abstract void engineInitVerify(Key verificationKey) throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#verify(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signature + * @return true if the signature is correct + * @throws XMLSignatureException + */ + protected abstract boolean engineVerify(byte[] signature) throws XMLSignatureException; + + /** + * Proxy method for {@link java.security.Signature#setParameter( + * java.security.spec.AlgorithmParameterSpec)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param params + * @throws XMLSignatureException + */ + protected abstract void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException; + + + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + } + + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + * @throws XMLSignatureException + */ + protected abstract void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException; public void reset() { - } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java 2013-06-28 11:32:59.083502124 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java 2013-06-28 11:32:58.915507354 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; @@ -42,570 +42,498 @@ import org.w3c.dom.Element; import org.w3c.dom.Text; - -/** - * - * @author $Author: mullan $ - */ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName()); - - /** - * Method engineGetURI - * - *@inheritDoc - */ - public abstract String engineGetURI(); - - /** - * Returns the output length of the hash/digest. - */ - abstract int getDigestLength(); - - /** Field _macAlgorithm */ - private Mac _macAlgorithm = null; - private boolean _HMACOutputLengthSet = false; - - /** Field _HMACOutputLength */ - int _HMACOutputLength = 0; - - /** - * Method IntegrityHmacSHA1das - * - * @throws XMLSignatureException - */ - public IntegrityHmac() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); - - try { - this._macAlgorithm = Mac.getInstance(algorithmID); - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } - } - - /** - * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param params - * @throws XMLSignatureException - */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { - throw new XMLSignatureException("empty"); - } - - public void reset() { - _HMACOutputLength=0; - _HMACOutputLengthSet = false; - _macAlgorithm.reset(); - } - - /** - * Proxy method for {@link java.security.Signature#verify(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param signature - * @return true if the signature is correct - * @throws XMLSignatureException - */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - - try { - if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "HMACOutputLength must not be less than " + getDigestLength()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IntegrityHmac.class.getName()); + + /** Field macAlgorithm */ + private Mac macAlgorithm = null; + + /** Field HMACOutputLength */ + private int HMACOutputLength = 0; + private boolean HMACOutputLengthSet = false; + + /** + * Method engineGetURI + * + *@inheritDoc + */ + public abstract String engineGetURI(); + + /** + * Returns the output length of the hash/digest. + */ + abstract int getDigestLength(); + + /** + * Method IntegrityHmac + * + * @throws XMLSignatureException + */ + public IntegrityHmac() throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); + } + + try { + this.macAlgorithm = Mac.getInstance(algorithmID); + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** + * Proxy method for {@link java.security.Signature#setParameter( + * java.security.spec.AlgorithmParameterSpec)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param params + * @throws XMLSignatureException + */ + protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { + throw new XMLSignatureException("empty"); + } + + 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. + * + * @param signature + * @return true if the signature is correct + * @throws XMLSignatureException + */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { + try { + if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + byte[] completeResult = this.macAlgorithm.doFinal(); + return MessageDigestAlgorithm.isEqual(completeResult, signature); } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - byte[] completeResult = this._macAlgorithm.doFinal(); - return MessageDigestAlgorithm.isEqual(completeResult, signature); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitVerify(Key secretKey) throws XMLSignatureException { - - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param secretKey + * @throws XMLSignatureException + */ + protected void engineInitVerify(Key secretKey) throws XMLSignatureException { + if (!(secretKey instanceof SecretKey)) { + String supplied = secretKey.getClass().getName(); + String needed = SecretKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { // reinstantiate Mac object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Mac mac = this._macAlgorithm; + Mac mac = this.macAlgorithm; try { - this._macAlgorithm = Mac.getInstance - (_macAlgorithm.getAlgorithm()); + this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous Mac if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e); } - this._macAlgorithm = mac; + this.macAlgorithm = mac; } throw new XMLSignatureException("empty", ex); - } - } + } + } - /** - * Proxy method for {@link java.security.Signature#sign()} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#sign()} method - * @throws XMLSignatureException - */ - protected byte[] engineSign() throws XMLSignatureException { - - try { - if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "HMACOutputLength must not be less than " + getDigestLength()); + /** + * Proxy method for {@link java.security.Signature#sign()} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#sign()} method + * @throws XMLSignatureException + */ + protected byte[] engineSign() throws XMLSignatureException { + try { + if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + return this.macAlgorithm.doFinal(); } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - return this._macAlgorithm.doFinal(); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method reduceBitLength - * - * @param completeResult - * @return the reduced bits. - * @param length - * - */ - private static byte[] reduceBitLength(byte completeResult[], int length) { - - int bytes = length / 8; - int abits = length % 8; - byte[] strippedResult = new byte[bytes + ((abits == 0) - ? 0 - : 1)]; - - System.arraycopy(completeResult, 0, strippedResult, 0, bytes); - - if (abits > 0) { - byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, - (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE }; - - strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]); - } - - return strippedResult; - } - - /** - * Method engineInitSign - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey) throws XMLSignatureException { - - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method engineInitSign - * - * @param secretKey - * @param algorithmParameterSpec - * @throws XMLSignatureException - */ - protected void engineInitSign( - Key secretKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._macAlgorithm.init(secretKey, algorithmParameterSpec); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method engineInitSign - * - * @param secretKey - * @param secureRandom - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey, SecureRandom secureRandom) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); - } - - /** - * Proxy method for {@link java.security.Signature#update(byte[])} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { - - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Proxy method for {@link java.security.Signature#update(byte)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param input - * @throws XMLSignatureException - */ - protected void engineUpdate(byte input) throws XMLSignatureException { - - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Proxy method for {@link java.security.Signature#update(byte[], int, int)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param buf - * @param offset - * @param len - * @throws XMLSignatureException - */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { - - try { - this._macAlgorithm.update(buf, offset, len); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method engineGetJCEAlgorithmString - * @inheritDoc - * - */ - protected String engineGetJCEAlgorithmString() { - - log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); - - return this._macAlgorithm.getAlgorithm(); - } - - /** - * Method engineGetJCEAlgorithmString - * - * @inheritDoc - */ - protected String engineGetJCEProviderName() { - return this._macAlgorithm.getProvider().getName(); - } - - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - */ - protected void engineSetHMACOutputLength(int HMACOutputLength) { - this._HMACOutputLength = HMACOutputLength; - this._HMACOutputLengthSet = true; - } - - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { - - super.engineGetContextFromElement(element); - - if (element == null) { - throw new IllegalArgumentException("element null"); - } - - Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), - Constants._TAG_HMACOUTPUTLENGTH,0); - - if (hmaclength != null) { - this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); - this._HMACOutputLengthSet = true; - } - - } - - /** - * Method engineAddContextToElement - * - * @param element - */ - public void engineAddContextToElement(Element element) { - - if (element == null) { - throw new IllegalArgumentException("null element"); - } - - if (this._HMACOutputLengthSet) { - Document doc = element.getOwnerDocument(); - Element HMElem = XMLUtils.createElementInSignatureSpace(doc, - Constants._TAG_HMACOUTPUTLENGTH); - Text HMText = - doc.createTextNode(new Integer(this._HMACOutputLength).toString()); - - HMElem.appendChild(HMText); - XMLUtils.addReturnToElement(element); - element.appendChild(HMElem); - XMLUtils.addReturnToElement(element); - } - } - - /** - * Class IntegrityHmacSHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA1 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA1 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA1() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; - } - - int getDigestLength() { - return 160; - } - } - - /** - * Class IntegrityHmacSHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA256 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA256 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA256() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; - } - - int getDigestLength() { - return 256; - } - } - - /** - * Class IntegrityHmacSHA384 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA384 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA384 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA384() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; - } - - int getDigestLength() { - return 384; - } - } - - /** - * Class IntegrityHmacSHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA512 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacSHA512 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA512() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; - } - - int getDigestLength() { - return 512; - } - } - - /** - * Class IntegrityHmacRIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacRIPEMD160 - * - * @throws XMLSignatureException - */ - public IntegrityHmacRIPEMD160() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; - } - - int getDigestLength() { - return 160; - } - } - - /** - * Class IntegrityHmacMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacMD5 extends IntegrityHmac { - - /** - * Constructor IntegrityHmacMD5 - * - * @throws XMLSignatureException - */ - public IntegrityHmacMD5() throws XMLSignatureException { - super(); - } - - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; - } - - int getDigestLength() { - return 128; - } - } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Method engineInitSign + * + * @param secretKey + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey) throws XMLSignatureException { + if (!(secretKey instanceof SecretKey)) { + String supplied = secretKey.getClass().getName(); + String needed = SecretKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Method engineInitSign + * + * @param secretKey + * @param algorithmParameterSpec + * @throws XMLSignatureException + */ + protected void engineInitSign( + Key secretKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + if (!(secretKey instanceof SecretKey)) { + String supplied = secretKey.getClass().getName(); + String needed = SecretKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.macAlgorithm.init(secretKey, algorithmParameterSpec); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Method engineInitSign + * + * @param secretKey + * @param secureRandom + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey, SecureRandom secureRandom) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); + } + + /** + * Proxy method for {@link java.security.Signature#update(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this.macAlgorithm.update(input); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Proxy method for {@link java.security.Signature#update(byte)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param input + * @throws XMLSignatureException + */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this.macAlgorithm.update(input); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Proxy method for {@link java.security.Signature#update(byte[], int, int)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param buf + * @param offset + * @param len + * @throws XMLSignatureException + */ + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + try { + this.macAlgorithm.update(buf, offset, len); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Method engineGetJCEAlgorithmString + * @inheritDoc + * + */ + protected String engineGetJCEAlgorithmString() { + return this.macAlgorithm.getAlgorithm(); + } + + /** + * Method engineGetJCEAlgorithmString + * + * @inheritDoc + */ + protected String engineGetJCEProviderName() { + return this.macAlgorithm.getProvider().getName(); + } + + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + */ + protected void engineSetHMACOutputLength(int HMACOutputLength) { + this.HMACOutputLength = HMACOutputLength; + this.HMACOutputLengthSet = true; + } + + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + super.engineGetContextFromElement(element); + + if (element == null) { + throw new IllegalArgumentException("element null"); + } + + Text hmaclength = + XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); + + if (hmaclength != null) { + this.HMACOutputLength = Integer.parseInt(hmaclength.getData()); + this.HMACOutputLengthSet = true; + } + } + + /** + * Method engineAddContextToElement + * + * @param element + */ + public void engineAddContextToElement(Element element) { + if (element == null) { + throw new IllegalArgumentException("null element"); + } + + if (this.HMACOutputLengthSet) { + Document doc = element.getOwnerDocument(); + Element HMElem = + XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); + Text HMText = + doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); + + HMElem.appendChild(HMText); + XMLUtils.addReturnToElement(element); + element.appendChild(HMElem); + XMLUtils.addReturnToElement(element); + } + } + + /** + * Class IntegrityHmacSHA1 + */ + public static class IntegrityHmacSHA1 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacSHA1 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA1() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; + } + + int getDigestLength() { + return 160; + } + } + + /** + * Class IntegrityHmacSHA256 + */ + public static class IntegrityHmacSHA256 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacSHA256 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA256() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; + } + + int getDigestLength() { + return 256; + } + } + + /** + * Class IntegrityHmacSHA384 + */ + public static class IntegrityHmacSHA384 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacSHA384 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA384() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; + } + + int getDigestLength() { + return 384; + } + } + + /** + * Class IntegrityHmacSHA512 + */ + public static class IntegrityHmacSHA512 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacSHA512 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA512() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; + } + + int getDigestLength() { + return 512; + } + } + + /** + * Class IntegrityHmacRIPEMD160 + */ + public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacRIPEMD160 + * + * @throws XMLSignatureException + */ + public IntegrityHmacRIPEMD160() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; + } + + int getDigestLength() { + return 160; + } + } + + /** + * Class IntegrityHmacMD5 + */ + public static class IntegrityHmacMD5 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacMD5 + * + * @throws XMLSignatureException + */ + public IntegrityHmacMD5() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; + } + + int getDigestLength() { + return 128; + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java 2013-06-28 11:32:59.815479340 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java 2013-06-28 11:32:59.643484693 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; @@ -36,22 +38,17 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignature; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; -/** - * - * @author $Author: mullan $ - */ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (SignatureBaseRSA.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName()); /** @inheritDoc */ public abstract String engineGetURI(); /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + private java.security.Signature signatureAlgorithm = null; /** * Constructor SignatureRSA @@ -59,17 +56,17 @@ * @throws XMLSignatureException */ public SignatureBaseRSA() throws XMLSignatureException { - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID); - String provider=JCEMapper.getProviderId(); + } + String provider = JCEMapper.getProviderId(); try { - if (provider==null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); + if (provider == null) { + this.signatureAlgorithm = Signature.getInstance(algorithmID); } else { - this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); + this.signatureAlgorithm = Signature.getInstance(algorithmID,provider); } } catch (java.security.NoSuchAlgorithmException ex) { Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; @@ -85,20 +82,17 @@ /** @inheritDoc */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { - try { - this._signatureAlgorithm.setParameter(params); + this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { throw new XMLSignatureException("empty", ex); } } /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { try { - return this._signatureAlgorithm.verify(signature); + return this.signatureAlgorithm.verify(signature); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -106,41 +100,38 @@ /** @inheritDoc */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - if (!(publicKey instanceof PublicKey)) { String supplied = publicKey.getClass().getName(); String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); + this.signatureAlgorithm.initVerify((PublicKey) publicKey); } catch (InvalidKeyException ex) { // reinstantiate Signature object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Signature sig = this._signatureAlgorithm; + Signature sig = this.signatureAlgorithm; try { - this._signatureAlgorithm = Signature.getInstance - (_signatureAlgorithm.getAlgorithm()); + this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { - // this shouldn't occur, but if it does, restore previous + // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } - this._signatureAlgorithm = sig; + this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); - } + } } /** @inheritDoc */ protected byte[] engineSign() throws XMLSignatureException { try { - return this._signatureAlgorithm.sign(); + return this.signatureAlgorithm.sign(); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -149,19 +140,16 @@ /** @inheritDoc */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign - ((PrivateKey) privateKey, secureRandom); + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -169,18 +157,16 @@ /** @inheritDoc */ protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); + this.signatureAlgorithm.initSign((PrivateKey) privateKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -189,7 +175,7 @@ /** @inheritDoc */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -198,17 +184,16 @@ /** @inheritDoc */ protected void engineUpdate(byte input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } } /** @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); + this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -216,34 +201,29 @@ /** @inheritDoc */ protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); + return this.signatureAlgorithm.getAlgorithm(); } /** @inheritDoc */ protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); + return this.signatureAlgorithm.getProvider().getName(); } /** @inheritDoc */ protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException { - throw new XMLSignatureException - ("algorithms.HMACOutputLengthOnlyForHMAC"); + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); } /** @inheritDoc */ protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA"); } /** * Class SignatureRSASHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA1 extends SignatureBaseRSA { @@ -264,9 +244,6 @@ /** * Class SignatureRSASHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA256 extends SignatureBaseRSA { @@ -287,9 +264,6 @@ /** * Class SignatureRSASHA384 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA384 extends SignatureBaseRSA { @@ -310,9 +284,6 @@ /** * Class SignatureRSASHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA512 extends SignatureBaseRSA { @@ -333,9 +304,6 @@ /** * Class SignatureRSARIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { @@ -356,9 +324,6 @@ /** * Class SignatureRSAMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSAMD5 extends SignatureBaseRSA { --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java 2013-06-28 11:33:00.567455933 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java 2013-06-28 11:33:00.367462157 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; @@ -37,21 +39,17 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; -/** - * - * @author $Author: mullan $ - */ public class SignatureDSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(SignatureDSA.class.getName()); - /** Field _URI */ - public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1"; + /** Field URI */ + public static final String URI = Constants.SignatureSpecNS + "dsa-sha1"; /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + private java.security.Signature signatureAlgorithm = null; /** * Method engineGetURI @@ -59,7 +57,7 @@ * @inheritDoc */ protected String engineGetURI() { - return SignatureDSA._URI; + return SignatureDSA.URI; } /** @@ -68,17 +66,17 @@ * @throws XMLSignatureException */ public SignatureDSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI); - if (log.isLoggable(java.util.logging.Level.FINE)) + String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI); + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); + } String provider = JCEMapper.getProviderId(); try { if (provider == null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); + this.signatureAlgorithm = Signature.getInstance(algorithmID); } else { - this._signatureAlgorithm = + this.signatureAlgorithm = Signature.getInstance(algorithmID, provider); } } catch (java.security.NoSuchAlgorithmException ex) { @@ -95,9 +93,8 @@ */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { - try { - this._signatureAlgorithm.setParameter(params); + this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { throw new XMLSignatureException("empty", ex); } @@ -107,15 +104,15 @@ * @inheritDoc */ protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - + throws XMLSignatureException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature)); + } byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature); - return this._signatureAlgorithm.verify(jcebytes); + return this.signatureAlgorithm.verify(jcebytes); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } catch (IOException ex) { @@ -127,32 +124,29 @@ * @inheritDoc */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - if (!(publicKey instanceof PublicKey)) { String supplied = publicKey.getClass().getName(); String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); + this.signatureAlgorithm.initVerify((PublicKey) publicKey); } catch (InvalidKeyException ex) { // reinstantiate Signature object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 - Signature sig = this._signatureAlgorithm; + Signature sig = this.signatureAlgorithm; try { - this._signatureAlgorithm = Signature.getInstance - (_signatureAlgorithm.getAlgorithm()); + this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } - this._signatureAlgorithm = sig; + this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); } @@ -162,9 +156,8 @@ * @inheritDoc */ protected byte[] engineSign() throws XMLSignatureException { - try { - byte jcebytes[] = this._signatureAlgorithm.sign(); + byte jcebytes[] = this.signatureAlgorithm.sign(); return SignatureDSA.convertASN1toXMLDSIG(jcebytes); } catch (IOException ex) { @@ -178,20 +171,17 @@ * @inheritDoc */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { - + throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -201,18 +191,16 @@ * @inheritDoc */ protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; - throw new XMLSignatureException - ("algorithms.WrongKeyForThisOperation", exArgs); + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); + this.signatureAlgorithm.initSign((PrivateKey) privateKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } @@ -223,7 +211,7 @@ */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -234,7 +222,7 @@ */ protected void engineUpdate(byte input) throws XMLSignatureException { try { - this._signatureAlgorithm.update(input); + this.signatureAlgorithm.update(input); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -243,10 +231,9 @@ /** * @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); + this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -258,7 +245,7 @@ * @inheritDoc */ protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); + return this.signatureAlgorithm.getAlgorithm(); } /** @@ -267,7 +254,7 @@ * @inheritDoc */ protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); + return this.signatureAlgorithm.getProvider().getName(); } /** @@ -282,8 +269,7 @@ * @throws IOException * @see 6.4.1 DSA */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { + private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { byte rLength = asn1Bytes[3]; int i; @@ -294,21 +280,20 @@ int j; for (j = sLength; - (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); + (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) - || (asn1Bytes[2] != 2) || (i > 20) - || (asn1Bytes[4 + rLength] != 2) || (j > 20)) { + || (asn1Bytes[2] != 2) || (i > 20) + || (asn1Bytes[4 + rLength] != 2) || (j > 20)) { throw new IOException("Invalid ASN.1 format of DSA signature"); - } + } byte xmldsigBytes[] = new byte[40]; - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, - i); + System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i); System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 40 - j, j); + 40 - j, j); - return xmldsigBytes; + return xmldsigBytes; } /** @@ -323,8 +308,7 @@ * @throws IOException * @see 6.4.1 DSA */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { + private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { if (xmldsigBytes.length != 40) { throw new IOException("Invalid XMLDSIG format of DSA signature"); @@ -337,7 +321,7 @@ int j = i; if (xmldsigBytes[20 - i] < 0) { - j += 1; + j += 1; } int k; @@ -373,10 +357,8 @@ * @param HMACOutputLength * @throws XMLSignatureException */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.HMACOutputLengthOnlyForHMAC"); + protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); } /** @@ -387,9 +369,8 @@ * @throws XMLSignatureException */ protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnDSA"); + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA"); } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java 2013-06-28 11:33:01.231435265 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java 2013-06-28 11:33:01.051440867 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; @@ -40,345 +40,417 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * - * @author $Author: mullan $ + * @author $Author: raul $ + * @author Alex Dupre */ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(SignatureECDSA.class.getName()); /** @inheritDoc */ - public abstract String engineGetURI(); + public abstract String engineGetURI(); + + /** Field algorithm */ + private java.security.Signature signatureAlgorithm = null; + + /** + * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param asn1Bytes + * @return the decode bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { + + if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + int offset; + if (asn1Bytes[1] > 0) { + offset = 2; + } else if (asn1Bytes[1] == (byte) 0x81) { + offset = 3; + } else { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + + byte rLength = asn1Bytes[offset + 1]; + int i; + + for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--); + + byte sLength = asn1Bytes[offset + 2 + rLength + 1]; + int j; + + for (j = sLength; + (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--); + + int rawLen = Math.max(i, j); + + if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset + || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength + || asn1Bytes[offset] != 2 + || asn1Bytes[offset + 2 + rLength] != 2) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + byte xmldsigBytes[] = new byte[2*rawLen]; + + System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i); + System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes, + 2*rawLen - j, j); + + return xmldsigBytes; + } + + /** + * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { + + int rawLen = xmldsigBytes.length/2; + + int i; + + for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--); + + int j = i; + + if (xmldsigBytes[rawLen - i] < 0) { + j += 1; + } + + int k; + + for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--); + + int l = k; + + if (xmldsigBytes[2*rawLen - k] < 0) { + l += 1; + } + + int len = 2 + j + 2 + l; + if (len > 255) { + throw new IOException("Invalid XMLDSIG format of ECDSA signature"); + } + int offset; + byte asn1Bytes[]; + if (len < 128) { + asn1Bytes = new byte[2 + 2 + j + 2 + l]; + offset = 1; + } else { + asn1Bytes = new byte[3 + 2 + j + 2 + l]; + asn1Bytes[1] = (byte) 0x81; + offset = 2; + } + asn1Bytes[0] = 48; + asn1Bytes[offset++] = (byte) len; + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) j; + + System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i); + + offset += j; + + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) l; + + System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k); + + return asn1Bytes; + } + + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureECDSA() throws XMLSignatureException { + + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); + } + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { + this.signatureAlgorithm = Signature.getInstance(algorithmID); + } 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() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + try { + this.signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { + try { + byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + } + + return this.signatureAlgorithm.verify(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - /** Field algorithm */ - private java.security.Signature _signatureAlgorithm = null; + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; - /** - * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. - * - * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param asn1Bytes - * @return the decode bytes - * - * @throws IOException - * @see 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { - - byte rLength = asn1Bytes[3]; - int i; - - for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); - - byte sLength = asn1Bytes[5 + rLength]; - int j; - - for (j = sLength; - (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); - - if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) - || (asn1Bytes[2] != 2) || (i > 24) - || (asn1Bytes[4 + rLength] != 2) || (j > 24)) { - throw new IOException("Invalid ASN.1 format of ECDSA signature"); - } - byte xmldsigBytes[] = new byte[48]; - - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, - i); - System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 48 - j, j); - - return xmldsigBytes; - } - - /** - * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. - * - * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param xmldsigBytes - * @return the encoded ASN.1 bytes - * - * @throws IOException - * @see 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - - if (xmldsigBytes.length != 48) { - throw new IOException("Invalid XMLDSIG format of ECDSA signature"); - } - - int i; - - for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); - - int j = i; - - if (xmldsigBytes[24 - i] < 0) { - j += 1; - } - - int k; - - for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); - - int l = k; - - if (xmldsigBytes[48 - k] < 0) { - l += 1; - } - - byte asn1Bytes[] = new byte[6 + j + l]; - - asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); - asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; - - System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i); - - asn1Bytes[4 + j] = 2; - asn1Bytes[5 + j] = (byte) l; - - System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); - - return asn1Bytes; - } - - /** - * Constructor SignatureRSA - * - * @throws XMLSignatureException - */ - public SignatureECDSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); - } 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() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } - } - - /** @inheritDoc */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { - - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { - - try { - byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); - - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); - - return this._signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineInitVerify(Key publicKey) throws XMLSignatureException { - - if (!(publicKey instanceof PublicKey)) { - String 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) { + 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.sun.com/view_bug.do?bug_id=4953555 - Signature sig = this._signatureAlgorithm; + Signature sig = this.signatureAlgorithm; try { - this._signatureAlgorithm = Signature.getInstance - (_signatureAlgorithm.getAlgorithm()); + this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous // Signature if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e); } - this._signatureAlgorithm = sig; + this.signatureAlgorithm = sig; } throw new XMLSignatureException("empty", ex); - } - } + } + } + + /** @inheritDoc */ + protected byte[] engineSign() throws XMLSignatureException { + try { + byte jcebytes[] = this.signatureAlgorithm.sign(); + + return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitSign(Key privateKey, SecureRandom secureRandom) + throws XMLSignatureException { + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + if (!(privateKey instanceof PrivateKey)) { + String supplied = privateKey.getClass().getName(); + String needed = PrivateKey.class.getName(); + Object exArgs[] = { supplied, needed }; - /** @inheritDoc */ - protected byte[] engineSign() throws XMLSignatureException { + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - try { - byte jcebytes[] = this._signatureAlgorithm.sign(); + /** @inheritDoc */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { - - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { - - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } - - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineUpdate(byte[] input) throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineUpdate(byte input) throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { - - try { - this._signatureAlgorithm.update(buf, offset, len); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); - } - - /** @inheritDoc */ - protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); - } - - /** @inheritDoc */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); - } - - /** @inheritDoc */ - protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); - } - - /** - * Class SignatureRSASHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.2 $ - */ - public static class SignatureECDSASHA1 extends SignatureECDSA { - - /** - * Constructor SignatureRSASHA1 - * - * @throws XMLSignatureException - */ - public SignatureECDSASHA1() throws XMLSignatureException { - super(); - } - - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; - } - } + /** @inheritDoc */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(buf, offset, len); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected String engineGetJCEAlgorithmString() { + return this.signatureAlgorithm.getAlgorithm(); + } + + /** @inheritDoc */ + protected String engineGetJCEProviderName() { + return this.signatureAlgorithm.getProvider().getName(); + } + + /** @inheritDoc */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); + } + + /** @inheritDoc */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + } + + /** + * Class SignatureRSASHA1 + * + * @author $Author: marcx $ + */ + public static class SignatureECDSASHA1 extends SignatureECDSA { + /** + * Constructor SignatureRSASHA1 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA1() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; + } + } + + /** + * Class SignatureRSASHA256 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA256 extends SignatureECDSA { + + /** + * Constructor SignatureRSASHA256 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA256() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256; + } + } + + /** + * Class SignatureRSASHA384 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA384 extends SignatureECDSA { + + /** + * Constructor SignatureRSASHA384 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA384() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384; + } + } + + /** + * Class SignatureRSASHA512 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA512 extends SignatureECDSA { + + /** + * Constructor SignatureRSASHA512 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA512() throws XMLSignatureException { + super(); + } + + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512; + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java 2013-06-28 11:33:01.827416713 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java 2013-06-28 11:33:01.655422066 -0400 @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Class CanonicalizationException * @@ -32,57 +31,58 @@ */ public class CanonicalizationException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor CanonicalizationException - * - */ - public CanonicalizationException() { - super(); - } - - /** - * Constructor CanonicalizationException - * - * @param _msgID - */ - public CanonicalizationException(String _msgID) { - super(_msgID); - } - - /** - * Constructor CanonicalizationException - * - * @param _msgID - * @param exArgs - */ - public CanonicalizationException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor CanonicalizationException - * - * @param _msgID - * @param _originalException - */ - public CanonicalizationException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor CanonicalizationException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public CanonicalizationException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor CanonicalizationException + * + */ + public CanonicalizationException() { + super(); + } + + /** + * Constructor CanonicalizationException + * + * @param msgID + */ + public CanonicalizationException(String msgID) { + super(msgID); + } + + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param exArgs + */ + public CanonicalizationException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param originalException + */ + public CanonicalizationException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public CanonicalizationException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java 2013-06-28 11:33:02.543394426 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java 2013-06-28 11:33:02.347400527 -0400 @@ -39,6 +39,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments; +import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -55,48 +56,53 @@ public static final String ENCODING = "UTF8"; /** - * XPath Expression for selecting every node and continuous comments joined - * in only one node + * XPath Expression for selecting every node and continuous comments joined + * in only one node */ - public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = + public static final String XPATH_C14N_WITH_COMMENTS_SINGLE_NODE = "(.//. | .//@* | .//namespace::*)"; /** * The URL defined in XML-SEC Rec for inclusive c14n without comments. */ - public static final String ALGO_ID_C14N_OMIT_COMMENTS = + public static final String ALGO_ID_C14N_OMIT_COMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; /** * The URL defined in XML-SEC Rec for inclusive c14n with comments. */ - public static final String ALGO_ID_C14N_WITH_COMMENTS = + public static final String ALGO_ID_C14N_WITH_COMMENTS = ALGO_ID_C14N_OMIT_COMMENTS + "#WithComments"; /** * The URL defined in XML-SEC Rec for exclusive c14n without comments. */ - public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS = + public static final String ALGO_ID_C14N_EXCL_OMIT_COMMENTS = "http://www.w3.org/2001/10/xml-exc-c14n#"; /** * The URL defined in XML-SEC Rec for exclusive c14n with comments. */ - public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS = + public static final String ALGO_ID_C14N_EXCL_WITH_COMMENTS = ALGO_ID_C14N_EXCL_OMIT_COMMENTS + "WithComments"; /** * The URI for inclusive c14n 1.1 without comments. */ - public static final String ALGO_ID_C14N11_OMIT_COMMENTS = + public static final String ALGO_ID_C14N11_OMIT_COMMENTS = "http://www.w3.org/2006/12/xml-c14n11"; /** * The URI for inclusive c14n 1.1 with comments. */ - public static final String ALGO_ID_C14N11_WITH_COMMENTS = + public static final String ALGO_ID_C14N11_WITH_COMMENTS = ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; + /** + * Non-standard algorithm to serialize the physical representation for XML Encryption + */ + public static final String ALGO_ID_C14N_PHYSICAL = + "http://santuario.apache.org/c14n/physical"; - private static Map> canonicalizerHash = + private static Map> canonicalizerHash = new ConcurrentHashMap>(); - + private final CanonicalizerSpi canonicalizerSpi; - + /** * Constructor Canonicalizer * @@ -105,7 +111,7 @@ */ private Canonicalizer(String algorithmURI) throws InvalidCanonicalizerException { try { - Class implementingClass = + Class implementingClass = canonicalizerHash.get(algorithmURI); canonicalizerSpi = implementingClass.newInstance(); @@ -141,7 +147,7 @@ public static void register(String algorithmURI, String implementingClass) throws AlgorithmAlreadyRegisteredException, ClassNotFoundException { // check whether URI is already registered - Class registeredClass = + Class registeredClass = canonicalizerHash.get(algorithmURI); if (registeredClass != null) { @@ -153,7 +159,7 @@ algorithmURI, (Class)Class.forName(implementingClass) ); } - + /** * Method register * @@ -173,35 +179,39 @@ canonicalizerHash.put(algorithmURI, implementingClass); } - + /** * This method registers the default algorithms. */ public static void registerDefaultAlgorithms() { canonicalizerHash.put( - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, Canonicalizer20010315OmitComments.class ); canonicalizerHash.put( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS, + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS, Canonicalizer20010315WithComments.class ); canonicalizerHash.put( - Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS, + Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS, Canonicalizer20010315ExclOmitComments.class ); canonicalizerHash.put( - Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS, + Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS, Canonicalizer20010315ExclWithComments.class ); canonicalizerHash.put( - Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS, + Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS, Canonicalizer11_OmitComments.class ); canonicalizerHash.put( - Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, + Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer11_WithComments.class ); + canonicalizerHash.put( + Canonicalizer.ALGO_ID_C14N_PHYSICAL, + CanonicalizerPhysical.class + ); } /** @@ -326,9 +336,9 @@ public byte[] canonicalizeXPathNodeSet( NodeList xpathNodeSet, String inclusiveNamespaces ) throws CanonicalizationException { - return + return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); - } + } /** * Canonicalizes an XPath node set. @@ -337,7 +347,7 @@ * @return the result of the c14n. * @throws CanonicalizationException */ - public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet) + public byte[] canonicalizeXPathNodeSet(Set xpathNodeSet) throws CanonicalizationException { return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); } @@ -353,12 +363,12 @@ public byte[] canonicalizeXPathNodeSet( Set xpathNodeSet, String inclusiveNamespaces ) throws CanonicalizationException { - return + return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); } /** - * Sets the writer where the canonicalization ends. ByteArrayOutputStream + * Sets the writer where the canonicalization ends. ByteArrayOutputStream * if none is set. * @param os */ @@ -381,5 +391,5 @@ public void notReset() { canonicalizerSpi.reset = false; } - + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java 2013-06-28 11:33:03.147375626 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java 2013-06-28 11:33:02.955381602 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n; - - import java.io.ByteArrayInputStream; import java.io.OutputStream; import java.util.Set; @@ -29,7 +29,6 @@ import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; @@ -37,166 +36,134 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; - /** - * Base class which all Caninicalization algorithms extend. + * Base class which all Canonicalization algorithms extend. * - * $todo$ cange JavaDoc * @author Christian Geuer-Pollmann */ public abstract class CanonicalizerSpi { - /** - * Method canonicalize - * - * - * @param inputBytes - * @return the c14n bytes. - * - * - * @throws CanonicalizationException - * @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 { - - java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); - InputSource in = new InputSource(bais); - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - - // needs to validate for ID attribute nomalization - dfactory.setNamespaceAware(true); - - DocumentBuilder db = dfactory.newDocumentBuilder(); - - /* - * for some of the test vectors from the specification, - * there has to be a validatin parser for ID attributes, default - * attribute values, NMTOKENS, etc. - * Unfortunaltely, the test vectors do use different DTDs or - * even no DTD. So Xerces 1.3.1 fires many warnings about using - * ErrorHandlers. - * - * 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. - * - */ - - // ErrorHandler eh = new C14NErrorHandler(); - // db.setErrorHandler(eh); - Document document = db.parse(in); - byte result[] = this.engineCanonicalizeSubTree(document); - return result; - } - - /** - * 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); - } - - //J- - /** Returns the URI of this engine. - * @return the URI - */ - public abstract String engineGetURI(); - - /** Returns the URI if include comments - * @return true if include. - */ - public abstract boolean engineGetIncludeComments(); - - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - throws CanonicalizationException; - - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException; - - /** - * C14n a node tree. - * - * @param rootNode - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException; - - /** - * C14n a node tree. - * - * @param rootNode - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) - throws CanonicalizationException; - - /** - * Sets the writter where the cannocalization ends. ByteArrayOutputStream if - * none is setted. - * @param os - */ - public abstract void setWriter(OutputStream os); - - /** Reset the writter after a c14n */ - protected boolean reset=false; - //J+ + /** Reset the writer after a c14n */ + protected boolean reset = false; + + /** + * Method canonicalize + * + * @param inputBytes + * @return the c14n bytes. + * + * @throws CanonicalizationException + * @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 { + + java.io.InputStream bais = new ByteArrayInputStream(inputBytes); + InputSource in = new InputSource(bais); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + + // needs to validate for ID attribute normalization + dfactory.setNamespaceAware(true); + + DocumentBuilder db = dfactory.newDocumentBuilder(); + + Document document = db.parse(in); + 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 + ); + } + + /** + * Returns the URI of this engine. + * @return the URI + */ + 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 + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException; + + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException; + + /** + * C14n a node tree. + * + * @param rootNode + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException; + + /** + * C14n a node tree. + * + * @param rootNode + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException; + + /** + * Sets the writer where the canonicalization ends. ByteArrayOutputStream if + * none is set. + * @param os + */ + public abstract void setWriter(OutputStream os); + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java 2013-06-28 11:33:03.831354336 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java 2013-06-28 11:33:03.663359564 -0400 @@ -2,87 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * @author Christian Geuer-Pollmann - */ public class InvalidCanonicalizerException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor InvalidCanonicalizerException - * - */ - public InvalidCanonicalizerException() { - super(); - } - - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - */ - public InvalidCanonicalizerException(String _msgID) { - super(_msgID); - } - - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - * @param exArgs - */ - public InvalidCanonicalizerException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - * @param _originalException - */ - public InvalidCanonicalizerException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidCanonicalizerException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor InvalidCanonicalizerException + * + */ + public InvalidCanonicalizerException() { + super(); + } + + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + */ + public InvalidCanonicalizerException(String msgID) { + super(msgID); + } + + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param exArgs + */ + public InvalidCanonicalizerException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param originalException + */ + public InvalidCanonicalizerException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidCanonicalizerException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java 2013-06-28 11:33:04.527332671 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java 2013-06-28 11:33:04.359337901 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.helper; @@ -29,7 +31,7 @@ * Compares two attributes based on the C14n specification. * *
    - *
  • Namespace nodes have a lesser document order position than attribute + *
  • Namespace nodes have a lesser document order position than attribute * nodes. *
  • An element's namespace nodes are sorted lexicographically by * local name (the default namespace node, if one exists, has no @@ -43,16 +45,16 @@ */ public class AttrCompare implements Comparator, Serializable { - private final static long serialVersionUID = -7113259629930576230L; - private final static int ATTR0_BEFORE_ATTR1 = -1; - private final static int ATTR1_BEFORE_ATTR0 = 1; - private final static String XMLNS=Constants.NamespaceSpecNS; + private static final long serialVersionUID = -7113259629930576230L; + private static final int ATTR0_BEFORE_ATTR1 = -1; + private static final int ATTR1_BEFORE_ATTR0 = 1; + private static final String XMLNS = Constants.NamespaceSpecNS; /** * Compares two attributes based on the C14n specification. * *
      - *
    • Namespace nodes have a lesser document order position than + *
    • Namespace nodes have a lesser document order position than * attribute nodes. *
    • An element's namespace nodes are sorted lexicographically by * local name (the default namespace node, if one exists, has no @@ -64,17 +66,16 @@ * * @param attr0 * @param attr1 - * @return returns a negative integer, zero, or a positive integer as + * @return returns a negative integer, zero, or a positive integer as * obj0 is less than, equal to, or greater than obj1 * */ public int compare(Attr attr0, Attr attr1) { - - String namespaceURI0 = attr0.getNamespaceURI(); + String namespaceURI0 = attr0.getNamespaceURI(); String namespaceURI1 = attr1.getNamespaceURI(); - - boolean isNamespaceAttr0 = XMLNS==namespaceURI0; - boolean isNamespaceAttr1 = XMLNS==namespaceURI1; + + boolean isNamespaceAttr0 = XMLNS.equals(namespaceURI0); + boolean isNamespaceAttr1 = XMLNS.equals(namespaceURI1); if (isNamespaceAttr0) { if (isNamespaceAttr1) { @@ -82,11 +83,11 @@ String localname0 = attr0.getLocalName(); String localname1 = attr1.getLocalName(); - if (localname0.equals("xmlns")) { + if ("xmlns".equals(localname0)) { localname0 = ""; } - if (localname1.equals("xmlns")) { + if ("xmlns".equals(localname1)) { localname1 = ""; } @@ -94,12 +95,10 @@ } // attr0 is a namespace, attr1 is not return ATTR0_BEFORE_ATTR1; - } - - if (isNamespaceAttr1) { + } else if (isNamespaceAttr1) { // attr1 is a namespace, attr0 is not return ATTR1_BEFORE_ATTR0; - } + } // none is a namespace if (namespaceURI0 == null) { @@ -109,17 +108,15 @@ return name0.compareTo(name1); } return ATTR0_BEFORE_ATTR1; - } - - if (namespaceURI1 == null) { + } else if (namespaceURI1 == null) { return ATTR1_BEFORE_ATTR0; - } + } int a = namespaceURI0.compareTo(namespaceURI1); if (a != 0) { return a; } - + return (attr0.getLocalName()).compareTo(attr1.getLocalName()); } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java 2013-06-28 11:33:05.227310882 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java 2013-06-28 11:33:05.059316112 -0400 @@ -2,33 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.helper; - - import 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,129 +35,121 @@ */ public class C14nHelper { - /** - * Constructor C14nHelper - * - */ - private C14nHelper() { - - // don't allow instantiation - } - - /** - * Method namespaceIsRelative - * - * @param namespace - * @return true if the given namespace is relative. - */ - public static boolean namespaceIsRelative(Attr namespace) { - return !namespaceIsAbsolute(namespace); - } - - /** - * Method namespaceIsRelative - * - * @param namespaceValue - * @return true if the given namespace is relative. - */ - public static boolean namespaceIsRelative(String namespaceValue) { - return !namespaceIsAbsolute(namespaceValue); - } - - /** - * Method namespaceIsAbsolute - * - * @param namespace - * @return true if the given namespace is absolute. - */ - public static boolean namespaceIsAbsolute(Attr namespace) { - return namespaceIsAbsolute(namespace.getValue()); - } - - /** - * Method namespaceIsAbsolute - * - * @param namespaceValue - * @return true if the given namespace is absolute. - */ - public static boolean namespaceIsAbsolute(String namespaceValue) { - - // assume empty namespaces are absolute - if (namespaceValue.length() == 0) { - return true; - } - return namespaceValue.indexOf(':')>0; - } - - /** - * 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 = nodeAttrName.equals("xmlns"); - boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); + /** + * Constructor C14nHelper + * + */ + private C14nHelper() { + // don't allow instantiation + } + + /** + * Method namespaceIsRelative + * + * @param namespace + * @return true if the given namespace is relative. + */ + public static boolean namespaceIsRelative(Attr namespace) { + return !namespaceIsAbsolute(namespace); + } + + /** + * Method namespaceIsRelative + * + * @param namespaceValue + * @return true if the given namespace is relative. + */ + public static boolean namespaceIsRelative(String namespaceValue) { + return !namespaceIsAbsolute(namespaceValue); + } + + /** + * Method namespaceIsAbsolute + * + * @param namespace + * @return true if the given namespace is absolute. + */ + public static boolean namespaceIsAbsolute(Attr namespace) { + return namespaceIsAbsolute(namespace.getValue()); + } + + /** + * Method namespaceIsAbsolute + * + * @param namespaceValue + * @return true if the given namespace is absolute. + */ + public static boolean namespaceIsAbsolute(String namespaceValue) { + // assume empty namespaces are absolute + if (namespaceValue.length() == 0) { + return true; + } + return namespaceValue.indexOf(':') > 0; + } + + /** + * 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 = nodeAttrName.equals("xmlns"); + boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); - if (definesDefaultNS || definesNonDefaultNS) { - if (namespaceIsRelative(attr)) { + 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(); - - for (int i = 0; i < attributes.getLength(); i++) { - C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); - } - } else { - throw new CanonicalizationException( - "Called checkForRelativeNamespace() on null"); - } - } + "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(); + + for (int i = 0; i < attributes.getLength(); i++) { + C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); + } + } else { + throw new CanonicalizationException("Called checkForRelativeNamespace() on null"); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java 2013-06-28 11:33:05.931288971 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java 2013-06-28 11:33:05.751294572 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -25,7 +27,6 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -34,7 +35,6 @@ import java.util.SortedSet; import java.util.TreeSet; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -42,8 +42,6 @@ import org.w3c.dom.Node; import org.xml.sax.SAXException; -import java.util.logging.Logger; -import java.util.logging.Logger; 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.signature.XMLSignatureInput; @@ -52,45 +50,51 @@ /** * Implements - * Canonical XML Version 1.1, a W3C Proposed Recommendation from 29 + * Canonical XML Version 1.1, a W3C Proposed Recommendation from 29 * January 2008. * * @author Sean Mullan * @author Raul Benito - * @version $Revision: 1.2 $ */ public abstract class Canonicalizer11 extends CanonicalizerBase { - boolean firstCall = true; - final SortedSet result = new TreeSet(COMPARE); - static final String XMLNS_URI = Constants.NamespaceSpecNS; - static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; - - static Logger log = Logger.getLogger(Canonicalizer11.class.getName()); + + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Canonicalizer11.class.getName()); + private final SortedSet result = new TreeSet(COMPARE); + + private boolean firstCall = true; - static class XmlAttrStack { - int currentLevel = 0; - int lastlevel = 0; - XmlsStackElement cur; + private static class XmlAttrStack { static class XmlsStackElement { int level; boolean rendered = false; List nodes = new ArrayList(); }; - List levels = new ArrayList(); + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; + List levels = new ArrayList(); + void push(int level) { currentLevel = level; - if (currentLevel == -1) + if (currentLevel == -1) { return; + } cur = null; while (lastlevel >= currentLevel) { levels.remove(levels.size() - 1); - if (levels.size() == 0) { + int newSize = levels.size(); + if (newSize == 0) { lastlevel = 0; - return; + return; } - lastlevel=(levels.get(levels.size()-1)).level; + lastlevel = (levels.get(newSize - 1)).level; } } + void addXmlnsAttr(Attr n) { if (cur == null) { cur = new XmlsStackElement(); @@ -100,22 +104,24 @@ } cur.nodes.add(n); } + void getXmlnsAttr(Collection col) { + int size = levels.size() - 1; if (cur == null) { cur = new XmlsStackElement(); cur.level = currentLevel; lastlevel = currentLevel; levels.add(cur); } - int size = levels.size() - 2; boolean parentRendered = false; XmlsStackElement e = null; if (size == -1) { parentRendered = true; } else { e = levels.get(size); - if (e.rendered && e.level+1 == currentLevel) + if (e.rendered && e.level + 1 == currentLevel) { parentRendered = true; + } } if (parentRendered) { col.addAll(cur.nodes); @@ -123,10 +129,10 @@ return; } - Map loa = new HashMap(); + Map loa = new HashMap(); List baseAttrs = new ArrayList(); boolean successiveOmitted = true; - for (;size>=0;size--) { + for (; size >= 0; size--) { e = levels.get(size); if (e.rendered) { successiveOmitted = false; @@ -134,16 +140,15 @@ Iterator it = e.nodes.iterator(); while (it.hasNext() && successiveOmitted) { Attr n = it.next(); - if (n.getLocalName().equals("base")) { - if (!e.rendered) { - baseAttrs.add(n); - } - } else if (!loa.containsKey(n.getName())) + if (n.getLocalName().equals("base") && !e.rendered) { + baseAttrs.add(n); + } else if (!loa.containsKey(n.getName())) { loa.put(n.getName(), n); + } } } if (!baseAttrs.isEmpty()) { - Iterator it = cur.nodes.iterator(); + Iterator it = col.iterator(); String base = null; Attr baseAttr = null; while (it.hasNext()) { @@ -164,7 +169,9 @@ try { base = joinURI(n.getValue(), base); } catch (URISyntaxException ue) { - ue.printStackTrace(); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ue.getMessage(), ue); + } } } } @@ -178,8 +185,9 @@ col.addAll(loa.values()); } }; - XmlAttrStack xmlattrStack = new XmlAttrStack(); - + + private XmlAttrStack xmlattrStack = new XmlAttrStack(); + /** * Constructor Canonicalizer11 * @@ -190,186 +198,197 @@ } /** - * Returns the Attr[]s to be outputted for the given element. + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Returns the Attr[]s to be output for the given element. *
      * The code of this method is a copy of {@link #handleAttributes(Element, * NameSpaceSymbTable)}, - * whereas it takes into account that subtree-c14n is -- well -- + * whereas it takes into account that subtree-c14n is -- well -- * subtree-based. * So if the element in question isRoot of c14n, it's parent is not in the * node set, as well as all other ancestors. * - * @param E + * @param element * @param ns - * @return the Attr[]s to be outputted + * @return the Attr[]s to be output * @throws CanonicalizationException */ - Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) throws CanonicalizationException { - if (!E.hasAttributes() && !firstCall) { - return null; + if (!element.hasAttributes() && !firstCall) { + return null; } - // result will contain the attrs which have to be outputted - final SortedSet result = this.result; + // result will contain the attrs which have to be output + final SortedSet result = this.result; result.clear(); - NamedNodeMap attrs = E.getAttributes(); - int attrsLength = attrs.getLength(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri = N.getNamespaceURI(); - - if (XMLNS_URI != NUri) { - // It's not a namespace attr node. Add to the result and - // continue. - result.add(N); - continue; - } - - String NName = N.getLocalName(); - String NValue = N.getValue(); - if (XML.equals(NName) - && XML_LANG_URI.equals(NValue)) { - // The default mapping for xml must not be output. - continue; - } - - Node n = ns.addMappingAndRender(NName, NValue, N); - if (n != null) { - // Render the ns definition - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()}; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + // It's not a namespace attr node. Add to the result and continue. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) { + // The default mapping for xml must not be output. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + + if (n != null) { + // Render the ns definition + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()}; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } } } } if (firstCall) { // It is the first node of the subtree - // Obtain all the namespaces defined in the parents, and added - // to the output. - ns.getUnrenderedNodes(result); + // Obtain all the namespaces defined in the parents, and added to the output. + ns.getUnrenderedNodes(result); // output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(getSortedSetAsCollection(result)); + xmlattrStack.getXmlnsAttr(result); firstCall = false; - } + } return result.iterator(); } - - /** - * Returns the Attr[]s to be outputted for the given element. + * Returns the Attr[]s to be output for the given element. *
      - * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a - * DOM which has been prepared using + * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a + * DOM which has been prepared using * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( * org.w3c.dom.Document)}. - * - * @param E + * + * @param element * @param ns - * @return the Attr[]s to be outputted + * @return the Attr[]s to be output * @throws CanonicalizationException */ - Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { // result will contain the attrs which have to be output xmlattrStack.push(ns.getLevel()); - boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1; - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); - } - - SortedSet result = this.result; + boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1; + final SortedSet result = this.result; result.clear(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr)attrs.item(i); - String NUri = N.getNamespaceURI(); - - if (XMLNS_URI != NUri) { - // A non namespace definition node. - if (XML_LANG_URI == NUri) { - if (N.getLocalName().equals("id")) { - if (isRealVisible) { - // treat xml:id like any other attribute - // (emit it, but don't inherit it) - result.add(N); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //A non namespace definition node. + if (XML_LANG_URI.equals(NUri)) { + if (NName.equals("id")) { + if (isRealVisible) { + // treat xml:id like any other attribute + // (emit it, but don't inherit it) + result.add(attribute); + } + } else { + xmlattrStack.addXmlnsAttr(attribute); + } + } else if (isRealVisible) { + //The node is visible add the attribute to the list of output attributes. + result.add(attribute); + } + } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) { + /* except omit namespace node with local name xml, which defines + * the xml prefix, if its string value is + * http://www.w3.org/XML/1998/namespace. + */ + // add the prefix binding to the ns symb table. + if (isVisible(attribute)) { + if (isRealVisible || !ns.removeMappingIfRender(NName)) { + // The xpath select this node output it if needed. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } } } else { - xmlattrStack.addXmlnsAttr(N); - } - } else if (isRealVisible) { - // The node is visible add the attribute to the list of - // output attributes. - result.add(N); - } - // keep working - continue; - } - - String NName = N.getLocalName(); - String NValue = N.getValue(); - if ("xml".equals(NName) - && XML_LANG_URI.equals(NValue)) { - /* except omit namespace node with local name xml, which defines - * the xml prefix, if its string value is - * http://www.w3.org/XML/1998/namespace. - */ - continue; - } - // add the prefix binding to the ns symb table. - // ns.addInclusiveMapping(NName,NValue,N,isRealVisible); - if (isVisible(N)) { - if (!isRealVisible && ns.removeMappingIfRender(NName)) { - continue; - } - // The xpath select this node output it if needed. - // Node n = ns.addMappingAndRenderXNodeSet - // (NName, NValue, N, isRealVisible); - Node n = ns.addMappingAndRender(NName, NValue, N); - if (n != null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = - { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); + if (isRealVisible && !XMLNS.equals(NName)) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, attribute); + } } } - } else { - if (isRealVisible && NName != XMLNS) { - ns.removeMapping(NName); - } else { - ns.addMapping(NName, NValue, N); - } } } - if (isRealVisible) { - // The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); + + if (isRealVisible) { + //The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); Node n = null; if (xmlns == null) { - // No xmlns def just get the already defined. - n = ns.getMapping(XMLNS); + //No xmlns def just get the already defined. + n = ns.getMapping(XMLNS); } else if (!isVisible(xmlns)) { - // There is a defn but the xmlns is not selected by the xpath. - // then xmlns="" - n = ns.addMappingAndRender(XMLNS, "", nullNode); + //There is a definition but the xmlns is not selected by the xpath. + //then xmlns="" + n = ns.addMappingAndRender(XMLNS, "", nullNode); } - // output the xmlns def if needed. + //output the xmlns def if needed. if (n != null) { result.add((Attr)n); } - // Float all xml:* attributes of the unselected parent elements to - // this one. addXmlAttributes(E,result); + //Float all xml:* attributes of the unselected parent elements to this one. xmlattrStack.getXmlnsAttr(result); ns.getUnrenderedNodes(result); } @@ -377,39 +396,12 @@ return result.iterator(); } - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException always - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } - - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param rootNode - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } - - void circumventBugIfNeeded(XMLSignatureInput input) - throws CanonicalizationException, ParserConfigurationException, + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - if (!input.isNeedsToBeExpanded()) + if (!input.isNeedsToBeExpanded()) { return; + } Document doc = null; if (input.getSubNode() != null) { doc = XMLUtils.getOwnerDocument(input.getSubNode()); @@ -419,40 +411,47 @@ XMLUtils.circumventBug2650(doc); } - void handleParent(Element e, NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { return; } xmlattrStack.push(-1); NamedNodeMap attrs = e.getAttributes(); int attrsLength = attrs.getLength(); for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS != N.getNamespaceURI()) { - // Not a namespace definition, ignore. - if (XML_LANG_URI == N.getNamespaceURI()) { - xmlattrStack.addXmlnsAttr(N); - } - continue; - } - - String NName = N.getLocalName(); - String NValue = N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); + + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) { + if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + ns.addMapping(NName, NValue, attribute); + } + } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); + } + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = "xmlns"; + Name = "xmlns"; + } else { + Name = "xmlns:" + NName; } - ns.addMapping(NName,NValue,N); + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); } } - private static String joinURI(String baseURI, String relativeURI) - throws URISyntaxException { + private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException { String bscheme = null; String bauthority = null; String bpath = ""; String bquery = null; - String bfragment = null; // Is this correct? // pre-parse the baseURI if (baseURI != null) { @@ -464,7 +463,6 @@ bauthority = base.getAuthority(); bpath = base.getPath(); bquery = base.getQuery(); - bfragment = base.getFragment(); } URI r = new URI(relativeURI); @@ -472,9 +470,8 @@ String rauthority = r.getAuthority(); String rpath = r.getPath(); String rquery = r.getQuery(); - String rfragment = null; - String tscheme, tauthority, tpath, tquery, tfragment; + String tscheme, tauthority, tpath, tquery; if (rscheme != null && rscheme.equals(bscheme)) { rscheme = null; } @@ -502,7 +499,7 @@ } else { if (bauthority != null && bpath.length() == 0) { tpath = "/" + rpath; - } else { + } else { int last = bpath.lastIndexOf('/'); if (last == -1) { tpath = rpath; @@ -518,13 +515,13 @@ } tscheme = bscheme; } - tfragment = rfragment; - return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString(); + return new URI(tscheme, tauthority, tpath, tquery, null).toString(); } private static String removeDotSegments(String path) { - - log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER"); + } // 1. The input buffer is initialized with the now-appended path // components then replace occurrences of "//" in the input buffer @@ -535,7 +532,7 @@ } // Initialize the output buffer with the empty string. - StringBuffer output = new StringBuffer(); + StringBuilder output = new StringBuilder(); // If the input buffer starts with a root slash "/" then move this // character to the output buffer. @@ -563,9 +560,9 @@ output.append("../"); } printStep("2A", output.toString(), input); - // 2B. if the input buffer begins with a prefix of "/./" or "/.", - // where "." is a complete path segment, then replace that prefix - // with "/" in the input buffer; otherwise, + // 2B. if the input buffer begins with a prefix of "/./" or "/.", + // where "." is a complete path segment, then replace that prefix + // with "/" in the input buffer; otherwise, } else if (input.startsWith("/./")) { input = input.substring(2); printStep("2B", output.toString(), input); @@ -573,16 +570,16 @@ // FIXME: what is complete path segment? input = input.replaceFirst("/.", "/"); printStep("2B", output.toString(), input); - // 2C. if the input buffer begins with a prefix of "/../" or "/..", - // where ".." is a complete path segment, then replace that prefix - // with "/" in the input buffer and if also the output buffer is - // empty, last segment in the output buffer equals "../" or "..", - // where ".." is a complete path segment, then append ".." or "/.." - // for the latter case respectively to the output buffer else - // remove the last segment and its preceding "/" (if any) from the - // output buffer and if hereby the first character in the output - // buffer was removed and it was not the root slash then delete a - // leading slash from the input buffer; otherwise, + // 2C. if the input buffer begins with a prefix of "/../" or "/..", + // where ".." is a complete path segment, then replace that prefix + // with "/" in the input buffer and if also the output buffer is + // empty, last segment in the output buffer equals "../" or "..", + // where ".." is a complete path segment, then append ".." or "/.." + // for the latter case respectively to the output buffer else + // remove the last segment and its preceding "/" (if any) from the + // output buffer and if hereby the first character in the output + // buffer was removed and it was not the root slash then delete a + // leading slash from the input buffer; otherwise, } else if (input.startsWith("/../")) { input = input.substring(3); if (output.length() == 0) { @@ -594,7 +591,7 @@ } else { int index = output.lastIndexOf("/"); if (index == -1) { - output = new StringBuffer(); + output = new StringBuilder(); if (input.charAt(0) == '/') { input = input.substring(1); } @@ -615,7 +612,7 @@ } else { int index = output.lastIndexOf("/"); if (index == -1) { - output = new StringBuffer(); + output = new StringBuilder(); if (input.charAt(0) == '/') { input = input.substring(1); } @@ -624,23 +621,24 @@ } } printStep("2C", output.toString(), input); - // 2D. if the input buffer consists only of ".", then remove - // that from the input buffer else if the input buffer consists - // only of ".." and if the output buffer does not contain only - // the root slash "/", then move the ".." to the output buffer - // else delte it.; otherwise, + // 2D. if the input buffer consists only of ".", then remove + // that from the input buffer else if the input buffer consists + // only of ".." and if the output buffer does not contain only + // the root slash "/", then move the ".." to the output buffer + // else delte it.; otherwise, } else if (input.equals(".")) { input = ""; printStep("2D", output.toString(), input); } else if (input.equals("..")) { - if (!output.toString().equals("/")) + if (!output.toString().equals("/")) { output.append(".."); + } input = ""; printStep("2D", output.toString(), input); - // 2E. move the first path segment (if any) in the input buffer - // to the end of the output buffer, including the initial "/" - // character (if any) and any subsequent characters up to, but not - // including, the next "/" character or the end of the input buffer. + // 2E. move the first path segment (if any) in the input buffer + // to the end of the output buffer, including the initial "/" + // character (if any) and any subsequent characters up to, but not + // including, the next "/" character or the end of the input buffer. } else { int end = -1; int begin = input.indexOf('/'); --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java 2013-06-28 11:33:06.703264940 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java 2013-06-28 11:33:06.543269920 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * 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 * - * Licensed 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java 2013-06-28 11:33:07.359244521 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java 2013-06-28 11:33:07.179250124 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * 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 * - * Licensed 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java 2013-06-28 11:33:08.003224475 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java 2013-06-28 11:33:07.815230327 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import java.io.IOException; import java.util.ArrayList; import java.util.Collection; @@ -47,344 +47,348 @@ import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * Implements Canonical * XML Version 1.0, a W3C Recommendation from 15 March 2001. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class Canonicalizer20010315 extends CanonicalizerBase { - boolean firstCall=true; - final SortedSet result= new TreeSet(COMPARE); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS; - static class XmlAttrStack { - int currentLevel=0; - int lastlevel=0; - XmlsStackElement cur; + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + + private boolean firstCall = true; + private final SortedSet result = new TreeSet(COMPARE); + + private static class XmlAttrStack { static class XmlsStackElement { - int level; - boolean rendered=false; - List nodes=new ArrayList(); + int level; + boolean rendered = false; + List nodes = new ArrayList(); }; - List levels=new ArrayList(); + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; + List levels = new ArrayList(); + void push(int level) { - currentLevel=level; - if (currentLevel==-1) - return; - cur=null; - while (lastlevel>=currentLevel) { - levels.remove(levels.size()-1); - if (levels.size()==0) { - lastlevel=0; - return; - } - lastlevel=(levels.get(levels.size()-1)).level; + currentLevel = level; + if (currentLevel == -1) { + return; + } + cur = null; + while (lastlevel >= currentLevel) { + levels.remove(levels.size() - 1); + int newSize = levels.size(); + if (newSize == 0) { + lastlevel = 0; + return; } + lastlevel = (levels.get(newSize - 1)).level; + } } + void addXmlnsAttr(Attr n) { - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - levels.add(cur); - lastlevel=currentLevel; - } - cur.nodes.add(n); + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + levels.add(cur); + lastlevel = currentLevel; + } + cur.nodes.add(n); } + void getXmlnsAttr(Collection col) { - int size=levels.size()-1; - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - lastlevel=currentLevel; - levels.add(cur); + int size = levels.size() - 1; + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + lastlevel = currentLevel; + levels.add(cur); + } + boolean parentRendered = false; + XmlsStackElement e = null; + if (size == -1) { + parentRendered = true; + } else { + e = levels.get(size); + if (e.rendered && e.level + 1 == currentLevel) { + parentRendered = true; } - boolean parentRendered=false; - XmlsStackElement e=null; - if (size==-1) { - parentRendered=true; - } else { - e=levels.get(size); - if (e.rendered && e.level+1==currentLevel) - parentRendered=true; - + } + if (parentRendered) { + col.addAll(cur.nodes); + cur.rendered = true; + return; + } + + Map loa = new HashMap(); + for (; size >= 0; size--) { + e = levels.get(size); + Iterator it = e.nodes.iterator(); + while (it.hasNext()) { + Attr n = it.next(); + if (!loa.containsKey(n.getName())) { + loa.put(n.getName(), n); + } } - if (parentRendered) { - col.addAll(cur.nodes); - cur.rendered=true; - return; - } + } + + cur.rendered = true; + col.addAll(loa.values()); + } - Map loa = new HashMap(); - for (;size>=0;size--) { - e=levels.get(size); - Iterator it=e.nodes.iterator(); - while (it.hasNext()) { - Attr n=it.next(); - if (!loa.containsKey(n.getName())) - loa.put(n.getName(),n); - } - //if (e.rendered) - //break; + } - }; - //cur.nodes.clear(); - //cur.nodes.addAll(loa.values()); - cur.rendered=true; - col.addAll(loa.values()); - } + private XmlAttrStack xmlattrStack = new XmlAttrStack(); + /** + * Constructor Canonicalizer20010315 + * + * @param includeComments + */ + public Canonicalizer20010315(boolean includeComments) { + super(includeComments); } - XmlAttrStack xmlattrStack=new XmlAttrStack(); + /** - * Constructor Canonicalizer20010315 - * - * @param includeComments - */ - public Canonicalizer20010315(boolean includeComments) { - super(includeComments); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
      - * The code of this method is a copy of {@link #handleAttributes(Element, - * NameSpaceSymbTable)}, - * whereas it takes into account that subtree-c14n is -- well -- subtree-based. - * So if the element in question isRoot of c14n, it's parent is not in the - * node set, as well as all other ancestors. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException { - if (!E.hasAttributes() && !firstCall) { - return null; - } - // result will contain the attrs which have to be outputted - final SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = E.getAttributes(); - int attrsLength = attrs.getLength(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri =N.getNamespaceURI(); - - if (XMLNS_URI!=NUri) { - //It's not a namespace attr node. Add to the result and continue. - result.add(N); - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getValue(); - if (XML.equals(NName) - && XML_LANG_URI.equals(NValue)) { - //The default mapping for xml must not be output. - continue; - } - - Node n=ns.addMappingAndRender(NName,NValue,N); - - if (n!=null) { - //Render the ns definition - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - - if (firstCall) { - //It is the first node of the subtree - //Obtain all the namespaces defined in the parents, and added to the output. - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); - //output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(result); - firstCall=false; - } - - return result.iterator(); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
      - * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has - * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException { - // result will contain the attrs which have to be outputted - xmlattrStack.push(ns.getLevel()); - boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1; - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs=E.getAttributes(); - attrsLength= attrs.getLength(); + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } + /** + * Always throws a CanonicalizationException because this is inclusive c14n. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException { - SortedSet result = this.result; - result.clear(); + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri =N.getNamespaceURI(); - - if (XMLNS_URI!=NUri) { - //A non namespace definition node. - if (XML_LANG_URI==NUri) { - xmlattrStack.addXmlnsAttr(N); - } else if (isRealVisible){ - //The node is visible add the attribute to the list of output attributes. - result.add(N); - } - //keep working - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getValue(); - if ("xml".equals(NName) - && XML_LANG_URI.equals(NValue)) { - /* except omit namespace node with local name xml, which defines - * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace. - */ - continue; - } - //add the prefix binding to the ns symb table. - //ns.addInclusiveMapping(NName,NValue,N,isRealVisible); - if (isVisible(N)) { - if (!isRealVisible && ns.removeMappingIfRender(NName)) { - continue; - } - //The xpath select this node output it if needed. - //Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); - Node n=ns.addMappingAndRender(NName,NValue,N); - if (n!=null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } else { - if (isRealVisible && NName!=XMLNS) { - ns.removeMapping(NName); - } else { - ns.addMapping(NName,NValue,N); + /** + * Returns the Attr[]s to be output for the given element. + *
      + * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes() && !firstCall) { + return null; + } + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //It's not a namespace attr node. Add to the result and continue. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) { + //The default mapping for xml must not be output. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + + if (n != null) { + //Render the ns definition + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } } + } } + + if (firstCall) { + //It is the first node of the subtree + //Obtain all the namespaces defined in the parents, and added to the output. + ns.getUnrenderedNodes(result); + //output the attributes in the xml namespace. + xmlattrStack.getXmlnsAttr(result); + firstCall = false; + } + + return result.iterator(); } - if (isRealVisible) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - Node n=null; - if (xmlns == null) { + + /** + * Returns the Attr[]s to be output for the given element. + *
      + * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has + * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1; + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //A non namespace definition node. + if (XML_LANG_URI.equals(NUri)) { + xmlattrStack.addXmlnsAttr(attribute); + } else if (isRealVisible) { + //The node is visible add the attribute to the list of output attributes. + result.add(attribute); + } + } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) { + /* except omit namespace node with local name xml, which defines + * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace. + */ + //add the prefix binding to the ns symb table. + if (isVisible(attribute)) { + if (isRealVisible || !ns.removeMappingIfRender(NName)) { + //The xpath select this node output it if needed. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } else { + if (isRealVisible && !XMLNS.equals(NName)) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, attribute); + } + } + } + } + } + if (isRealVisible) { + //The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + Node n = null; + if (xmlns == null) { //No xmlns def just get the already defined. - n=ns.getMapping(XMLNS); - } else if ( !isVisible(xmlns)) { + n = ns.getMapping(XMLNS); + } else if (!isVisible(xmlns)) { //There is a definition but the xmlns is not selected by the xpath. //then xmlns="" - n=ns.addMappingAndRender(XMLNS,"",nullNode); + n = ns.addMappingAndRender(XMLNS, "", nullNode); + } + //output the xmlns def if needed. + if (n != null) { + result.add((Attr)n); + } + //Float all xml:* attributes of the unselected parent elements to this one. + xmlattrStack.getXmlnsAttr(result); + ns.getUnrenderedNodes(result); } - //output the xmlns def if needed. - if (n!=null) { - result.add((Attr)n); - } - //Float all xml:* attributes of the unselected parent elements to this one. - //addXmlAttributes(E,result); - xmlattrStack.getXmlnsAttr(result); - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); + return result.iterator(); + } + + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + if (!input.isNeedsToBeExpanded()) { + return; + } + Document doc = null; + if (input.getSubNode() != null) { + doc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); } - return result.iterator(); - } - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException always - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { - - /** $todo$ well, should we throw UnsupportedOperationException ? */ - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } - - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param rootNode - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) - throws CanonicalizationException { - - /** $todo$ well, should we throw UnsupportedOperationException ? */ - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } - void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - if (!input.isNeedsToBeExpanded()) - return; - Document doc = null; - if (input.getSubNode() != null) { - doc=XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - doc=XMLUtils.getOwnerDocument(input.getNodeSet()); - } - XMLUtils.circumventBug2650(doc); - - } - - void handleParent(Element e, NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { - return; - } - xmlattrStack.push(-1); - NamedNodeMap attrs = e.getAttributes(); - int attrsLength = attrs.getLength(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { - //Not a namespace definition, ignore. - if (XML_LANG_URI==N.getNamespaceURI()) { - xmlattrStack.addXmlnsAttr(N); - } - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; - } - ns.addMapping(NName,NValue,N); - } - } + @Override + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { + return; + } + xmlattrStack.push(-1); + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); + + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) { + if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + ns.addMapping(NName, NValue, attribute); + } + } else if (XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); + } + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = "xmlns"; + Name = "xmlns"; + } else { + Name = "xmlns:" + NName; + } + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java 2013-06-28 11:33:08.659204056 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java 2013-06-28 11:33:08.471209908 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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. - * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -25,7 +27,6 @@ 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; @@ -40,6 +41,7 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; + /** * Implements " Exclusive XML @@ -50,303 +52,281 @@ * implementation of "Canonical XML". A big "thank you" to Ren?? for this. *
      * THIS implementation is a complete rewrite of the algorithm. - * + * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ + * @version $Revision: 1147448 $ * @see
      * XML Canonicalization, Version 1.0 */ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { + + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + /** * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of * the inclusive namespaces. */ - TreeSet _inclusiveNSSet = new TreeSet(); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - final SortedSet result = new TreeSet(COMPARE); - /** - * Constructor Canonicalizer20010315Excl - * - * @param includeComments - */ - public Canonicalizer20010315Excl(boolean includeComments) { - super(includeComments); - } + private SortedSet inclusiveNSSet; + + private final SortedSet result = new TreeSet(COMPARE); - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, "",null); - } - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @param inclusiveNamespaces - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, inclusiveNamespaces,null); - } - /** - * Method engineCanonicalizeSubTree - * @param rootNode - * @param inclusiveNamespaces - * @param excl A element to exclude from the c14n process. - * @return the rootNode c14n. - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces,Node excl) throws CanonicalizationException { - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalizeSubTree(rootNode,excl); - } - /** - * - * @param rootNode - * @param inclusiveNamespaces - * @return the rootNode c14n. - * @throws CanonicalizationException - */ - @SuppressWarnings("unchecked") - public byte[] engineCanonicalize(XMLSignatureInput rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalize(rootNode); - } + /** + * Constructor Canonicalizer20010315Excl + * + * @param includeComments + */ + public Canonicalizer20010315Excl(boolean includeComments) { + super(includeComments); + } - /** - * Method handleAttributesSubtree - * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E,NameSpaceSymbTable ns) - throws CanonicalizationException { - // System.out.println("During the traversal, I encountered " + - // XMLUtils.getXPath(E)); - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs=null; - - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); - } - //The prefix visibly utilized(in the attribute or in the name) in the element - SortedSet visiblyUtilized = getNSSetClone(); + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, "", null); + } - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @param inclusiveNamespaces + * + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, inclusiveNamespaces, null); + } - if (XMLNS_URI!=N.getNamespaceURI()) { - //Not a namespace definition. - //The Element is output element, add his prefix(if used) to visibyUtilized - String prefix = N.getPrefix(); - if ( (prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ) { - visiblyUtilized.add(prefix); - } - //Add to the result. - result.add(N); - continue; - } - String NName=N.getLocalName(); - String NNodeValue=N.getNodeValue(); + /** + * Method engineCanonicalizeSubTree + * @param rootNode + * @param inclusiveNamespaces + * @param excl A element to exclude from the c14n process. + * @return the rootNode c14n. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, Node excl + ) throws CanonicalizationException{ + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeSubTree(rootNode, excl); + } - if (ns.addMapping(NName, NNodeValue,N)) { - //New definition check if it is relative. - if (C14nHelper.namespaceIsRelative(NNodeValue)) { - Object exArgs[] = {E.getTagName(), NName, - N.getNodeValue()}; + /** + * + * @param rootNode + * @param inclusiveNamespaces + * @return the rootNode c14n. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalize( + XMLSignatureInput rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalize(rootNode); + } + + /** + * Method engineCanonicalizeXPathNodeSet + * @inheritDoc + * @param xpathNodeSet + * @param inclusiveNamespaces + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } + + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + SortedSet visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); + } + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NNodeValue = attribute.getNodeValue(); + + if (!XMLNS_URI.equals(attribute.getNamespaceURI())) { + // Not a namespace definition. + // The Element is output element, add the prefix (if used) to + // visiblyUtilized + String prefix = attribute.getPrefix(); + if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) { + visiblyUtilized.add(prefix); + } + // Add to the result. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NNodeValue)) + && ns.addMapping(NName, NNodeValue, attribute) + && C14nHelper.namespaceIsRelative(NNodeValue)) { + // The default mapping for xml must not be output. + // New definition check if it is relative. + Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()}; throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); } } - } - String prefix; - if (E.getNamespaceURI() != null) { - prefix = E.getPrefix(); - if ((prefix == null) || (prefix.length() == 0)) { - prefix=XMLNS; - } - - } else { - prefix=XMLNS; - } - visiblyUtilized.add(prefix); - - //This can be optimezed by I don't have time - Iterator it=visiblyUtilized.iterator(); - while (it.hasNext()) { - String s=it.next(); - Attr key=ns.getMapping(s); - if (key==null) { - continue; - } - result.add(key); - } - - return result.iterator(); } - - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @param inclusiveNamespaces - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); - + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; } - - @SuppressWarnings("unchecked") - private TreeSet getInclusiveNameSpace(String inclusiveNameSpaces) { - return (TreeSet)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces); - } - - - @SuppressWarnings("unchecked") - private SortedSet getNSSetClone() { - return (SortedSet) this._inclusiveNSSet.clone(); + visiblyUtilized.add(prefix); + + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } + + return result.iterator(); } - - - /** + + /** * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - final Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); + * @param element + * @throws CanonicalizationException + */ + @Override + protected final Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + Set visiblyUtilized = null; + // It's the output selected. + boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1; + if (isOutputElement) { + visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); + } } - //The prefix visibly utilized(in the attribute or in the name) in the element - Set visiblyUtilized =null; - //It's the output selected. - boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1; - if (isOutputElement) { - visiblyUtilized = getNSSetClone(); - } - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - - if (XMLNS_URI!=N.getNamespaceURI()) { - if ( !isVisible(N) ) { - //The node is not in the nodeset(if there is a nodeset) - continue; - } - //Not a namespace definition. - if (isOutputElement) { - //The Element is output element, add his prefix(if used) to visibyUtilized - String prefix = N.getPrefix(); - if ((prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ){ - visiblyUtilized.add(prefix); - } - //Add to the result. - result.add(N); - } - continue; - } - String NName=N.getLocalName(); - if (isOutputElement && !isVisible(N) && NName!=XMLNS) { - ns.removeMappingIfNotRender(NName); - continue; - } - String NNodeValue=N.getNodeValue(); - - if (!isOutputElement && isVisible(N) && _inclusiveNSSet.contains(NName) && !ns.removeMappingIfRender(NName)) { - Node n=ns.addMappingAndRender(NName,NNodeValue,N); - if (n!=null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + + String NName = attribute.getLocalName(); + String NNodeValue = attribute.getNodeValue(); + + if (!XMLNS_URI.equals(attribute.getNamespaceURI())) { + if (isVisible(attribute) && isOutputElement) { + // The Element is output element, add the prefix (if used) + // to visibyUtilized + String prefix = attribute.getPrefix(); + if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) { + visiblyUtilized.add(prefix); + } + // Add to the result. + result.add(attribute); + } + } else if (isOutputElement && !isVisible(attribute) && !XMLNS.equals(NName)) { + ns.removeMappingIfNotRender(NName); + } else { + if (!isOutputElement && isVisible(attribute) + && inclusiveNSSet.contains(NName) + && !ns.removeMappingIfRender(NName)) { + Node n = ns.addMappingAndRender(NName, NNodeValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } } + } - - - if (ns.addMapping(NName, NNodeValue,N)) { - //New definiton check if it is relative - if (C14nHelper.namespaceIsRelative(NNodeValue)) { - Object exArgs[] = {E.getTagName(), NName, - N.getNodeValue()}; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); + if (ns.addMapping(NName, NNodeValue, attribute) + && C14nHelper.namespaceIsRelative(NNodeValue)) { + // New definition check if it is relative + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } } } - } + } - if (isOutputElement) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - if ((xmlns!=null) && (!isVisible(xmlns))) { - //There is a definition but the xmlns is not selected by the xpath. - //then xmlns="" - ns.addMapping(XMLNS,"",nullNode); + if (isOutputElement) { + // The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + if (xmlns != null && !isVisible(xmlns)) { + // There is a definition but the xmlns is not selected by the + // xpath. then xmlns="" + ns.addMapping(XMLNS, "", nullNode); } - if (E.getNamespaceURI() != null) { - String prefix = E.getPrefix(); - if ((prefix == null) || (prefix.length() == 0)) { - visiblyUtilized.add(XMLNS); - } else { - visiblyUtilized.add( prefix); - } - } else { - visiblyUtilized.add(XMLNS); - } - //This can be optimezed by I don't have time - //visiblyUtilized.addAll(this._inclusiveNSSet); - Iterator it=visiblyUtilized.iterator(); - while (it.hasNext()) { - String s=it.next(); - Attr key=ns.getMapping(s); - if (key==null) { - continue; - } - result.add(key); - } + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; + } + visiblyUtilized.add(prefix); + + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); } + } + } - return result.iterator(); - } - void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty()) - return; - Document doc = null; - if (input.getSubNode() != null) { - doc=XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - doc=XMLUtils.getOwnerDocument(input.getNodeSet()); - } + return result.iterator(); + } - XMLUtils.circumventBug2650(doc); - } + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { + if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty() || inclusiveNSSet.isEmpty()) { + return; + } + Document doc = null; + if (input.getSubNode() != null) { + doc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java 2013-06-28 11:33:09.279184758 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java 2013-06-28 11:33:09.107190112 -0400 @@ -2,48 +2,44 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package com.sun.org.apache.xml.internal.security.c14n.implementations; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; -/** - * - * - */ -public class Canonicalizer20010315ExclOmitComments - extends Canonicalizer20010315Excl { - - /** - * - */ - public Canonicalizer20010315ExclOmitComments() { - super(false); - } - - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; - } +public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl { - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return false; - } + /** + * + */ + public Canonicalizer20010315ExclOmitComments() { + super(false); + } + + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + } + + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return false; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java 2013-06-28 11:33:09.967163343 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java 2013-06-28 11:33:09.799168572 -0400 @@ -2,52 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** * Class Canonicalizer20010315ExclWithComments - * - * @version $Revision: 1.5 $ */ -public class Canonicalizer20010315ExclWithComments - extends Canonicalizer20010315Excl { - - /** - * Constructor Canonicalizer20010315ExclWithComments - * - */ - public Canonicalizer20010315ExclWithComments() { - super(true); - } - - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; - } +public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl { - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return true; - } + /** + * Constructor Canonicalizer20010315ExclWithComments + * + */ + public Canonicalizer20010315ExclWithComments() { + super(true); + } + + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + } + + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java 2013-06-28 11:33:10.647142177 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java 2013-06-28 11:33:10.483147281 -0400 @@ -2,50 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** - * * @author Christian Geuer-Pollmann */ public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 { - /** - * Constructor Canonicalizer20010315WithXPathOmitComments - * - */ - public Canonicalizer20010315OmitComments() { - super(false); - } - - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; - } - - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return false; - } + /** + * Constructor Canonicalizer20010315WithXPathOmitComments + * + */ + public Canonicalizer20010315OmitComments() { + super(false); + } + + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + } + + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return false; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java 2013-06-28 11:33:11.247123501 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java 2013-06-28 11:33:11.059129353 -0400 @@ -2,47 +2,47 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; /** - * * @author Christian Geuer-Pollmann */ public class Canonicalizer20010315WithComments extends Canonicalizer20010315 { - /** - * Constructor Canonicalizer20010315WithXPathWithComments - * - */ - public Canonicalizer20010315WithComments() { - super(true); - } + /** + * Constructor Canonicalizer20010315WithXPathWithComments + */ + public Canonicalizer20010315WithComments() { + super(true); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return true; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java 2013-06-28 11:33:11.919102584 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java 2013-06-28 11:33:11.683109930 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -33,12 +33,10 @@ import java.util.ListIterator; import java.util.Map; import java.util.Set; -import java.util.SortedSet; -import java.util.Collection; +import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizerSpi; @@ -56,794 +54,829 @@ import org.w3c.dom.ProcessingInstruction; import org.xml.sax.SAXException; - /** * Abstract base class for canonicalization algorithms. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class CanonicalizerBase extends CanonicalizerSpi { - //Constants to be outputed, In char array form, so - //less garbage is generate when outputed. - private static final byte[] _END_PI = {'?','>'}; - private static final byte[] _BEGIN_PI = {'<','?'}; - private static final byte[] _END_COMM = {'-','-','>'}; - private static final byte[] _BEGIN_COMM = {'<','!','-','-'}; - private static final byte[] __XA_ = {'&','#','x','A',';'}; - private static final byte[] __X9_ = {'&','#','x','9',';'}; - private static final byte[] _QUOT_ = {'&','q','u','o','t',';'}; - private static final byte[] __XD_ = {'&','#','x','D',';'}; - private static final byte[] _GT_ = {'&','g','t',';'}; - private static final byte[] _LT_ = {'&','l','t',';'}; - private static final byte[] _END_TAG = {'<','/'}; - private static final byte[] _AMP_ = {'&','a','m','p',';'}; - final static AttrCompare COMPARE=new AttrCompare(); - final static String XML="xml"; - final static String XMLNS="xmlns"; - final static byte[] equalsStr= {'=','\"'}; - static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - //The null xmlns definiton. - protected static final Attr nullNode; - static { - try { - nullNode=DocumentBuilderFactory.newInstance(). - newDocumentBuilder().newDocument().createAttributeNS(Constants.NamespaceSpecNS,XMLNS); - nullNode.setValue(""); - } catch (Exception e) { - throw new RuntimeException("Unable to create nullNode"/*,*/+e); - } - } - - List nodeFilter; - - boolean _includeComments; - Set _xpathNodeSet = null; - /** - * The node to be skiped/excluded from the DOM tree - * in subtree canonicalizations. - */ - Node _excludeNode =null; - OutputStream _writer = new UnsyncByteArrayOutputStream();//null; - - /** - * Constructor CanonicalizerBase - * - * @param includeComments - */ - public CanonicalizerBase(boolean includeComments) { - this._includeComments = includeComments; - } - - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return engineCanonicalizeSubTree(rootNode,(Node)null); - } - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - throws CanonicalizationException { - this._xpathNodeSet = xpathNodeSet; - return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet)); - } - - /** - * Canonicalizes a Subtree node. - * @param input the root of the subtree to canicalize - * @return The canonicalize stream. - * @throws CanonicalizationException - */ - public byte[] engineCanonicalize(XMLSignatureInput input) - throws CanonicalizationException { + public static final String XML = "xml"; + public static final String XMLNS = "xmlns"; + + protected static final AttrCompare COMPARE = new AttrCompare(); + protected static final Attr nullNode; + + private static final byte[] END_PI = {'?','>'}; + private static final byte[] BEGIN_PI = {'<','?'}; + private static final byte[] END_COMM = {'-','-','>'}; + private static final byte[] BEGIN_COMM = {'<','!','-','-'}; + private static final byte[] XA = {'&','#','x','A',';'}; + private static final byte[] X9 = {'&','#','x','9',';'}; + private static final byte[] QUOT = {'&','q','u','o','t',';'}; + private static final byte[] XD = {'&','#','x','D',';'}; + private static final byte[] GT = {'&','g','t',';'}; + private static final byte[] LT = {'&','l','t',';'}; + private static final byte[] END_TAG = {'<','/'}; + private static final byte[] AMP = {'&','a','m','p',';'}; + private static final byte[] equalsStr = {'=','\"'}; + + 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; + + static { + // The null xmlns definition. + try { + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + nullNode = documentBuilder.newDocument().createAttributeNS(Constants.NamespaceSpecNS, XMLNS); + nullNode.setValue(""); + } catch (Exception e) { + throw new RuntimeException("Unable to create nullNode: " + e); + } + } + + private List nodeFilter; + + private boolean includeComments; + private Set xpathNodeSet; + /** + * The node to be skipped/excluded from the DOM tree + * in subtree canonicalizations. + */ + private Node excludeNode; + private OutputStream writer = new ByteArrayOutputStream(); + + /** + * Constructor CanonicalizerBase + * + * @param includeComments + */ + public CanonicalizerBase(boolean includeComments) { + this.includeComments = includeComments; + } + + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, (Node)null); + } + + /** + * Method engineCanonicalizeXPathNodeSet + * @inheritDoc + * @param xpathNodeSet + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException { + this.xpathNodeSet = xpathNodeSet; + return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet)); + } + + /** + * Canonicalizes a Subtree node. + * @param input the root of the subtree to canicalize + * @return The canonicalize stream. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalize(XMLSignatureInput input) throws CanonicalizationException { try { - if (input.isExcludeComments()) - _includeComments = false; - byte[] bytes; - if (input.isOctetStream()) { - return engineCanonicalize(input.getBytes()); - } - if (input.isElement()) { - bytes = engineCanonicalizeSubTree(input.getSubNode(), input - .getExcludeNode()); - return bytes; - } else if (input.isNodeSet()) { - nodeFilter=input.getNodeFilters(); + if (input.isExcludeComments()) { + includeComments = false; + } + if (input.isOctetStream()) { + return engineCanonicalize(input.getBytes()); + } + if (input.isElement()) { + return engineCanonicalizeSubTree(input.getSubNode(), input.getExcludeNode()); + } else if (input.isNodeSet()) { + nodeFilter = input.getNodeFilters(); circumventBugIfNeeded(input); - if (input.getSubNode() != null) { - bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); - } else { - bytes = engineCanonicalizeXPathNodeSet(input.getNodeSet()); - } - return bytes; - - } - return null; - } catch (CanonicalizationException ex) { - throw new CanonicalizationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } catch (SAXException ex) { - throw new CanonicalizationException("empty", ex); - } - } - /** - * @param _writer The _writer to set. - */ - public void setWriter(OutputStream _writer) { - this._writer = _writer; + if (input.getSubNode() != null) { + return engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); + } else { + return engineCanonicalizeXPathNodeSet(input.getNodeSet()); + } + } + return null; + } catch (CanonicalizationException ex) { + throw new CanonicalizationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new CanonicalizationException("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } catch (SAXException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + /** + * @param writer The writer to set. + */ + public void setWriter(OutputStream writer) { + this.writer = writer; } /** - * Canonicalizes a Subtree node. - * - * @param rootNode - * the root of the subtree to canicalize - * @param excludeNode - * a node to be excluded from the canicalize operation - * @return The canonicalize stream. - * @throws CanonicalizationException - */ - byte[] engineCanonicalizeSubTree(Node rootNode,Node excludeNode) - throws CanonicalizationException { - this._excludeNode = excludeNode; + * Canonicalizes a Subtree node. + * + * @param rootNode + * the root of the subtree to canonicalize + * @param excludeNode + * a node to be excluded from the canonicalize operation + * @return The canonicalize stream. + * @throws CanonicalizationException + */ + protected byte[] engineCanonicalizeSubTree(Node rootNode, Node excludeNode) + throws CanonicalizationException { + this.excludeNode = excludeNode; try { - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) { + NameSpaceSymbTable ns = new NameSpaceSymbTable(); + int nodeLevel = NODE_BEFORE_DOCUMENT_ELEMENT; + if (rootNode != null && Node.ELEMENT_NODE == rootNode.getNodeType()) { //Fills the nssymbtable with the definitions of the parent of the root subnode - getParentNameSpaces((Element)rootNode,ns); - nodeLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - this.canonicalizeSubTree(rootNode,ns,rootNode,nodeLevel); - this._writer.close(); - if (this._writer instanceof ByteArrayOutputStream) { - byte []result=((ByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((ByteArrayOutputStream)this._writer).reset(); - } + 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(); - } - return result; - } - return null; - - } catch (UnsupportedEncodingException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } - } - - - /** - * Method canonicalizeSubTree, this function is a recursive one. - * - * @param currentNode - * @param ns - * @param endnode - * @throws CanonicalizationException - * @throws IOException - */ - final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode, - int documentLevel) - throws CanonicalizationException, IOException { - if (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(); + } 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("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + + /** + * Method canonicalizeSubTree, this function is a recursive one. + * + * @param currentNode + * @param ns + * @param endnode + * @throws CanonicalizationException + * @throws IOException + */ + protected final void canonicalizeSubTree( + Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel + ) throws CanonicalizationException, IOException { + if (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()) { + switch (currentNode.getNodeType()) { - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); + case Node.ENTITY_NODE : + case Node.NOTATION_NODE : + case Node.ATTRIBUTE_NODE : + // illegal node type during traversal + throw new CanonicalizationException("empty"); case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - sibling= currentNode.getFirstChild(); - break; - - case Node.COMMENT_NODE : - if (includeComments) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE : - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; - - case Node.TEXT_NODE : - case Node.CDATA_SECTION_NODE : - outputTextToWriter(currentNode.getNodeValue(), writer); - break; - - case Node.ELEMENT_NODE : - documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - if (currentNode==excludeNode) { - break; - } - Element currentElement = (Element) currentNode; - //Add a level to the nssymbtable. So latter can be pop-back. - ns.outputNodePush(); - writer.write('<'); - String name=currentElement.getTagName(); - UtfHelpper.writeByte(name,writer,cache); - - Iterator attrs = this.handleAttributesSubtree(currentElement,ns); - if (attrs!=null) { - //we output all Attrs which are available - while (attrs.hasNext()) { - Attr attr = attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); - } - } - writer.write('>'); - sibling= currentNode.getFirstChild(); - if (sibling==null) { - writer.write(_END_TAG); - UtfHelpper.writeStringToUtf8(name,writer); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - if (parentNode != null) { - sibling= currentNode.getNextSibling(); - } - } else { - parentNode=currentElement; - } - break; - } - while (sibling==null && parentNode!=null) { - writer.write(_END_TAG); - UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - if (parentNode==endnode) - return; - sibling=parentNode.getNextSibling(); - parentNode=parentNode.getParentNode(); - if (parentNode !=null && parentNode.getNodeType() != Node.ELEMENT_NODE) { - documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; - parentNode=null; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); + case Node.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; + + case Node.COMMENT_NODE : + if (includeComments) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); + } + break; + + case Node.PROCESSING_INSTRUCTION_NODE : + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); + break; + + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE : + outputTextToWriter(currentNode.getNodeValue(), writer); + break; + + case Node.ELEMENT_NODE : + documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + if (currentNode == excludeNode) { + break; + } + Element currentElement = (Element)currentNode; + //Add a level to the nssymbtable. So latter can be pop-back. + ns.outputNodePush(); + writer.write('<'); + String name = currentElement.getTagName(); + UtfHelpper.writeByte(name, writer, cache); + + Iterator attrs = this.handleAttributesSubtree(currentElement, ns); + if (attrs != null) { + //we output all Attrs which are available + while (attrs.hasNext()) { + Attr attr = attrs.next(); + outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); + } + } + writer.write('>'); + sibling = currentNode.getFirstChild(); + if (sibling == null) { + writer.write(END_TAG); + UtfHelpper.writeStringToUtf8(name, writer); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + if (parentNode != null) { + sibling = currentNode.getNextSibling(); + } + } else { + parentNode = currentElement; + } + break; + + case Node.DOCUMENT_TYPE_NODE : + default : + break; + } + while (sibling == null && parentNode != null) { + writer.write(END_TAG); + UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + if (parentNode == endnode) { + return; + } + sibling = parentNode.getNextSibling(); + parentNode = parentNode.getParentNode(); + if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) { + documentLevel = NODE_AFTER_DOCUMENT_ELEMENT; + parentNode = null; + } + } + if (sibling == null) { + return; + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); } while(true); } + private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) + 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("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + /** + * Canonicalizes all the nodes included in the currentNode and contained in the + * xpathNodeSet field. + * + * @param currentNode + * @param endnode + * @throws CanonicalizationException + * @throws IOException + */ + protected final void canonicalizeXPathNodeSet(Node currentNode, Node endnode) + throws CanonicalizationException, IOException { + if (isVisibleInt(currentNode) == -1) { + return; + } + boolean currentNodeIsVisible = false; + NameSpaceSymbTable ns = new NameSpaceSymbTable(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + getParentNameSpaces((Element)currentNode, ns); + } + if (currentNode == null) { + return; + } + Node sibling = null; + Node parentNode = null; + OutputStream writer = this.writer; + int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT; + Map cache = new HashMap(); + do { + switch (currentNode.getNodeType()) { + + case Node.ENTITY_NODE : + case Node.NOTATION_NODE : + case Node.ATTRIBUTE_NODE : + // illegal node type during traversal + throw new CanonicalizationException("empty"); + + case Node.DOCUMENT_FRAGMENT_NODE : + case Node.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; + + case Node.COMMENT_NODE : + if (this.includeComments && (isVisibleDO(currentNode, ns.getLevel()) == 1)) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); + } + break; + + case Node.PROCESSING_INSTRUCTION_NODE : + if (isVisible(currentNode)) { + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); + } + break; + + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE : + if (isVisible(currentNode)) { + outputTextToWriter(currentNode.getNodeValue(), writer); + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + outputTextToWriter(nextSibling.getNodeValue(), writer); + currentNode = nextSibling; + sibling = currentNode.getNextSibling(); + } + } + break; - private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) - throws CanonicalizationException { + case Node.ELEMENT_NODE : + documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + Element currentElement = (Element) currentNode; + //Add a level to the nssymbtable. So latter can be pop-back. + String name = null; + int i = isVisibleDO(currentNode, ns.getLevel()); + if (i == -1) { + sibling = currentNode.getNextSibling(); + break; + } + currentNodeIsVisible = (i == 1); + if (currentNodeIsVisible) { + ns.outputNodePush(); + writer.write('<'); + name = currentElement.getTagName(); + UtfHelpper.writeByte(name, writer, cache); + } else { + ns.push(); + } + + Iterator attrs = handleAttributes(currentElement,ns); + if (attrs != null) { + //we output all Attrs which are available + while (attrs.hasNext()) { + Attr attr = attrs.next(); + outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); + } + } + if (currentNodeIsVisible) { + writer.write('>'); + } + sibling = currentNode.getFirstChild(); - try { - this.canonicalizeXPathNodeSet(doc,doc); - this._writer.close(); - if (this._writer instanceof ByteArrayOutputStream) { - byte [] sol=((ByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((ByteArrayOutputStream)this._writer).reset(); + if (sibling == null) { + if (currentNodeIsVisible) { + writer.write(END_TAG); + UtfHelpper.writeByte(name, writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + } else { + ns.pop(); + } + if (parentNode != null) { + sibling = currentNode.getNextSibling(); + } + } else { + parentNode = currentElement; + } + break; + + case Node.DOCUMENT_TYPE_NODE : + default : + break; } - return sol; - } else if (this._writer instanceof UnsyncByteArrayOutputStream) { - byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((UnsyncByteArrayOutputStream)this._writer).reset(); - } - return result; - } - return null; - } catch (UnsupportedEncodingException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } - } - - /** - * Canoicalizes all the nodes included in the currentNode and contained in the - * _xpathNodeSet field. - * - * @param currentNode - * @param endnode - * @throws CanonicalizationException - * @throws IOException - */ - final void canonicalizeXPathNodeSet(Node currentNode,Node endnode ) - throws CanonicalizationException, IOException { - if (isVisibleInt(currentNode)==-1) + while (sibling == null && parentNode != null) { + if (isVisible(parentNode)) { + writer.write(END_TAG); + UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + } else { + ns.pop(); + } + if (parentNode == endnode) { + return; + } + sibling = parentNode.getNextSibling(); + parentNode = parentNode.getParentNode(); + if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) { + parentNode = null; + documentLevel = NODE_AFTER_DOCUMENT_ELEMENT; + } + } + if (sibling == null) { return; - boolean currentNodeIsVisible = false; - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) - getParentNameSpaces((Element)currentNode,ns); - Node sibling=null; - Node parentNode=null; - OutputStream writer=this._writer; - int documentLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - Map cache=new HashMap(); - do { - switch (currentNode.getNodeType()) { - - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); - - case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - //currentNode = currentNode.getFirstChild(); - sibling= currentNode.getFirstChild(); - break; - - case Node.COMMENT_NODE : - if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE : - if (isVisible(currentNode)) - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; - - case Node.TEXT_NODE : - case Node.CDATA_SECTION_NODE : - if (isVisible(currentNode)) { - outputTextToWriter(currentNode.getNodeValue(), writer); - for (Node nextSibling = currentNode.getNextSibling(); - (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) - || (nextSibling.getNodeType() - == Node.CDATA_SECTION_NODE)); - nextSibling = nextSibling.getNextSibling()) { - outputTextToWriter(nextSibling.getNodeValue(), writer); - currentNode=nextSibling; - sibling=currentNode.getNextSibling(); - } - - } - break; - - case Node.ELEMENT_NODE : - documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - Element currentElement = (Element) currentNode; - //Add a level to the nssymbtable. So latter can be pop-back. - String name=null; - int i=isVisibleDO(currentNode,ns.getLevel()); - if (i==-1) { - sibling= currentNode.getNextSibling(); - break; - } - currentNodeIsVisible=(i==1); - if (currentNodeIsVisible) { - ns.outputNodePush(); - writer.write('<'); - name=currentElement.getTagName(); - UtfHelpper.writeByte(name,writer,cache); - } else { - ns.push(); - } - - Iterator attrs = handleAttributes(currentElement,ns); - if (attrs!=null) { - //we output all Attrs which are available - while (attrs.hasNext()) { - Attr attr = attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); - } - } - if (currentNodeIsVisible) { - writer.write('>'); - } - sibling= currentNode.getFirstChild(); - - if (sibling==null) { - if (currentNodeIsVisible) { - writer.write(_END_TAG); - UtfHelpper.writeByte(name,writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - } else { - ns.pop(); - } - if (parentNode != null) { - sibling= currentNode.getNextSibling(); - } - } else { - parentNode=currentElement; - } - break; - } - while (sibling==null && parentNode!=null) { - if (isVisible(parentNode)) { - writer.write(_END_TAG); - UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - } else { - ns.pop(); - } - if (parentNode==endnode) - return; - sibling=parentNode.getNextSibling(); - parentNode=parentNode.getParentNode(); - if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) { - parentNode=null; - documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); } while(true); - } - int isVisibleDO(Node currentNode,int level) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - int i=(it.next()).isNodeIncludeDO(currentNode,level); - if (i!=1) - return i; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return 0; - return 1; - } - int isVisibleInt(Node currentNode) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - int i=(it.next()).isNodeInclude(currentNode); - if (i!=1) - return i; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return 0; - return 1; - } - - boolean isVisible(Node currentNode) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - if ((it.next()).isNodeInclude(currentNode)!=1) - return false; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return false; - return true; - } - - void handleParent(Element e,NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { - return; - } - NamedNodeMap attrs = e.getAttributes(); - int attrsLength = attrs.getLength(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { - //Not a namespace definition, ignore. - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; - } - ns.addMapping(NName,NValue,N); - } - } - - /** - * Adds to ns the definitons from the parent elements of el - * @param el - * @param ns - */ - final void getParentNameSpaces(Element el,NameSpaceSymbTable ns) { - List parents=new ArrayList(10); - Node n1=el.getParentNode(); - if (n1 == null || n1.getNodeType() != Node.ELEMENT_NODE) { - return; - } - //Obtain all the parents of the elemnt - Node parent = n1; - while (parent!=null && parent.getNodeType() == Node.ELEMENT_NODE) { - parents.add((Element)parent); - parent = parent.getParentNode(); - } - //Visit them in reverse order. - ListIterator it=parents.listIterator(parents.size()); - while (it.hasPrevious()) { - Element ele=it.previous(); - handleParent(ele, ns); + } + + protected int isVisibleDO(Node currentNode, int level) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + int i = (it.next()).isNodeIncludeDO(currentNode, level); + if (i != 1) { + return i; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return 0; + } + return 1; + } + + protected int isVisibleInt(Node currentNode) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + int i = (it.next()).isNodeInclude(currentNode); + if (i != 1) { + return i; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return 0; + } + return 1; + } + + protected boolean isVisible(Node currentNode) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + if (it.next().isNodeInclude(currentNode) != 1) { + return false; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return false; + } + return true; + } + + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { + return; + } + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); + + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI()) + && (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue))) { + ns.addMapping(NName, NValue, attribute); + } + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = XMLNS; + Name = XMLNS; + } else { + Name = XMLNS + ":" + NName; + } + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); } + } + + /** + * Adds to ns the definitions from the parent elements of el + * @param el + * @param ns + */ + protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) { + Node n1 = el.getParentNode(); + if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) { + return; + } + //Obtain all the parents of the element + List parents = new ArrayList(); + Node parent = n1; + while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) { + parents.add((Element)parent); + parent = parent.getParentNode(); + } + //Visit them in reverse order. + ListIterator it = parents.listIterator(parents.size()); + while (it.hasPrevious()) { + Element ele = it.previous(); + handleParent(ele, ns); + } + parents.clear(); Attr nsprefix; - if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null) - && "".equals(nsprefix.getValue())) { - ns.addMappingAndRender("xmlns","",nullNode); - } - } - /** - * Obtain the attributes to output for this node in XPathNodeSet c14n. - * - * @param E - * @param ns - * @return the attributes nodes to output. - * @throws CanonicalizationException - */ - abstract Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException; - - /** - * Obtain the attributes to output for this node in a Subtree c14n. - * - * @param E - * @param ns - * @return the attributes nodes to output. - * @throws CanonicalizationException - */ - abstract Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException; - - abstract void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; - - /** - * Outputs an Attribute to the internal Writer. - * - * The string value of the node is modified by replacing - *
        - *
      • all ampersands (&) with &amp;
      • - *
      • all open angle brackets (<) with &lt;
      • - *
      • all quotation mark characters with &quot;
      • - *
      • and the whitespace characters #x9, #xA, and #xD, with character - * references. The character references are written in uppercase - * hexadecimal with no leading zeroes (for example, #xD is represented - * by the character reference &#xD;)
      • - *
      - * - * @param name - * @param value - * @param writer - * @throws IOException - */ - static final void outputAttrToWriter(final String name, final String value, final OutputStream writer, - final Map cache) throws IOException { - writer.write(' '); - UtfHelpper.writeByte(name,writer,cache); - writer.write(equalsStr); - byte []toWrite; - final int length = value.length(); - int i=0; - while (i < length) { - char c = value.charAt(i++); + if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null) + && "".equals(nsprefix.getValue())) { + ns.addMappingAndRender(XMLNS, "", nullNode); + } + } + + /** + * Obtain the attributes to output for this node in XPathNodeSet c14n. + * + * @param element + * @param ns + * @return the attributes nodes to output. + * @throws CanonicalizationException + */ + abstract Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException; - switch (c) { + /** + * Obtain the attributes to output for this node in a Subtree c14n. + * + * @param element + * @param ns + * @return the attributes nodes to output. + * @throws CanonicalizationException + */ + abstract Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException; - case '&' : - toWrite=_AMP_; - break; + abstract void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; - case '<' : - toWrite=_LT_; - break; + /** + * Outputs an Attribute to the internal Writer. + * + * The string value of the node is modified by replacing + *
        + *
      • all ampersands (&) with &amp;
      • + *
      • all open angle brackets (<) with &lt;
      • + *
      • all quotation mark characters with &quot;
      • + *
      • and the whitespace characters #x9, #xA, and #xD, with character + * references. The character references are written in uppercase + * hexadecimal with no leading zeroes (for example, #xD is represented + * by the character reference &#xD;)
      • + *
      + * + * @param name + * @param value + * @param writer + * @throws IOException + */ + protected static final void outputAttrToWriter( + final String name, final String value, + final OutputStream writer, final Map cache + ) throws IOException { + writer.write(' '); + UtfHelpper.writeByte(name, writer, cache); + writer.write(equalsStr); + byte[] toWrite; + final int length = value.length(); + int i = 0; + while (i < length) { + char c = value.charAt(i++); + + switch (c) { + + case '&' : + toWrite = AMP; + break; + + case '<' : + toWrite = LT; + break; + + case '"' : + toWrite = QUOT; + break; + + case 0x09 : // '\t' + toWrite = X9; + break; + + case 0x0A : // '\n' + toWrite = XA; + break; + + case 0x0D : // '\r' + toWrite = XD; + break; + + default : + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + continue; + } + writer.write(toWrite); + } - case '"' : - toWrite=_QUOT_; - break; + writer.write('\"'); + } - case 0x09 : // '\t' - toWrite=__X9_; - break; + /** + * Outputs a PI to the internal Writer. + * + * @param currentPI + * @param writer where to write the things + * @throws IOException + */ + protected void outputPItoWriter( + ProcessingInstruction currentPI, OutputStream writer, int position + ) throws IOException { + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(BEGIN_PI); - case 0x0A : // '\n' - toWrite=__XA_; - break; + final String target = currentPI.getTarget(); + int length = target.length(); - case 0x0D : // '\r' - toWrite=__XD_; - break; + for (int i = 0; i < length; i++) { + char c = target.charAt(i); + if (c == 0x0D) { + writer.write(XD); + } else { + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + } + } - default : - if (c < 0x80 ) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - continue; - } - writer.write(toWrite); - } - - writer.write('\"'); - } - - /** - * Outputs a PI to the internal Writer. - * - * @param currentPI - * @param writer where to write the things - * @throws IOException - */ - static final void outputPItoWriter(ProcessingInstruction currentPI, OutputStream writer,int position) throws IOException { - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - writer.write(_BEGIN_PI); - - final String target = currentPI.getTarget(); - int length = target.length(); - - for (int i = 0; i < length; i++) { - char c=target.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - if (c < 0x80) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - } - } - - final String data = currentPI.getData(); - - length = data.length(); - - if (length > 0) { - writer.write(' '); - - for (int i = 0; i < length; i++) { - char c=data.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - } - } - } + final String data = currentPI.getData(); - writer.write(_END_PI); - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - } - - /** - * Method outputCommentToWriter - * - * @param currentComment - * @param writer writer where to write the things - * @throws IOException - */ - static final void outputCommentToWriter(Comment currentComment, OutputStream writer,int position) throws IOException { - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - writer.write(_BEGIN_COMM); - - final String data = currentComment.getData(); - final int length = data.length(); - - for (int i = 0; i < length; i++) { - char c=data.charAt(i); - if (c==0x0D) { - writer.write(__XD_); - } else { - if (c < 0x80) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - } - } - - writer.write(_END_COMM); - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - writer.write('\n'); - } - } - - /** - * Outputs a Text of CDATA section to the internal Writer. - * - * @param text - * @param writer writer where to write the things - * @throws IOException - */ - static final void outputTextToWriter(final String text, final OutputStream writer) throws IOException { - final int length = text.length(); - byte []toWrite; - for (int i = 0; i < length; i++) { - char c = text.charAt(i); + length = data.length(); - switch (c) { + if (length > 0) { + writer.write(' '); - case '&' : - toWrite=_AMP_; - break; + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + if (c == 0x0D) { + writer.write(XD); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + } + } - case '<' : - toWrite=_LT_; - break; + writer.write(END_PI); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + } - case '>' : - toWrite=_GT_; - break; + /** + * Method outputCommentToWriter + * + * @param currentComment + * @param writer writer where to write the things + * @throws IOException + */ + protected void outputCommentToWriter( + Comment currentComment, OutputStream writer, int position + ) throws IOException { + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(BEGIN_COMM); - case 0xD : - toWrite=__XD_; - break; + final String data = currentComment.getData(); + final int length = data.length(); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + if (c == 0x0D) { + writer.write(XD); + } else { + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + } + } - default : - if (c < 0x80) { - writer.write(c); - } else { - UtfHelpper.writeCharToUtf8(c,writer); - }; - continue; - } - writer.write(toWrite); - } - } - - @SuppressWarnings("unchecked") - protected Collection getSortedSetAsCollection(SortedSet result) { - return (Collection)(Collection)result; + writer.write(END_COMM); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); + } } + /** + * Outputs a Text of CDATA section to the internal Writer. + * + * @param text + * @param writer writer where to write the things + * @throws IOException + */ + protected static final void outputTextToWriter( + final String text, final OutputStream writer + ) throws IOException { + final int length = text.length(); + byte[] toWrite; + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&' : + toWrite = AMP; + break; + + case '<' : + toWrite = LT; + break; + + case '>' : + toWrite = GT; + break; + + case 0xD : + toWrite = XD; + break; + + default : + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + continue; + } + writer.write(toWrite); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java 2013-06-28 11:33:12.615080920 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java 2013-06-28 11:33:12.447086149 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -29,191 +31,185 @@ import org.w3c.dom.Attr; import org.w3c.dom.Node; - - /** - * A stack based Symble Table. + * A stack based Symbol Table. *
      For speed reasons all the symbols are introduced in the same map, * and at the same time in a list so it can be removed when the frame is pop back. * @author Raul Benito - **/ + */ public class NameSpaceSymbTable { - /**The map betwen prefix-> entry table. */ - SymbMap symb; - /**The level of nameSpaces (for Inclusive visibility).*/ - int nameSpaces=0; - /**The stacks for removing the definitions when doing pop.*/ - List level; - boolean cloned=true; - static final String XMLNS="xmlns"; - final static SymbMap initialMap=new SymbMap(); - static { - NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true,XMLNS); - ne.lastrendered=""; - initialMap.put(XMLNS,ne); - } + private static final String XMLNS = "xmlns"; + private static final SymbMap initialMap = new SymbMap(); + + static { + NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS); + ne.lastrendered = ""; + initialMap.put(XMLNS, ne); + } + + /**The map betwen prefix-> entry table. */ + private SymbMap symb; + + /**The stacks for removing the definitions when doing pop.*/ + private List level; + private boolean cloned = true; + /** * Default constractor - **/ - public NameSpaceSymbTable() { - level = new ArrayList(10); - //Insert the default binding for xmlns. - symb=(SymbMap) initialMap.clone(); + **/ + public NameSpaceSymbTable() { + level = new ArrayList(); + //Insert the default binding for xmlns. + symb = (SymbMap) initialMap.clone(); } /** - * Get all the unrendered nodes in the name space. - * For Inclusive rendering + * Get all the unrendered nodes in the name space. + * For Inclusive rendering * @param result the list where to fill the unrendered xmlns definitions. - **/ - public void getUnrenderedNodes(Collection result) { - //List result=new ArrayList(); - Iterator it=symb.entrySet().iterator(); - while (it.hasNext()) { - NameSpaceSymbEntry n= it.next(); - //put them rendered? - if ((!n.rendered) && (n.n!=null)) { - n=(NameSpaceSymbEntry) n.clone(); + **/ + public void getUnrenderedNodes(Collection result) { + Iterator it = symb.entrySet().iterator(); + while (it.hasNext()) { + NameSpaceSymbEntry n = it.next(); + //put them rendered? + if ((!n.rendered) && (n.n != null)) { + n = (NameSpaceSymbEntry) n.clone(); needsClone(); - symb.put(n.prefix,n); - n.lastrendered=n.uri; - n.rendered=true; + symb.put(n.prefix, n); + n.lastrendered = n.uri; + n.rendered = true; - result.add(n.n); - - } - } - } + result.add(n.n); + } + } + } - /** - * Push a frame for visible namespace. + /** + * Push a frame for visible namespace. * For Inclusive rendering. **/ - public void outputNodePush() { - nameSpaces++; - push(); - } + public void outputNodePush() { + push(); + } - /** + /** * Pop a frame for visible namespace. **/ - public void outputNodePop() { - nameSpaces--; - pop(); - } + public void outputNodePop() { + pop(); + } - /** + /** * Push a frame for a node. * Inclusive or Exclusive. **/ - public void push() { - //Put the number of namespace definitions in the stack. + public void push() { + //Put the number of namespace definitions in the stack. level.add(null); - cloned=false; - } + cloned = false; + } - /** + /** * Pop a frame. * Inclusive or Exclusive. **/ - public void pop() { - int size=level.size()-1; - Object ob= level.remove(size); - if (ob!=null) { - symb=(SymbMap)ob; - if (size==0) { - cloned=false; - } else - cloned=(level.get(size-1)!=symb); + public void pop() { + int size = level.size() - 1; + Object ob = level.remove(size); + if (ob != null) { + symb = (SymbMap)ob; + if (size == 0) { + cloned = false; + } else { + cloned = (level.get(size - 1) != symb); + } } else { - cloned=false; - } - - + cloned = false; } + } - final void needsClone() { - if (!cloned) { - level.set(level.size()-1,symb); - symb=(SymbMap) symb.clone(); - cloned=true; + final void needsClone() { + if (!cloned) { + level.set(level.size() - 1, symb); + symb = (SymbMap) symb.clone(); + cloned = true; } } - /** - * Gets the attribute node that defines the binding for the prefix. + /** + * Gets the attribute node that defines the binding for the prefix. * @param prefix the prefix to obtain the attribute. * @return null if there is no need to render the prefix. Otherwise the node of * definition. **/ - public Attr getMapping(String prefix) { - NameSpaceSymbEntry entry=symb.get(prefix); - if (entry==null) { - //There is no definition for the prefix(a bug?). - return null; - } - if (entry.rendered) { - //No need to render an entry already rendered. - return null; - } - // Mark this entry as render. - entry=(NameSpaceSymbEntry) entry.clone(); - needsClone(); - symb.put(prefix,entry); - entry.rendered=true; - entry.level=nameSpaces; - entry.lastrendered=entry.uri; - // Return the node for outputing. - return entry.n; + public Attr getMapping(String prefix) { + NameSpaceSymbEntry entry = symb.get(prefix); + if (entry == null) { + //There is no definition for the prefix(a bug?). + return null; } + if (entry.rendered) { + //No need to render an entry already rendered. + return null; + } + // Mark this entry as render. + entry = (NameSpaceSymbEntry) entry.clone(); + needsClone(); + symb.put(prefix, entry); + entry.rendered = true; + entry.lastrendered = entry.uri; + // Return the node for outputing. + return entry.n; + } - /** - * Gets a definition without mark it as render. + /** + * Gets a definition without mark it as render. * For render in exclusive c14n the namespaces in the include prefixes. * @param prefix The prefix whose definition is neaded. * @return the attr to render, null if there is no need to render **/ - public Attr getMappingWithoutRendered(String prefix) { - NameSpaceSymbEntry entry= symb.get(prefix); - if (entry==null) { - return null; - } - if (entry.rendered) { - return null; - } - return entry.n; + public Attr getMappingWithoutRendered(String prefix) { + NameSpaceSymbEntry entry = symb.get(prefix); + if (entry == null) { + return null; + } + if (entry.rendered) { + return null; } + return entry.n; + } - /** + /** * Adds the mapping for a prefix. * @param prefix the prefix of definition * @param uri the Uri of the definition * @param n the attribute that have the definition * @return true if there is already defined. **/ - public boolean addMapping(String prefix, String uri,Attr n) { - NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob!=null) && uri.equals(ob.uri)) { - //If we have it previously defined. Don't keep working. - return false; - } - //Creates and entry in the table for this new definition. - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix); + public boolean addMapping(String prefix, String uri, Attr n) { + NameSpaceSymbEntry ob = symb.get(prefix); + if ((ob != null) && uri.equals(ob.uri)) { + //If we have it previously defined. Don't keep working. + return false; + } + //Creates and entry in the table for this new definition. + NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix); needsClone(); - symb.put(prefix, ne); - if (ob != null) { - //We have a previous definition store it for the pop. - //Check if a previous definition(not the inmidiatly one) has been rendered. - ne.lastrendered=ob.lastrendered; - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - //Yes it is. Mark as rendered. - ne.rendered=true; - } - } + symb.put(prefix, ne); + if (ob != null) { + //We have a previous definition store it for the pop. + //Check if a previous definition(not the inmidiatly one) has been rendered. + ne.lastrendered = ob.lastrendered; + if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { + //Yes it is. Mark as rendered. + ne.rendered = true; + } + } return true; - } + } /** * Adds a definition and mark it as render. @@ -223,147 +219,148 @@ * @param n the attribute that have the definition * @return the attr to render, null if there is no need to render **/ - public Node addMappingAndRender(String prefix, String uri,Attr n) { + public Node addMappingAndRender(String prefix, String uri, Attr n) { NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob!=null) && uri.equals(ob.uri)) { - if (!ob.rendered) { - ob=(NameSpaceSymbEntry) ob.clone(); + if ((ob != null) && uri.equals(ob.uri)) { + if (!ob.rendered) { + ob = (NameSpaceSymbEntry) ob.clone(); needsClone(); - symb.put(prefix,ob); - ob.lastrendered=uri; - ob.rendered=true; + symb.put(prefix, ob); + ob.lastrendered = uri; + ob.rendered = true; return ob.n; - } + } return null; - } + } - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix); - ne.lastrendered=uri; + NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri,n,true,prefix); + ne.lastrendered = uri; needsClone(); symb.put(prefix, ne); - if (ob != null) { - - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - ne.rendered=true; - return null; - } + if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { + ne.rendered = true; + return null; } return ne.n; } - public int getLevel() { - // TODO Auto-generated method stub - return level.size(); - } + public int getLevel() { + return level.size(); + } - public void removeMapping(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public void removeMapping(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null) { + if (ob != null) { needsClone(); - symb.put(prefix,null); - } + symb.put(prefix, null); } + } - public void removeMappingIfNotRender(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public void removeMappingIfNotRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null && !ob.rendered) { + if (ob != null && !ob.rendered) { needsClone(); - symb.put(prefix,null); - } + symb.put(prefix, null); } + } - public boolean removeMappingIfRender(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public boolean removeMappingIfRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null && ob.rendered) { + if (ob != null && ob.rendered) { needsClone(); - symb.put(prefix,null); + symb.put(prefix, null); } return false; - } + } } /** * The internal structure of NameSpaceSymbTable. **/ class NameSpaceSymbEntry implements Cloneable { - NameSpaceSymbEntry(String name,Attr n,boolean rendered,String prefix) { - this.uri=name; - this.rendered=rendered; - this.n=n; - this.prefix=prefix; + + String prefix; + + /**The URI that the prefix defines */ + String uri; + + /**The last output in the URI for this prefix (This for speed reason).*/ + String lastrendered = null; + + /**This prefix-URI has been already render or not.*/ + boolean rendered = false; + + /**The attribute to include.*/ + Attr n; + + NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) { + this.uri = name; + this.rendered = rendered; + this.n = n; + this.prefix = prefix; } + /** @inheritDoc */ - public Object clone() { + public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } - /** The level where the definition was rendered(Only for inclusive) */ - int level=0; - String prefix; - /**The URI that the prefix defines */ - String uri; - /**The last output in the URI for this prefix (This for speed reason).*/ - String lastrendered=null; - /**This prefix-URI has been already render or not.*/ - boolean rendered=false; - /**The attribute to include.*/ - Attr n; }; class SymbMap implements Cloneable { - int free=23; + int free = 23; NameSpaceSymbEntry[] entries; String[] keys; - SymbMap() { - entries=new NameSpaceSymbEntry[free]; - keys=new String[free]; - } - void put(String key, NameSpaceSymbEntry value) { + + SymbMap() { + entries = new NameSpaceSymbEntry[free]; + keys = new String[free]; + } + + void put(String key, NameSpaceSymbEntry value) { int index = index(key); Object oldKey = keys[index]; keys[index] = key; entries[index] = value; - if (oldKey==null || !oldKey.equals(key)) { - if (--free == 0) { - free=entries.length; - int newCapacity = free<<2; - rehash(newCapacity); - } + if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) { + free = entries.length; + int newCapacity = free << 2; + rehash(newCapacity); } } List entrySet() { - List a=new ArrayList(); - for (int i=0;i a = new ArrayList(); + for (int i = 0;i < entries.length;i++) { + if ((entries[i] != null) && !("".equals(entries[i].uri))) { + a.add(entries[i]); } } - return a; + return a; } - protected int index(Object obj) { + protected int index(Object obj) { Object[] set = keys; int length = set.length; //abs of index - int index = (obj.hashCode() & 0x7fffffff) % length; + int index = (obj.hashCode() & 0x7fffffff) % length; Object cur = set[index]; - if (cur == null || (cur.equals( obj))) { - return index; + if (cur == null || (cur.equals(obj))) { + return index; } - length=length-1; + length--; do { - index=index==length? 0:++index; - cur = set[index]; - } while (cur != null && (!cur.equals(obj))); + index = index == length ? 0 : ++index; + cur = set[index]; + } while (cur != null && (!cur.equals(obj))); return index; } @@ -377,11 +374,11 @@ String oldKeys[] = keys; NameSpaceSymbEntry oldVals[] = entries; - keys = new String[newCapacity]; + keys = new String[newCapacity]; entries = new NameSpaceSymbEntry[newCapacity]; for (int i = oldCapacity; i-- > 0;) { - if(oldKeys[i] != null) { + if (oldKeys[i] != null) { String o = oldKeys[i]; int index = index(o); keys[index] = o; @@ -391,20 +388,19 @@ } NameSpaceSymbEntry get(String key) { - return entries[index(key)]; + 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); + 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; + return copy; } catch (CloneNotSupportedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } return null; --- old/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java 2013-06-28 11:33:13.279060252 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java 2013-06-28 11:33:13.111065481 -0400 @@ -1,3 +1,25 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.c14n.implementations; import java.io.IOException; @@ -6,150 +28,153 @@ public class UtfHelpper { - final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException { - byte []result= cache.get(str); - if (result==null) { - result=getStringInUtf8(str); - cache.put(str,result); - } - - out.write(result); + static final void writeByte( + final String str, + final OutputStream out, + Map cache + ) throws IOException { + byte[] result = cache.get(str); + if (result == null) { + result = getStringInUtf8(str); + cache.put(str, result); + } - } + out.write(result); + } - final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ - if (c < 0x80) { + static final 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)); + + } + + static final void writeStringToUtf8( + final String str, + final OutputStream out + ) throws IOException{ + final int length = str.length(); + int i = 0; + char c; + while (i < length) { + c = str.charAt(i++); + if (c < 0x80) { out.write(c); - return; + continue; } - if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { //No Surrogates in sun java out.write(0x3f); - return; - } + continue; + } + char ch; int bias; int write; - char ch; if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } + ch = (char)(c>>>12); + write = 0xE0; + if (ch > 0) { + write |= (ch & 0x0F); + } out.write(write); - write=0x80; - bias=0x3F; + write = 0x80; + bias = 0x3F; } else { - write=0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); + write = 0xC0; + bias = 0x1F; } + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); + } out.write(write); - out.write(0x80 | ((c) & 0x3F)); - - } - - final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ - final int length=str.length(); - int i=0; - char c; - while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ - //No Surrogates in sun java - out.write(0x3f); - continue; - } - char ch; - int bias; - int write; - 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 final static byte[] getStringInUtf8(final String str) { - final int length=str.length(); - boolean expanded=false; - byte []result=new byte[length]; - int i=0; - int out=0; - char c; - while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ - //No Surrogates in sun java - result[out++]=0x3f; - - continue; - } - if (!expanded) { - byte newResult[]=new byte[3*length]; - System.arraycopy(result, 0, newResult, 0, out); - result=newResult; - expanded=true; - } - char ch; - int bias; - byte write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=(byte)0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - result[out++]=write; - write=(byte)0x80; - bias=0x3F; - } else { - write=(byte)0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - result[out++]=write; - result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/ - - } - if (expanded) { - byte newResult[]=new byte[out]; - System.arraycopy(result, 0, newResult, 0, out); - result=newResult; - } - return result; - } + out.write(0x80 | ((c) & 0x3F)); + } + } + + public static final byte[] getStringInUtf8(final String str) { + final int length = str.length(); + boolean expanded = false; + byte[] result = new byte[length]; + int i = 0; + int out = 0; + char c; + while (i < length) { + c = str.charAt(i++); + if (c < 0x80) { + result[out++] = (byte)c; + continue; + } + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { + //No Surrogates in sun java + result[out++] = 0x3f; + continue; + } + if (!expanded) { + byte newResult[] = new byte[3*length]; + System.arraycopy(result, 0, newResult, 0, out); + result = newResult; + expanded = true; + } + char ch; + int bias; + byte write; + if (c > 0x07FF) { + ch = (char)(c>>>12); + write = (byte)0xE0; + if (ch > 0) { + write |= (ch & 0x0F); + } + result[out++] = write; + write = (byte)0x80; + bias = 0x3F; + } else { + write = (byte)0xC0; + bias = 0x1F; + } + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); + } + result[out++] = write; + result[out++] = (byte)(0x80 | ((c) & 0x3F)); + } + if (expanded) { + byte newResult[] = new byte[out]; + System.arraycopy(result, 0, newResult, 0, out); + result = newResult; + } + return result; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java 2013-06-28 11:33:13.931039958 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java 2013-06-28 11:33:13.759045311 -0400 @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.util.Iterator; import com.sun.org.apache.xml.internal.security.keys.KeyInfo; import org.w3c.dom.Element; - /** * A Key Agreement algorithm provides for the derivation of a shared secret key * based on a shared secret computed from certain types of compatible public @@ -79,9 +79,10 @@ * @author Axl Mattheus */ public interface AgreementMethod { + /** - * Returns an byte array. - * @return + * Returns a byte array. + * @return a byte array. */ byte[] getKANonce(); @@ -92,8 +93,8 @@ void setKANonce(byte[] kanonce); /** - * Returns aditional information regarding the AgreementMethod. - * @return + * Returns additional information regarding the AgreementMethod. + * @return additional information regarding the AgreementMethod. */ Iterator getAgreementMethodInformation(); @@ -134,7 +135,7 @@ void setOriginatorKeyInfo(KeyInfo keyInfo); /** - * Retruns information relating to the recipient's shared secret. + * Returns information relating to the recipient's shared secret. * * @return information relating to the recipient's shared secret. */ --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java 2013-06-28 11:33:14.543020908 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java 2013-06-28 11:33:14.379026013 -0400 @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - /** * CipherData provides encrypted data. It must either contain the * encrypted octet sequence as base64 encoded text of the @@ -42,10 +43,12 @@ * @author Axl Mattheus */ public interface CipherData { + /** VALUE_TYPE ASN */ - public static final int VALUE_TYPE = 0x00000001; + int VALUE_TYPE = 0x00000001; + /** REFERENCE_TYPE ASN */ - public static final int REFERENCE_TYPE = 0x00000002; + int REFERENCE_TYPE = 0x00000002; /** * Returns the type of encrypted data contained in the @@ -76,18 +79,17 @@ * Returns a reference to an external location containing the encrypted * octet sequence (byte array). * - * @return the reference to an external location containing the enctrypted - * octet sequence. + * @return the reference to an external location containing the encrypted + * octet sequence. */ CipherReference getCipherReference(); /** * Sets the CipherData's reference. * - * @param reference an external location containing the enctrypted octet - * sequence. + * @param reference an external location containing the encrypted octet sequence. * @throws XMLEncryptionException */ - void setCipherReference(CipherReference reference) throws - XMLEncryptionException; + void setCipherReference(CipherReference reference) throws XMLEncryptionException; } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java 2013-06-28 11:33:15.218999866 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java 2013-06-28 11:33:15.047005220 -0400 @@ -2,34 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; import org.w3c.dom.Attr; - /** * CipherReference identifies a source which, when processed, * yields the encrypted octet sequence. *

      * The actual value is obtained as follows. The CipherReference URI * contains an identifier that is dereferenced. Should the - * CipherReference element contain an OPTIONAL sequence of * Transforms, the data resulting from dereferencing the URI is * transformed as specified so as to yield the intended cipher value. For * example, if the value is base64 encoded within an XML document; the @@ -62,20 +62,21 @@ /** * Returns an URI that contains an identifier that should be * dereferenced. - * @return + * @return an URI that contains an identifier that should be + * dereferenced. */ String getURI(); - /** - * Gets the URI as an Attribute node. Used to meld the CipherREference - * with the XMLSignature ResourceResolvers - * @return - */ - public Attr getURIAsAttr(); + /** + * Gets the URI as an Attribute node. Used to meld the CipherReference + * with the XMLSignature ResourceResolvers + * @return the URI as an Attribute node + */ + Attr getURIAsAttr(); /** * Returns the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @return the transform that specifies how to transform the reference to * yield the intended cipher value. @@ -84,10 +85,11 @@ /** * Sets the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @param transforms the set of Transforms that specifies how * to transform the reference to yield the intended cipher value. */ void setTransforms(Transforms transforms); } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java 2013-06-28 11:33:15.890978950 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java 2013-06-28 11:33:15.726984054 -0400 @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - /** * CipherValue is the wrapper for cipher text. * @@ -28,20 +29,18 @@ */ public interface CipherValue { /** - * Resturns the Base 64 encoded, encrypted octets that is the - * CihperValue. + * Returns the Base 64 encoded, encrypted octets that is the + * CipherValue. * * @return cipher value. */ - String getValue(); - // byte[] getValue(); + String getValue(); /** * Sets the Base 64 encoded, encrypted octets that is the - * CihperValue. + * CipherValue. * * @param value the cipher value. */ - void setValue(String value); - // void setValue(byte[] value); + void setValue(String value); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java 2013-06-28 11:33:16.554958281 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java 2013-06-28 11:33:16.390963386 -0400 @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - /** * The EncryptedData element is the core element in the syntax. Not * only does its CipherData child contain the encrypted data, but @@ -42,3 +43,4 @@ */ public interface EncryptedData extends EncryptedType { } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java 2013-06-28 11:33:17.222937489 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java 2013-06-28 11:33:17.030943465 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - - /** * The EncryptedKey element is used to transport encryption keys * from the originator to a known recipient(s). It may be used as a stand-alone @@ -51,9 +51,9 @@ * @author Axl Mattheus */ public interface EncryptedKey extends EncryptedType { + /** - * Returns a hint as to which recipient this encrypted key value is intended - * for. + * Returns a hint as to which recipient this encrypted key value is intended for. * * @return the recipient of the EncryptedKey. */ @@ -110,3 +110,4 @@ */ void setCarriedName(String name); } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java 2013-06-28 11:33:17.898916447 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java 2013-06-28 11:33:17.726921801 -0400 @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import com.sun.org.apache.xml.internal.security.keys.KeyInfo; - /** * EncryptedType is the abstract type from which EncryptedData and * EncryptedKey are derived. While these two latter element types @@ -50,6 +50,7 @@ * @author Axl Mattheus */ public interface EncryptedType { + /** * Returns a String providing for the standard method of * assigning an id to the element within the document context. @@ -61,7 +62,7 @@ /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -117,7 +118,7 @@ void setMimeType(String type); /** - * Retusn an URI representing the encoding of the + * Return an URI representing the encoding of the * EncryptedType. * * @return the encoding of this EncryptedType. @@ -128,7 +129,7 @@ * Sets the URI representing the encoding of the * EncryptedType. * - * @param encoding. + * @param encoding */ void setEncoding(String encoding); @@ -189,7 +190,8 @@ * Sets the EncryptionProperties that supplies additional * information about the generation of the EncryptedType. * - * @param properties. + * @param properties */ void setEncryptionProperties(EncryptionProperties properties); } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java 2013-06-28 11:33:18.590894908 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java 2013-06-28 11:33:18.422900137 -0400 @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.util.Iterator; import org.w3c.dom.Element; - /** * EncryptionMethod describes the encryption algorithm applied to * the cipher data. If the element is absent, the encryption algorithm must be @@ -81,6 +81,30 @@ * @param parameters the OAEP parameters. */ void setOAEPparams(byte[] parameters); + + /** + * Set the Digest Algorithm to use + * @param digestAlgorithm the Digest Algorithm to use + */ + void setDigestAlgorithm(String digestAlgorithm); + + /** + * Get the Digest Algorithm to use + * @return the Digest Algorithm to use + */ + String getDigestAlgorithm(); + + /** + * Set the MGF Algorithm to use + * @param mgfAlgorithm the MGF Algorithm to use + */ + void setMGFAlgorithm(String mgfAlgorithm); + + /** + * Get the MGF Algorithm to use + * @return the MGF Algorithm to use + */ + String getMGFAlgorithm(); /** * Returns an iterator over all the additional elements contained in the @@ -106,3 +130,4 @@ */ void removeEncryptionMethodInformation(Element information); } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java 2013-06-28 11:33:19.250874364 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java 2013-06-28 11:33:19.082879593 -0400 @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.util.Iterator; - /** * EncryptionProperties can hold additional information concerning * the generation of the EncryptedData or @@ -46,6 +46,7 @@ * @author Axl Mattheus */ public interface EncryptionProperties { + /** * Returns the EncryptionProperties' id. * @@ -72,14 +73,15 @@ /** * Adds an EncryptionProperty. * - * @param property. + * @param property */ void addEncryptionProperty(EncryptionProperty property); /** * Removes the specified EncryptionProperty. * - * @param property. + * @param property */ void removeEncryptionProperty(EncryptionProperty property); } + --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java 2013-06-28 11:33:19.930853198 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java 2013-06-28 11:33:19.750858801 -0400 @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.util.Iterator; import org.w3c.dom.Element; @@ -50,6 +51,7 @@ * @author Axl Mattheus */ public interface EncryptionProperty { + /** * Returns the EncryptedType being described. * @@ -61,7 +63,7 @@ /** * Sets the target. * - * @param target. + * @param target */ void setTarget(String target); @@ -75,7 +77,7 @@ /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -98,7 +100,7 @@ /** * Returns the properties of the EncryptionProperty. * - * @return an Iterator over all the addiitonal encryption + * @return an Iterator over all the additional encryption * information contained in this class. */ Iterator getEncryptionInformation(); --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java 2013-06-28 11:33:20.610832032 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java 2013-06-28 11:33:20.434837511 -0400 @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.util.Iterator; import org.w3c.dom.Element; - /** * A wrapper for a pointer from a key value of an EncryptedKey to * items encrypted by that key value (EncryptedData or @@ -45,6 +45,13 @@ */ public interface Reference { /** + * Returns the Element tag name for this Reference. + * + * @return the tag name of this Reference. + */ + String getType(); + + /** * Returns a URI that points to an Element that * were encrypted using the key defined in the enclosing * EncryptedKey element. @@ -79,14 +86,14 @@ /** * Adds retrieval information. * - * @param info. + * @param info */ void addElementRetrievalInformation(Element info); /** * Removes the specified retrieval information. * - * @param info. + * @param info */ void removeElementRetrievalInformation(Element info); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java 2013-06-28 11:33:21.270811489 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java 2013-06-28 11:33:21.102816718 -0400 @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.util.Iterator; - /** * ReferenceList is an element that contains pointers from a key * value of an EncryptedKey to items encrypted by that key value @@ -45,10 +45,12 @@ * @see Reference */ public interface ReferenceList { - /** DATA TAG */ - public static final int DATA_REFERENCE = 0x00000001; + + /** DATA TAG */ + int DATA_REFERENCE = 0x00000001; + /** KEY TAG */ - public static final int KEY_REFERENCE = 0x00000002; + int KEY_REFERENCE = 0x00000002; /** * Adds a reference to this reference list. @@ -57,21 +59,21 @@ * @throws IllegalAccessException if the Reference is not an * instance of DataReference or KeyReference. */ - public void add(Reference reference); + void add(Reference reference); /** * Removes a reference from the ReferenceList. * * @param reference the reference to remove. */ - public void remove(Reference reference); + void remove(Reference reference); /** * Returns the size of the ReferenceList. * * @return the size of the ReferenceList. */ - public int size(); + int size(); /** * Indicates if the ReferenceList is empty. @@ -79,29 +81,29 @@ * @return true if the ReferenceList is * empty, else false. */ - public boolean isEmpty(); + boolean isEmpty(); /** * Returns an Iterator over all the References - * contatined in this ReferenceList. + * contained in this ReferenceList. * * @return Iterator. */ - public Iterator getReferences(); + Iterator getReferences(); /** * DataReference factory method. Returns a * DataReference. * @param uri - * @return + * @return a DataReference. */ - public Reference newDataReference(String uri); + Reference newDataReference(String uri); /** * KeyReference factory method. Returns a * KeyReference. * @param uri - * @return + * @return a KeyReference. */ - public Reference newKeyReference(String uri); + Reference newKeyReference(String uri); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java 2013-06-28 11:33:21.914791443 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java 2013-06-28 11:33:21.754796424 -0400 @@ -2,27 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - - - /** * A container for ds:Transforms. *

      @@ -40,36 +39,12 @@ */ public interface Transforms { /** - * Returns an Iterator over all the transforms contained in - * this transform list. - * - * @return all transforms. - */ - /* Iterator getTransforms(); */ - - /** - * Adds a ds:Transform to the list of transforms. - * - * @param transform. + * Temporary method to turn the XMLEncryption Transforms class + * into a DS class. The main logic is currently implemented in the + * DS class, so we need to get to get the base class. + *

      + * Note This will be removed in future versions */ - /* void addTransform(Transform transform); */ - - /** - * Removes the specified transform. - * - * @param transform. - */ - /* void removeTransform(Transform transform); */ - - /** - * Temporary method to turn the XMLEncryption Transforms class - * into a DS class. The main logic is currently implemented in the - * DS class, so we need to get to get the base class. - *

      - * Note This will be removed in future versions - * @return - */ - - com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms(); + com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms(); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java 2013-06-28 11:33:22.586770526 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java 2013-06-28 11:33:22.426775507 -0400 @@ -2,57 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - import java.io.ByteArrayOutputStream; import java.io.InputStream; -import java.io.IOException; -import java.io.StringReader; import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.security.spec.MGF1ParameterSpec; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import javax.crypto.spec.OAEPParameterSpec; +import javax.crypto.spec.PSource; import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException; +import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; 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.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.EncryptedKeyResolver; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException; @@ -62,17 +67,11 @@ import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; -import com.sun.org.apache.xml.internal.utils.URI; import org.w3c.dom.Attr; import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - /** * XMLCipher encrypts and decrypts the contents of @@ -85,133 +84,245 @@ */ public class XMLCipher { - private static java.util.logging.Logger logger = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLCipher.class.getName()); - //J- - /** Triple DES EDE (192 bit key) in CBC mode */ - public static final String TRIPLEDES = + /** Triple DES EDE (192 bit key) in CBC mode */ + public static final String TRIPLEDES = EncryptionConstants.ALGO_ID_BLOCKCIPHER_TRIPLEDES; + /** AES 128 Cipher */ - public static final String AES_128 = + public static final String AES_128 = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128; + /** AES 256 Cipher */ - public static final String AES_256 = + public static final String AES_256 = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256; + /** AES 192 Cipher */ - public static final String AES_192 = + public static final String AES_192 = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192; + + /** AES 128 GCM Cipher */ + public static final String AES_128_GCM = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM; + + /** AES 192 GCM Cipher */ + public static final String AES_192_GCM = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM; + + /** AES 256 GCM Cipher */ + public static final String AES_256_GCM = + EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM; + /** RSA 1.5 Cipher */ - public static final String RSA_v1dot5 = + public static final String RSA_v1dot5 = EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15; + /** RSA OAEP Cipher */ - public static final String RSA_OAEP = + public static final String RSA_OAEP = EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP; + + /** RSA OAEP Cipher */ + public static final String RSA_OAEP_11 = + EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP_11; + /** DIFFIE_HELLMAN Cipher */ - public static final String DIFFIE_HELLMAN = + public static final String DIFFIE_HELLMAN = EncryptionConstants.ALGO_ID_KEYAGREEMENT_DH; + /** Triple DES EDE (192 bit key) in CBC mode KEYWRAP*/ - public static final String TRIPLEDES_KeyWrap = + public static final String TRIPLEDES_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_TRIPLEDES; + /** AES 128 Cipher KeyWrap */ - public static final String AES_128_KeyWrap = + public static final String AES_128_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_AES128; + /** AES 256 Cipher KeyWrap */ - public static final String AES_256_KeyWrap = + public static final String AES_256_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_AES256; + /** AES 192 Cipher KeyWrap */ - public static final String AES_192_KeyWrap = + public static final String AES_192_KeyWrap = EncryptionConstants.ALGO_ID_KEYWRAP_AES192; + /** SHA1 Cipher */ - public static final String SHA1 = + public static final String SHA1 = Constants.ALGO_ID_DIGEST_SHA1; + /** SHA256 Cipher */ - public static final String SHA256 = + public static final String SHA256 = MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256; + /** SHA512 Cipher */ - public static final String SHA512 = + public static final String SHA512 = MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512; + /** RIPEMD Cipher */ - public static final String RIPEMD_160 = + public static final String RIPEMD_160 = MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160; + /** XML Signature NS */ - public static final String XML_DSIG = + public static final String XML_DSIG = Constants.SignatureSpecNS; + /** N14C_XML */ - public static final String N14C_XML = + public static final String N14C_XML = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + /** N14C_XML with comments*/ - public static final String N14C_XML_WITH_COMMENTS = + public static final String N14C_XML_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; - /** N14C_XML excluisve */ - public static final String EXCL_XML_N14C = + + /** N14C_XML exclusive */ + public static final String EXCL_XML_N14C = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; - /** N14C_XML exclusive with commetns*/ - public static final String EXCL_XML_N14C_WITH_COMMENTS = + + /** N14C_XML exclusive with comments*/ + public static final String EXCL_XML_N14C_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + + /** N14C_PHYSICAL preserve the physical representation*/ + public static final String PHYSICAL_XML_N14C = + Canonicalizer.ALGO_ID_C14N_PHYSICAL; + /** Base64 encoding */ - public static final String BASE64_ENCODING = + public static final String BASE64_ENCODING = com.sun.org.apache.xml.internal.security.transforms.Transforms.TRANSFORM_BASE64_DECODE; - //J+ /** ENCRYPT Mode */ public static final int ENCRYPT_MODE = Cipher.ENCRYPT_MODE; + /** DECRYPT Mode */ public static final int DECRYPT_MODE = Cipher.DECRYPT_MODE; + /** UNWRAP Mode */ public static final int UNWRAP_MODE = Cipher.UNWRAP_MODE; + /** WRAP Mode */ public static final int WRAP_MODE = Cipher.WRAP_MODE; private static final String ENC_ALGORITHMS = TRIPLEDES + "\n" + - AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" + - RSA_OAEP + "\n" + TRIPLEDES_KeyWrap + "\n" + AES_128_KeyWrap + "\n" + - AES_256_KeyWrap + "\n" + AES_192_KeyWrap+ "\n"; - - /** Cipher created during initialisation that is used for encryption */ - private Cipher _contextCipher; - /** Mode that the XMLCipher object is operating in */ - private int _cipherMode = Integer.MIN_VALUE; - /** URI of algorithm that is being used for cryptographic operation */ - private String _algorithm = null; - /** Cryptographic provider requested by caller */ - private String _requestedJCEProvider = null; - /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */ - private Canonicalizer _canon; - /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */ - private Document _contextDocument; - /** Instance of factory used to create XML Encryption objects */ - private Factory _factory; - /** Internal serializer class for going to/from UTF-8 */ - private Serializer _serializer; - - /** Local copy of user's key */ - private Key _key; - /** Local copy of the kek (used to decrypt EncryptedKeys during a + AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" + + RSA_OAEP + "\n" + RSA_OAEP_11 + "\n" + TRIPLEDES_KeyWrap + "\n" + + AES_128_KeyWrap + "\n" + AES_256_KeyWrap + "\n" + AES_192_KeyWrap + "\n" + + AES_128_GCM + "\n" + AES_192_GCM + "\n" + AES_256_GCM + "\n"; + + /** Cipher created during initialisation that is used for encryption */ + private Cipher contextCipher; + + /** Mode that the XMLCipher object is operating in */ + private int cipherMode = Integer.MIN_VALUE; + + /** URI of algorithm that is being used for cryptographic operation */ + private String algorithm = null; + + /** Cryptographic provider requested by caller */ + private String requestedJCEProvider = null; + + /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */ + private Canonicalizer canon; + + /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */ + private Document contextDocument; + + /** Instance of factory used to create XML Encryption objects */ + private Factory factory; + + /** Serializer class for going to/from UTF-8 */ + private Serializer serializer; + + /** Local copy of user's key */ + private Key key; + + /** Local copy of the kek (used to decrypt EncryptedKeys during a * DECRYPT_MODE operation */ - private Key _kek; - - // The EncryptedKey being built (part of a WRAP operation) or read - // (part of an UNWRAP operation) - - private EncryptedKey _ek; + private Key kek; - // The EncryptedData being built (part of a WRAP operation) or read - // (part of an UNWRAP operation) - - private EncryptedData _ed; + // The EncryptedKey being built (part of a WRAP operation) or read + // (part of an UNWRAP operation) + private EncryptedKey ek; + + // The EncryptedData being built (part of a WRAP operation) or read + // (part of an UNWRAP operation) + private EncryptedData ed; + + private SecureRandom random; + + private boolean secureValidation; + + private String digestAlg; + + /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */ + private List internalKeyResolvers; + + /** + * Set the Serializer algorithm to use + */ + public void setSerializer(Serializer serializer) { + this.serializer = serializer; + serializer.setCanonicalizer(this.canon); + } + + /** + * Get the Serializer algorithm to use + */ + public Serializer getSerializer() { + return serializer; + } /** * Creates a new XMLCipher. * - * @since 1.0. - */ - private XMLCipher() { - logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); + * @param transformation the name of the transformation, e.g., + * XMLCipher.TRIPLEDES. If null the XMLCipher can only + * be used for decrypt or unwrap operations where the encryption method + * is defined in the EncryptionMethod element. + * @param provider the JCE provider that supplies the transformation, + * if null use the default provider. + * @param canon the name of the c14n algorithm, if + * null use standard serializer + * @param digestMethod An optional digestMethod to use. + */ + private XMLCipher( + String transformation, + String provider, + String canonAlg, + String digestMethod + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); + } + + factory = new Factory(); + + algorithm = transformation; + requestedJCEProvider = provider; + digestAlg = digestMethod; + + // Create a canonicalizer - used when serializing DOM to octets + // prior to encryption (and for the reverse) - _factory = new Factory(); - _serializer = new Serializer(); + try { + if (canonAlg == null) { + // The default is to preserve the physical representation. + this.canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_PHYSICAL); + } else { + this.canon = Canonicalizer.getInstance(canonAlg); + } + } catch (InvalidCanonicalizerException ice) { + throw new XMLEncryptionException("empty", ice); + } + if (serializer == null) { + serializer = new DocumentSerializer(); + } + serializer.setCanonicalizer(this.canon); + + if (transformation != null) { + contextCipher = constructCipher(transformation, digestMethod); + } } /** @@ -222,20 +333,38 @@ * @since 1.0. */ private static boolean isValidEncryptionAlgorithm(String algorithm) { - boolean result = ( + return ( algorithm.equals(TRIPLEDES) || algorithm.equals(AES_128) || algorithm.equals(AES_256) || algorithm.equals(AES_192) || + algorithm.equals(AES_128_GCM) || + algorithm.equals(AES_192_GCM) || + algorithm.equals(AES_256_GCM) || algorithm.equals(RSA_v1dot5) || algorithm.equals(RSA_OAEP) || + algorithm.equals(RSA_OAEP_11) || algorithm.equals(TRIPLEDES_KeyWrap) || algorithm.equals(AES_128_KeyWrap) || algorithm.equals(AES_256_KeyWrap) || algorithm.equals(AES_192_KeyWrap) ); + } - return (result); + /** + * Validate the transformation argument of getInstance or getProviderInstance + * + * @param transformation the name of the transformation, e.g., + * XMLCipher.TRIPLEDES which is shorthand for + * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" + */ + private static void validateTransformation(String transformation) { + if (null == transformation) { + throw new NullPointerException("Transformation unexpectedly null..."); + } + if (!isValidEncryptionAlgorithm(transformation)) { + log.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); + } } /** @@ -248,7 +377,7 @@ * the default provider package, other provider packages are searched. *

      * NOTE1: The transformation name does not follow the same - * pattern as that oulined in the Java Cryptography Extension Reference + * pattern as that outlined in the Java Cryptography Extension Reference * Guide but rather that specified by the XML Encryption Syntax and * Processing document. The rational behind this is to make it easier for a * novice at writing Java Encryption software to use the library. @@ -257,7 +386,7 @@ * same pattern regarding exceptional conditions as that used in * javax.crypto.Cipher. Instead, it only throws an * XMLEncryptionException which wraps an underlying exception. - * The stack trace from the exception should be self explanitory. + * The stack trace from the exception should be self explanatory. * * @param transformation the name of the transformation, e.g., * XMLCipher.TRIPLEDES which is shorthand for @@ -266,293 +395,169 @@ * @return the XMLCipher * @see javax.crypto.Cipher#getInstance(java.lang.String) */ - public static XMLCipher getInstance(String transformation) throws - XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._key = null; - instance._kek = null; - - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation); - - try { - instance._contextCipher = Cipher.getInstance(jceAlgorithm); - logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + - instance._contextCipher.getAlgorithm()); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchPaddingException nspe) { - throw new XMLEncryptionException("empty", nspe); + public static XMLCipher getInstance(String transformation) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation"); } - - return (instance); + validateTransformation(transformation); + return new XMLCipher(transformation, null, null, null); } - /** - * Returns an XMLCipher that implements the specified - * transformation, operates on the specified context document and serializes - * the document with the specified canonicalization algorithm before it - * encrypts the document. - *

      - * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param canon the name of the c14n algorithm, if - * null use standard serializer - * @return - * @throws XMLEncryptionException - */ - - public static XMLCipher getInstance(String transformation, String canon) - throws XMLEncryptionException { - XMLCipher instance = XMLCipher.getInstance(transformation); - - if (canon != null) { - try { - instance._canon = Canonicalizer.getInstance(canon); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - } - - return instance; - } - - public static XMLCipher getInstance(String transformation,Cipher cipher) throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._key = null; - instance._kek = null; - - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

      + * + * @param transformation the name of the transformation + * @param canon the name of the c14n algorithm, if null use + * standard serializer + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getInstance(String transformation, String canon) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm"); } - - String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation); - - try { - instance._contextCipher = cipher; - //Cipher.getInstance(jceAlgorithm); - logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " + - instance._contextCipher.getAlgorithm()); - }catch(Exception ex) { - throw new XMLEncryptionException("empty", ex); + validateTransformation(transformation); + return new XMLCipher(transformation, null, canon, null); + } + + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

      + * + * @param transformation the name of the transformation + * @param canon the name of the c14n algorithm, if null use + * standard serializer + * @param digestMethod An optional digestMethod to use + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getInstance(String transformation, String canon, String digestMethod) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm"); } - - return (instance); + validateTransformation(transformation); + return new XMLCipher(transformation, null, canon, digestMethod); } /** * Returns an XMLCipher that implements the specified * transformation and operates on the specified context document. * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param provider the JCE provider that supplies the transformation + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation * @return the XMLCipher * @throws XMLEncryptionException */ - public static XMLCipher getProviderInstance(String transformation, String provider) - throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher..."); - if (null == transformation) - logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null..."); - if(null == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null.."); - if("" == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider's value unexpectedly not specified..."); - if(!isValidEncryptionAlgorithm(transformation)) - logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = transformation; - instance._requestedJCEProvider = provider; - instance._key = null; - instance._kek = null; - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - try { - String jceAlgorithm = - JCEMapper.translateURItoJCEID(transformation); - - instance._contextCipher = Cipher.getInstance(jceAlgorithm, provider); - - logger.log(java.util.logging.Level.FINE, "cipher._algorithm = " + - instance._contextCipher.getAlgorithm()); - logger.log(java.util.logging.Level.FINE, "provider.name = " + provider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspe) { - throw new XMLEncryptionException("empty", nspe); + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and provider"); } - - return (instance); + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, null, null); } - /** - * Returns an XMLCipher that implements the specified + /** + * Returns an XMLCipher that implements the specified * transformation, operates on the specified context document and serializes * the document with the specified canonicalization algorithm before it * encrypts the document. *

      - * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param provider the JCE provider that supplies the transformation - * @param canon the name of the c14n algorithm, if - * null use standard serializer - * @return - * @throws XMLEncryptionException - */ - public static XMLCipher getProviderInstance( - String transformation, - String provider, - String canon) - throws XMLEncryptionException { - - XMLCipher instance = XMLCipher.getProviderInstance(transformation, provider); - if (canon != null) { - try { - instance._canon = Canonicalizer.getInstance(canon); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - } - return instance; + * + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation + * @param canon the name of the c14n algorithm, if null use standard + * serializer + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getProviderInstance( + String transformation, String provider, String canon + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm"); + } + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, canon, null); + } + + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

      + * + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation + * @param canon the name of the c14n algorithm, if null use standard + * serializer + * @param digestMethod An optional digestMethod to use + * @return the XMLCipher + * @throws XMLEncryptionException + */ + public static XMLCipher getProviderInstance( + String transformation, String provider, String canon, String digestMethod + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm"); } + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, canon, digestMethod); + } /** * Returns an XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod element. - * + * transformation, and can therefore only be used for decrypt or + * unwrap operations where the encryption method is defined in the + * EncryptionMethod element. + * * @return The XMLCipher * @throws XMLEncryptionException */ - - public static XMLCipher getInstance() - throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation..."); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = null; - instance._requestedJCEProvider = null; - instance._key = null; - instance._kek = null; - instance._contextCipher = null; - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - return (instance); + public static XMLCipher getInstance() throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with no arguments"); + } + return new XMLCipher(null, null, null, null); } /** * Returns an XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod element. - * - * Allows the caller to specify a provider that will be used for - * cryptographic operations. + * transformation, and can therefore only be used for decrypt or + * unwrap operations where the encryption method is defined in the + * EncryptionMethod element. + * + * Allows the caller to specify a provider that will be used for + * cryptographic operations. * - * @param provider the JCE provider that supplies the cryptographic - * needs. + * @param provider the JCE provider that supplies the transformation * @return the XMLCipher * @throws XMLEncryptionException */ - - public static XMLCipher getProviderInstance(String provider) - throws XMLEncryptionException { - // sanity checks - - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher, provider but no transformation"); - if(null == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider unexpectedly null.."); - if("" == provider) - logger.log(java.util.logging.Level.SEVERE, "Provider's value unexpectedly not specified..."); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = null; - instance._requestedJCEProvider = provider; - instance._key = null; - instance._kek = null; - instance._contextCipher = null; - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - return (instance); + public static XMLCipher getProviderInstance(String provider) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with provider"); + } + return new XMLCipher(null, provider, null, null); } /** @@ -561,13 +566,13 @@ * The cipher is initialized for one of the following four operations: * encryption, decryption, key wrapping or key unwrapping, depending on the * value of opmode. - * - * For WRAP and ENCRYPT modes, this also initialises the internal - * EncryptedKey or EncryptedData (with a CipherValue) - * structure that will be used during the ensuing operations. This - * can be obtained (in order to modify KeyInfo elements etc. prior to - * finalising the encryption) by calling - * {@link #getEncryptedData} or {@link #getEncryptedKey}. + * + * For WRAP and ENCRYPT modes, this also initialises the internal + * EncryptedKey or EncryptedData (with a CipherValue) + * structure that will be used during the ensuing operations. This + * can be obtained (in order to modify KeyInfo elements etc. prior to + * finalising the encryption) by calling + * {@link #getEncryptedData} or {@link #getEncryptedKey}. * * @param opmode the operation mode of this cipher (this is one of the * following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE) @@ -577,195 +582,250 @@ */ public void init(int opmode, Key key) throws XMLEncryptionException { // sanity checks - logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); - - _ek = null; - _ed = null; - - switch (opmode) { - - case ENCRYPT_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE"); - _ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET"); - break; - case DECRYPT_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE"); - break; - case WRAP_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE"); - _ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET"); - break; - case UNWRAP_MODE : - logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE"); - break; - default : - logger.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid"); - throw new XMLEncryptionException("Invalid mode in init"); - } - - _cipherMode = opmode; - _key = key; - - } - - /** - * Get the EncryptedData being build - * - * Returns the EncryptedData being built during an ENCRYPT operation. - * This can then be used by applications to add KeyInfo elements and - * set other parameters. - * - * @return The EncryptedData being built - */ - - public EncryptedData getEncryptedData() { - - // Sanity checks - logger.log(java.util.logging.Level.FINE, "Returning EncryptedData"); - return _ed; - - } - - /** - * Get the EncryptedData being build - * - * Returns the EncryptedData being built during an ENCRYPT operation. - * This can then be used by applications to add KeyInfo elements and - * set other parameters. - * - * @return The EncryptedData being built - */ - - public EncryptedKey getEncryptedKey() { - - // Sanity checks - logger.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); - return _ek; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Initializing XMLCipher..."); } - /** - * Set a Key Encryption Key. - *

      - * The Key Encryption Key (KEK) is used for encrypting/decrypting - * EncryptedKey elements. By setting this separately, the XMLCipher - * class can know whether a key applies to the data part or wrapped key - * part of an encrypted object. - * - * @param kek The key to use for de/encrypting key data - */ - - public void setKEK(Key kek) { + ek = null; + ed = null; - _kek = kek; + switch (opmode) { + case ENCRYPT_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE"); + } + ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET"); + break; + case DECRYPT_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE"); + } + break; + case WRAP_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE"); + } + ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET"); + break; + case UNWRAP_MODE : + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE"); + } + break; + default : + log.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid"); + throw new XMLEncryptionException("Invalid mode in init"); } - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - *

      - * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedData EncryptedData object to martial - * @return the DOM Element representing the passed in - * object + cipherMode = opmode; + this.key = key; + } + + /** + * Set whether secure validation is enabled or not. The default is false. */ - - public Element martial(EncryptedData encryptedData) { - - return (_factory.toElement (encryptedData)); - - } - - /** - * Martial an EncryptedKey - * - * Takes an EncryptedKey object and returns a DOM Element that - * represents the appropriate EncryptedKey - * - *

      - * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedKey EncryptedKey object to martial - * @return the DOM Element representing the passed in - * object */ - - public Element martial(EncryptedKey encryptedKey) { - - return (_factory.toElement (encryptedKey)); - + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to an XMLCipher. + * These KeyResolvers are used in KeyInfo objects in DECRYPT and + * UNWRAP modes. + * + * @param keyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi keyResolver) { + if (internalKeyResolvers == null) { + internalKeyResolvers = new ArrayList(); } + internalKeyResolvers.add(keyResolver); + } - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - * - * @param context The document that will own the returned nodes - * @param encryptedData EncryptedData object to martial - * @return the DOM Element representing the passed in - * object */ - - public Element martial(Document context, EncryptedData encryptedData) { - - _contextDocument = context; - return (_factory.toElement (encryptedData)); - + /** + * Get the EncryptedData being built + *

      + * Returns the EncryptedData being built during an ENCRYPT operation. + * This can then be used by applications to add KeyInfo elements and + * set other parameters. + * + * @return The EncryptedData being built + */ + public EncryptedData getEncryptedData() { + // Sanity checks + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Returning EncryptedData"); } + return ed; + } - /** - * Martial an EncryptedKey - * - * Takes an EncryptedKey object and returns a DOM Element that - * represents the appropriate EncryptedKey - * - * @param context The document that will own the created nodes - * @param encryptedKey EncryptedKey object to martial - * @return the DOM Element representing the passed in - * object */ - - public Element martial(Document context, EncryptedKey encryptedKey) { - - _contextDocument = context; - return (_factory.toElement (encryptedKey)); - + /** + * Get the EncryptedData being build + * + * Returns the EncryptedData being built during an ENCRYPT operation. + * This can then be used by applications to add KeyInfo elements and + * set other parameters. + * + * @return The EncryptedData being built + */ + public EncryptedKey getEncryptedKey() { + // Sanity checks + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); } + return ek; + } /** - * Encrypts an Element and replaces it with its encrypted - * counterpart in the context Document, that is, the - * Document specified when one calls - * {@link #getInstance(String) getInstance}. + * Set a Key Encryption Key. + *

      + * The Key Encryption Key (KEK) is used for encrypting/decrypting + * EncryptedKey elements. By setting this separately, the XMLCipher + * class can know whether a key applies to the data part or wrapped key + * part of an encrypted object. * - * @param element the Element to encrypt. - * @return the context Document with the encrypted - * Element having replaced the source Element. - * @throws Exception + * @param kek The key to use for de/encrypting key data */ - private Document encryptElement(Element element) throws Exception{ - logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); - - if (_algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - encryptData(_contextDocument, element, false); - - Element encryptedElement = _factory.toElement(_ed); - - Node sourceParent = element.getParentNode(); - sourceParent.replaceChild(encryptedElement, element); - - return (_contextDocument); + public void setKEK(Key kek) { + this.kek = kek; + } + + /** + * Martial an EncryptedData + * + * Takes an EncryptedData object and returns a DOM Element that + * represents the appropriate EncryptedData + *

      + * Note: This should only be used in cases where the context + * document has been passed in via a call to doFinal. + * + * @param encryptedData EncryptedData object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(EncryptedData encryptedData) { + return factory.toElement(encryptedData); + } + + /** + * Martial an EncryptedData + * + * Takes an EncryptedData object and returns a DOM Element that + * represents the appropriate EncryptedData + * + * @param context The document that will own the returned nodes + * @param encryptedData EncryptedData object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, EncryptedData encryptedData) { + contextDocument = context; + return factory.toElement(encryptedData); + } + + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + *

      + * Note: This should only be used in cases where the context + * document has been passed in via a call to doFinal. + * + * @param encryptedKey EncryptedKey object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(EncryptedKey encryptedKey) { + return factory.toElement(encryptedKey); + } + + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + * @param context The document that will own the created nodes + * @param encryptedKey EncryptedKey object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, EncryptedKey encryptedKey) { + contextDocument = context; + return factory.toElement(encryptedKey); + } + + /** + * Martial a ReferenceList + * + * Takes a ReferenceList object and returns a DOM Element that + * represents the appropriate ReferenceList + * + *

      + * Note: This should only be used in cases where the context + * document has been passed in via a call to doFinal. + * + * @param referenceList ReferenceList object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(ReferenceList referenceList) { + return factory.toElement(referenceList); + } + + /** + * Martial a ReferenceList + * + * Takes a ReferenceList object and returns a DOM Element that + * represents the appropriate ReferenceList + * + * @param context The document that will own the created nodes + * @param referenceList ReferenceList object to martial + * @return the DOM Element representing the passed in + * object + */ + public Element martial(Document context, ReferenceList referenceList) { + contextDocument = context; + return factory.toElement(referenceList); + } + + /** + * Encrypts an Element and replaces it with its encrypted + * counterpart in the context Document, that is, the + * Document specified when one calls + * {@link #getInstance(String) getInstance}. + * + * @param element the Element to encrypt. + * @return the context Document with the encrypted + * Element having replaced the source Element. + * @throws Exception + */ + private Document encryptElement(Element element) throws Exception{ + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } + + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } + encryptData(contextDocument, element, false); + + Element encryptedElement = factory.toElement(ed); + + Node sourceParent = element.getParentNode(); + sourceParent.replaceChild(encryptedElement, element); + + return contextDocument; } /** @@ -782,25 +842,28 @@ * Element. * @throws Exception */ - private Document encryptElementContent(Element element) throws - /* XMLEncryption */Exception { - logger.log(java.util.logging.Level.FINE, "Encrypting element content..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element content..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } - if (_algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - encryptData(_contextDocument, element, true); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } + encryptData(contextDocument, element, true); - Element encryptedElement = _factory.toElement(_ed); + Element encryptedElement = factory.toElement(ed); removeContent(element); element.appendChild(encryptedElement); - return (_contextDocument); + return contextDocument; } /** @@ -812,19 +875,22 @@ * @return the processed Document. * @throws Exception to indicate any exceptional conditions. */ - public Document doFinal(Document context, Document source) throws - /* XMLEncryption */Exception { - logger.log(java.util.logging.Level.FINE, "Processing source document..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == source) - logger.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null..."); + public Document doFinal(Document context, Document source) throws /* XMLEncryption */Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Processing source document..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == source) { + log.log(java.util.logging.Level.SEVERE, "Source document unexpectedly null..."); + } - _contextDocument = context; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: result = decryptElement(source.getDocumentElement()); break; @@ -832,15 +898,13 @@ result = encryptElement(source.getDocumentElement()); break; case UNWRAP_MODE: - break; case WRAP_MODE: break; default: - throw new XMLEncryptionException( - "empty", new IllegalStateException()); + throw new XMLEncryptionException("empty", new IllegalStateException()); } - return (result); + return result; } /** @@ -852,19 +916,22 @@ * @return the processed Document. * @throws Exception to indicate any exceptional conditions. */ - public Document doFinal(Document context, Element element) throws - /* XMLEncryption */Exception { - logger.log(java.util.logging.Level.FINE, "Processing source element..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + public Document doFinal(Document context, Element element) throws /* XMLEncryption */Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Processing source element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + } - _contextDocument = context; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: result = decryptElement(element); break; @@ -872,15 +939,13 @@ result = encryptElement(element); break; case UNWRAP_MODE: - break; case WRAP_MODE: break; default: - throw new XMLEncryptionException( - "empty", new IllegalStateException()); + throw new XMLEncryptionException("empty", new IllegalStateException()); } - return (result); + return result; } /** @@ -896,18 +961,22 @@ * @throws Exception to indicate any exceptional conditions. */ public Document doFinal(Document context, Element element, boolean content) - throws /* XMLEncryption*/ Exception { - logger.log(java.util.logging.Level.FINE, "Processing source element..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + throws /* XMLEncryption*/ Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Processing source element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null..."); + } - _contextDocument = context; + contextDocument = context; Document result = null; - switch (_cipherMode) { + switch (cipherMode) { case DECRYPT_MODE: if (content) { result = decryptElementContent(element); @@ -923,15 +992,13 @@ } break; case UNWRAP_MODE: - break; case WRAP_MODE: break; default: - throw new XMLEncryptionException( - "empty", new IllegalStateException()); + throw new XMLEncryptionException("empty", new IllegalStateException()); } - return (result); + return result; } /** @@ -939,15 +1006,15 @@ * you want to have full control over the contents of the * EncryptedData structure. * - * this does not change the source document in any way. + * This does not change the source document in any way. * * @param context the context Document. * @param element the Element that will be encrypted. * @return the EncryptedData * @throws Exception */ - public EncryptedData encryptData(Document context, Element element) throws - /* XMLEncryption */Exception { + public EncryptedData encryptData(Document context, Element element) throws + /* XMLEncryption */Exception { return encryptData(context, element, false); } @@ -965,16 +1032,21 @@ * @return the EncryptedData * @throws Exception */ - public EncryptedData encryptData(Document context, String type, - InputStream serializedData) throws Exception { - - logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if (null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if (null == serializedData) - logger.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null..."); - if (_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + public EncryptedData encryptData( + Document context, String type, InputStream serializedData + ) throws Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == serializedData) { + log.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } return encryptData(context, null, type, serializedData); } @@ -984,7 +1056,7 @@ * you want to have full control over the contents of the * EncryptedData structure. * - * this does not change the source document in any way. + * This does not change the source document in any way. * * @param context the context Document. * @param element the Element that will be encrypted. @@ -994,84 +1066,84 @@ * @throws Exception */ public EncryptedData encryptData( - Document context, Element element, boolean contentMode) - throws /* XMLEncryption */ Exception { - - logger.log(java.util.logging.Level.FINE, "Encrypting element..."); - if (null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if (null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if (_cipherMode != ENCRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + Document context, Element element, boolean contentMode + ) throws /* XMLEncryption */ Exception { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting element..."); + } + if (null == context) { + log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); + } + if (null == element) { + log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); + } + if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); + } if (contentMode) { - return encryptData - (context, element, EncryptionConstants.TYPE_CONTENT, null); + return encryptData(context, element, EncryptionConstants.TYPE_CONTENT, null); } else { - return encryptData - (context, element, EncryptionConstants.TYPE_ELEMENT, null); + return encryptData(context, element, EncryptionConstants.TYPE_ELEMENT, null); } } private EncryptedData encryptData( - Document context, Element element, String type, - InputStream serializedData) throws /* XMLEncryption */ Exception { + Document context, Element element, String type, InputStream serializedData + ) throws /* XMLEncryption */ Exception { + contextDocument = context; - _contextDocument = context; - - if (_algorithm == null) { - throw new XMLEncryptionException - ("XMLCipher instance without transformation specified"); + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); } - String serializedOctets = null; + byte[] serializedOctets = null; if (serializedData == null) { - if (type == EncryptionConstants.TYPE_CONTENT) { + if (type.equals(EncryptionConstants.TYPE_CONTENT)) { NodeList children = element.getChildNodes(); if (null != children) { - serializedOctets = _serializer.serialize(children); + serializedOctets = serializer.serializeToByteArray(children); } else { Object exArgs[] = { "Element has no content." }; throw new XMLEncryptionException("empty", exArgs); } } else { - serializedOctets = _serializer.serialize(element); + serializedOctets = serializer.serializeToByteArray(element); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8")); } - logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets); } byte[] encryptedBytes = null; // Now create the working cipher if none was created already Cipher c; - if (_contextCipher == null) { - String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm); - logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); - - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } + if (contextCipher == null) { + c = constructCipher(algorithm, null); } else { - c = _contextCipher; + c = contextCipher; } // Now perform the encryption try { - // Should internally generate an IV - // todo - allow user to set an IV - c.init(_cipherMode, _key); + // The Spec mandates a 96-bit IV for GCM algorithms + if (AES_128_GCM.equals(algorithm) || AES_192_GCM.equals(algorithm) + || AES_256_GCM.equals(algorithm)) { + if (random == null) { + random = SecureRandom.getInstance("SHA1PRNG"); + } + byte[] temp = new byte[12]; + random.nextBytes(temp); + IvParameterSpec paramSpec = new IvParameterSpec(temp); + c.init(cipherMode, key, paramSpec); + } else { + c.init(cipherMode, key); + } } catch (InvalidKeyException ike) { throw new XMLEncryptionException("empty", ike); + } catch (NoSuchAlgorithmException ex) { + throw new XMLEncryptionException("empty", ex); } try { @@ -1086,13 +1158,16 @@ baos.write(c.doFinal()); encryptedBytes = baos.toByteArray(); } else { - encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8")); - logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + - Integer.toString(c.getOutputSize( - serializedOctets.getBytes().length))); + encryptedBytes = c.doFinal(serializedOctets); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + + Integer.toString(c.getOutputSize(serializedOctets.length))); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + + Integer.toString(encryptedBytes.length)); } - logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " + - Integer.toString(encryptedBytes.length)); } catch (IllegalStateException ise) { throw new XMLEncryptionException("empty", ise); } catch (IllegalBlockSizeException ibse) { @@ -1106,300 +1181,410 @@ // Now build up to a properly XML Encryption encoded octet stream // IvParameterSpec iv; byte[] iv = c.getIV(); - byte[] finalEncryptedBytes = - new byte[iv.length + encryptedBytes.length]; + byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length]; System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length); - System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, - encryptedBytes.length); + System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length); String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes); - logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); - logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " + - base64EncodedEncryptedOctets.length()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + log.log(java.util.logging.Level.FINE, "Encrypted octets length = " + base64EncodedEncryptedOctets.length()); + } try { - CipherData cd = _ed.getCipherData(); + CipherData cd = ed.getCipherData(); CipherValue cv = cd.getCipherValue(); // cv.setValue(base64EncodedEncryptedOctets.getBytes()); cv.setValue(base64EncodedEncryptedOctets); if (type != null) { - _ed.setType(new URI(type).toString()); + ed.setType(new URI(type).toString()); } EncryptionMethod method = - _factory.newEncryptionMethod(new URI(_algorithm).toString()); - _ed.setEncryptionMethod(method); - } catch (URI.MalformedURIException mfue) { - throw new XMLEncryptionException("empty", mfue); + factory.newEncryptionMethod(new URI(algorithm).toString()); + method.setDigestAlgorithm(digestAlg); + ed.setEncryptionMethod(method); + } catch (URISyntaxException ex) { + throw new XMLEncryptionException("empty", ex); } - return (_ed); + return ed; } /** * Returns an EncryptedData interface. Use this operation if - * you want to load an EncryptedData structure from a DOM - * structure and manipulate the contents + * you want to load an EncryptedData structure from a DOM + * structure and manipulate the contents. * * @param context the context Document. * @param element the Element that will be loaded * @throws XMLEncryptionException - * @return + * @return the EncryptedData */ - public EncryptedData loadEncryptedData(Document context, Element element) - throws XMLEncryptionException { - logger.log(java.util.logging.Level.FINE, "Loading encrypted element..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + public EncryptedData loadEncryptedData(Document context, Element element) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Loading encrypted element..."); + } + if (null == context) { + throw new NullPointerException("Context document unexpectedly null..."); + } + if (null == element) { + throw new NullPointerException("Element unexpectedly null..."); + } + if (cipherMode != DECRYPT_MODE) { + throw new XMLEncryptionException("XMLCipher unexpectedly not in DECRYPT_MODE..."); + } - _contextDocument = context; - _ed = _factory.newEncryptedData(element); + contextDocument = context; + ed = factory.newEncryptedData(element); - return (_ed); + return ed; } /** * Returns an EncryptedKey interface. Use this operation if - * you want to load an EncryptedKey structure from a DOM - * structure and manipulate the contents. + * you want to load an EncryptedKey structure from a DOM + * structure and manipulate the contents. * * @param context the context Document. * @param element the Element that will be loaded - * @return + * @return the EncryptedKey * @throws XMLEncryptionException */ + public EncryptedKey loadEncryptedKey(Document context, Element element) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Loading encrypted key..."); + } + if (null == context) { + throw new NullPointerException("Context document unexpectedly null..."); + } + if (null == element) { + throw new NullPointerException("Element unexpectedly null..."); + } + if (cipherMode != UNWRAP_MODE && cipherMode != DECRYPT_MODE) { + throw new XMLEncryptionException( + "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..." + ); + } - public EncryptedKey loadEncryptedKey(Document context, Element element) - throws XMLEncryptionException { - logger.log(java.util.logging.Level.FINE, "Loading encrypted key..."); - if(null == context) - logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null..."); - if(null == element) - logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - if(_cipherMode != UNWRAP_MODE && _cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..."); - - _contextDocument = context; - _ek = _factory.newEncryptedKey(element); - return (_ek); + contextDocument = context; + ek = factory.newEncryptedKey(element); + return ek; } /** * Returns an EncryptedKey interface. Use this operation if - * you want to load an EncryptedKey structure from a DOM - * structure and manipulate the contents. - * - * Assumes that the context document is the document that owns the element + * you want to load an EncryptedKey structure from a DOM + * structure and manipulate the contents. + * + * Assumes that the context document is the document that owns the element * * @param element the Element that will be loaded - * @return + * @return the EncryptedKey * @throws XMLEncryptionException */ - - public EncryptedKey loadEncryptedKey(Element element) - throws XMLEncryptionException { - - return (loadEncryptedKey(element.getOwnerDocument(), element)); + public EncryptedKey loadEncryptedKey(Element element) throws XMLEncryptionException { + return loadEncryptedKey(element.getOwnerDocument(), element); } - + /** * Encrypts a key to an EncryptedKey structure - * - * @param doc the Context document that will be used to general DOM - * @param key Key to encrypt (will use previously set KEK to - * perform encryption - * @return + * + * @param doc the Context document that will be used to general DOM + * @param key Key to encrypt (will use previously set KEK to + * perform encryption + * @return the EncryptedKey * @throws XMLEncryptionException */ + public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException { + return encryptKey(doc, key, null, null); + } - public EncryptedKey encryptKey(Document doc, Key key) throws - XMLEncryptionException { - - logger.log(java.util.logging.Level.FINE, "Encrypting key ..."); - - if(null == key) - logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null..."); - if(_cipherMode != WRAP_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE..."); - - if (_algorithm == null) { - - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - - _contextDocument = doc; - - byte[] encryptedBytes = null; - Cipher c; + /** + * Encrypts a key to an EncryptedKey structure + * + * @param doc the Context document that will be used to general DOM + * @param key Key to encrypt (will use previously set KEK to + * perform encryption + * @param mgfAlgorithm The xenc11 MGF Algorithm to use + * @param oaepParams The OAEPParams to use + * @return the EncryptedKey + * @throws XMLEncryptionException + */ + public EncryptedKey encryptKey( + Document doc, + Key key, + String mgfAlgorithm, + byte[] oaepParams + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypting key ..."); + } - if (_contextCipher == null) { - // Now create the working cipher + if (null == key) { + log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null..."); + } + if (cipherMode != WRAP_MODE) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE..."); + } + if (algorithm == null) { + throw new XMLEncryptionException("XMLCipher instance without transformation specified"); + } - String jceAlgorithm = - JCEMapper.translateURItoJCEID(_algorithm); + contextDocument = doc; - logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm); + byte[] encryptedBytes = null; + Cipher c; - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - } else { - c = _contextCipher; - } - // Now perform the encryption + if (contextCipher == null) { + // Now create the working cipher + c = constructCipher(algorithm, null); + } else { + c = contextCipher; + } + // Now perform the encryption - try { - // Should internally generate an IV - // todo - allow user to set an IV - c.init(Cipher.WRAP_MODE, _key); - encryptedBytes = c.wrap(key); - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (IllegalBlockSizeException ibse) { - throw new XMLEncryptionException("empty", ibse); - } + try { + // Should internally generate an IV + // todo - allow user to set an IV + OAEPParameterSpec oaepParameters = + constructOAEPParameters( + algorithm, digestAlg, mgfAlgorithm, oaepParams + ); + if (oaepParameters == null) { + c.init(Cipher.WRAP_MODE, this.key); + } else { + c.init(Cipher.WRAP_MODE, this.key, oaepParameters); + } + encryptedBytes = c.wrap(key); + } catch (InvalidKeyException ike) { + throw new XMLEncryptionException("empty", ike); + } catch (IllegalBlockSizeException ibse) { + throw new XMLEncryptionException("empty", ibse); + } catch (InvalidAlgorithmParameterException e) { + throw new XMLEncryptionException("empty", e); + } String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); + log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length()); + } - logger.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); - logger.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + - base64EncodedEncryptedOctets.length()); - - CipherValue cv = _ek.getCipherData().getCipherValue(); - cv.setValue(base64EncodedEncryptedOctets); + CipherValue cv = ek.getCipherData().getCipherValue(); + cv.setValue(base64EncodedEncryptedOctets); try { - EncryptionMethod method = _factory.newEncryptionMethod( - new URI(_algorithm).toString()); - _ek.setEncryptionMethod(method); - } catch (URI.MalformedURIException mfue) { - throw new XMLEncryptionException("empty", mfue); + EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString()); + method.setDigestAlgorithm(digestAlg); + method.setMGFAlgorithm(mgfAlgorithm); + method.setOAEPparams(oaepParams); + ek.setEncryptionMethod(method); + } catch (URISyntaxException ex) { + throw new XMLEncryptionException("empty", ex); } - return _ek; - + return ek; } - /** - * Decrypt a key from a passed in EncryptedKey structure - * - * @param encryptedKey Previously loaded EncryptedKey that needs - * to be decrypted. - * @param algorithm Algorithm for the decryption - * @return a key corresponding to the give type + /** + * Decrypt a key from a passed in EncryptedKey structure + * + * @param encryptedKey Previously loaded EncryptedKey that needs + * to be decrypted. + * @param algorithm Algorithm for the decryption + * @return a key corresponding to the given type * @throws XMLEncryptionException - */ + */ + public Key decryptKey(EncryptedKey encryptedKey, String algorithm) + throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + } - public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws - XMLEncryptionException { + if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); + } - logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); + if (algorithm == null) { + throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm"); + } - if(_cipherMode != UNWRAP_MODE) - logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in UNWRAP_MODE..."); + if (key == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers"); + } - if (algorithm == null) { - throw new XMLEncryptionException("Cannot decrypt a key without knowing the algorithm"); + KeyInfo ki = encryptedKey.getKeyInfo(); + if (ki != null) { + ki.setSecureValidation(secureValidation); + try { + String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm(); + String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg); + if ("RSA".equals(keyType)) { + key = ki.getPrivateKey(); + } else { + key = ki.getSecretKey(); + } + } + catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } } + } + if (key == null) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve"); + throw new XMLEncryptionException("Unable to decrypt without a KEK"); + } + } - if (_key == null) { + // Obtain the encrypted octets + XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey); + cipherInput.setSecureValidation(secureValidation); + byte[] encryptedBytes = cipherInput.getBytes(); - logger.log(java.util.logging.Level.FINE, "Trying to find a KEK via key resolvers"); + String jceKeyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(algorithm); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "JCE Key Algorithm: " + jceKeyAlgorithm); + } - KeyInfo ki = encryptedKey.getKeyInfo(); - if (ki != null) { - try { - _key = ki.getSecretKey(); - } - catch (Exception e) { - } - } - if (_key == null) { - logger.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve"); - throw new XMLEncryptionException("Unable to decrypt without a KEK"); - } - } + Cipher c; + if (contextCipher == null) { + // Now create the working cipher + c = + constructCipher( + encryptedKey.getEncryptionMethod().getAlgorithm(), + encryptedKey.getEncryptionMethod().getDigestAlgorithm() + ); + } else { + c = contextCipher; + } - // Obtain the encrypted octets - XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey); - byte [] encryptedBytes = cipherInput.getBytes(); - - String jceKeyAlgorithm = - JCEMapper.getJCEKeyAlgorithmFromURI(algorithm); - - Cipher c; - if (_contextCipher == null) { - // Now create the working cipher - - String jceAlgorithm = - JCEMapper.translateURItoJCEID( - encryptedKey.getEncryptionMethod().getAlgorithm()); - - logger.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); - - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - } else { - c = _contextCipher; - } + Key ret; + + try { + EncryptionMethod encMethod = encryptedKey.getEncryptionMethod(); + OAEPParameterSpec oaepParameters = + constructOAEPParameters( + encMethod.getAlgorithm(), encMethod.getDigestAlgorithm(), + encMethod.getMGFAlgorithm(), encMethod.getOAEPparams() + ); + if (oaepParameters == null) { + c.init(Cipher.UNWRAP_MODE, key); + } else { + c.init(Cipher.UNWRAP_MODE, key, oaepParameters); + } + ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY); + } catch (InvalidKeyException ike) { + throw new XMLEncryptionException("empty", ike); + } catch (NoSuchAlgorithmException nsae) { + throw new XMLEncryptionException("empty", nsae); + } catch (InvalidAlgorithmParameterException e) { + throw new XMLEncryptionException("empty", e); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); + } - Key ret; + return ret; + } + + /** + * Construct an OAEPParameterSpec object from the given parameters + */ + private OAEPParameterSpec constructOAEPParameters( + String encryptionAlgorithm, + String digestAlgorithm, + String mgfAlgorithm, + byte[] oaepParams + ) { + if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithm) + || XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) { + + String jceDigestAlgorithm = "SHA-1"; + if (digestAlgorithm != null) { + jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm); + } + + PSource.PSpecified pSource = PSource.PSpecified.DEFAULT; + if (oaepParams != null) { + pSource = new PSource.PSpecified(oaepParams); + } + + MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1"); + if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) { + if (EncryptionConstants.MGF1_SHA256.equals(mgfAlgorithm)) { + mgfParameterSpec = new MGF1ParameterSpec("SHA-256"); + } else if (EncryptionConstants.MGF1_SHA384.equals(mgfAlgorithm)) { + mgfParameterSpec = new MGF1ParameterSpec("SHA-384"); + } else if (EncryptionConstants.MGF1_SHA512.equals(mgfAlgorithm)) { + mgfParameterSpec = new MGF1ParameterSpec("SHA-512"); + } + } + return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource); + } + + return null; + } + + /** + * Construct a Cipher object + */ + private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException { + String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); + } + Cipher c; + try { + if (requestedJCEProvider == null) { + c = Cipher.getInstance(jceAlgorithm); + } else { + c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider); + } + } catch (NoSuchAlgorithmException nsae) { + // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested + // Some JDKs don't support RSA/ECB/OAEPPadding + if (XMLCipher.RSA_OAEP.equals(algorithm) + && (digestAlgorithm == null + || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) { try { - c.init(Cipher.UNWRAP_MODE, _key); - ret = c.unwrap(encryptedBytes, jceKeyAlgorithm, Cipher.SECRET_KEY); - - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); + if (requestedJCEProvider == null) { + c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); + } else { + c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider); + } + } catch (Exception ex) { + throw new XMLEncryptionException("empty", ex); } - - logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK"); - - return ret; - + } else { + throw new XMLEncryptionException("empty", nsae); + } + } catch (NoSuchProviderException nspre) { + throw new XMLEncryptionException("empty", nspre); + } catch (NoSuchPaddingException nspae) { + throw new XMLEncryptionException("empty", nspae); + } + + return c; } - /** - * Decrypt a key from a passed in EncryptedKey structure. This version - * is used mainly internally, when the cipher already has an - * EncryptedData loaded. The algorithm URI will be read from the - * EncryptedData - * - * @param encryptedKey Previously loaded EncryptedKey that needs - * to be decrypted. - * @return a key corresponding to the give type + /** + * Decrypt a key from a passed in EncryptedKey structure. This version + * is used mainly internally, when the cipher already has an + * EncryptedData loaded. The algorithm URI will be read from the + * EncryptedData + * + * @param encryptedKey Previously loaded EncryptedKey that needs + * to be decrypted. + * @return a key corresponding to the given type * @throws XMLEncryptionException - */ - - public Key decryptKey(EncryptedKey encryptedKey) throws - XMLEncryptionException { - - return decryptKey(encryptedKey, _ed.getEncryptionMethod().getAlgorithm()); - - } + */ + public Key decryptKey(EncryptedKey encryptedKey) throws XMLEncryptionException { + return decryptKey(encryptedKey, ed.getEncryptionMethod().getAlgorithm()); + } /** * Removes the contents of a Node. @@ -1407,7 +1592,7 @@ * @param node the Node to clear. */ private static void removeContent(Node node) { - while (node.hasChildNodes()) { + while (node.hasChildNodes()) { node.removeChild(node.getFirstChild()); } } @@ -1419,196 +1604,191 @@ * @return the Node as a result of the decrypt operation. * @throws XMLEncryptionException */ - private Document decryptElement(Element element) throws - XMLEncryptionException { - - logger.log(java.util.logging.Level.FINE, "Decrypting element..."); - - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); - - String octets; - try { - octets = new String(decryptToByteArray(element), "UTF-8"); - } catch (UnsupportedEncodingException uee) { - throw new XMLEncryptionException("empty", uee); - } - - - logger.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + octets); - - Node sourceParent = element.getParentNode(); - - DocumentFragment decryptedFragment = - _serializer.deserialize(octets, sourceParent); - + private Document decryptElement(Element element) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting element..."); + } - // The de-serialiser returns a fragment whose children we need to - // take on. + if (cipherMode != DECRYPT_MODE) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + } - if (sourceParent != null && sourceParent.getNodeType() == Node.DOCUMENT_NODE) { + byte[] octets = decryptToByteArray(element); - // If this is a content decryption, this may have problems + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets)); + } - _contextDocument.removeChild(_contextDocument.getDocumentElement()); - _contextDocument.appendChild(decryptedFragment); - } - else { - sourceParent.replaceChild(decryptedFragment, element); + Node sourceParent = element.getParentNode(); + Node decryptedNode = serializer.deserialize(octets, sourceParent); - } + // The de-serialiser returns a node whose children we need to take on. + if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) { + // If this is a content decryption, this may have problems + contextDocument.removeChild(contextDocument.getDocumentElement()); + contextDocument.appendChild(decryptedNode); + } else if (sourceParent != null) { + sourceParent.replaceChild(decryptedNode, element); + } - return (_contextDocument); + return contextDocument; } - - /** - * - * @param element - * @return + /** + * + * @param element + * @return the Node as a result of the decrypt operation. * @throws XMLEncryptionException - */ - private Document decryptElementContent(Element element) throws - XMLEncryptionException { - Element e = (Element) element.getElementsByTagNameNS( + */ + private Document decryptElementContent(Element element) throws XMLEncryptionException { + Element e = + (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA).item(0); + EncryptionConstants._TAG_ENCRYPTEDDATA + ).item(0); if (null == e) { - throw new XMLEncryptionException("No EncryptedData child element."); + throw new XMLEncryptionException("No EncryptedData child element."); } - return (decryptElement(e)); + return decryptElement(e); } - /** - * Decrypt an EncryptedData element to a byte array - * - * When passed in an EncryptedData node, returns the decryption - * as a byte array. - * - * Does not modify the source document + /** + * Decrypt an EncryptedData element to a byte array. + * + * When passed in an EncryptedData node, returns the decryption + * as a byte array. + * + * Does not modify the source document. * @param element - * @return + * @return the bytes resulting from the decryption * @throws XMLEncryptionException - */ - - public byte[] decryptToByteArray(Element element) - throws XMLEncryptionException { - - logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); - - if(_cipherMode != DECRYPT_MODE) - logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); - - EncryptedData encryptedData = _factory.newEncryptedData(element); - - if (_key == null) { - - KeyInfo ki = encryptedData.getKeyInfo(); + */ + public byte[] decryptToByteArray(Element element) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); + } - if (ki != null) { - try { - // Add a EncryptedKey resolver - ki.registerInternalKeyResolver( - new EncryptedKeyResolver(encryptedData. - getEncryptionMethod(). - getAlgorithm(), - _kek)); - _key = ki.getSecretKey(); - } catch (KeyResolverException kre) { - // We will throw in a second... - } - } + if (cipherMode != DECRYPT_MODE) { + log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE..."); + } - if (_key == null) { - logger.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptElement called without a key and unable to resolve"); + EncryptedData encryptedData = factory.newEncryptedData(element); - throw new XMLEncryptionException("encryption.nokey"); + if (key == null) { + KeyInfo ki = encryptedData.getKeyInfo(); + if (ki != null) { + try { + // Add an EncryptedKey resolver + String encMethodAlgorithm = encryptedData.getEncryptionMethod().getAlgorithm(); + EncryptedKeyResolver resolver = new EncryptedKeyResolver(encMethodAlgorithm, kek); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + resolver.registerInternalKeyResolver(internalKeyResolvers.get(i)); } + } + ki.registerInternalKeyResolver(resolver); + ki.setSecureValidation(secureValidation); + key = ki.getSecretKey(); + } catch (KeyResolverException kre) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, kre.getMessage(), kre); + } } + } - // Obtain the encrypted octets - XMLCipherInput cipherInput = new XMLCipherInput(encryptedData); - byte [] encryptedBytes = cipherInput.getBytes(); + if (key == null) { + log.log(java.util.logging.Level.SEVERE, + "XMLCipher::decryptElement called without a key and unable to resolve" + ); + throw new XMLEncryptionException("encryption.nokey"); + } + } - // Now create the working cipher + // Obtain the encrypted octets + XMLCipherInput cipherInput = new XMLCipherInput(encryptedData); + cipherInput.setSecureValidation(secureValidation); + byte[] encryptedBytes = cipherInput.getBytes(); + + // Now create the working cipher + String jceAlgorithm = + JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); + } - String jceAlgorithm = - JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm()); + Cipher c; + try { + if (requestedJCEProvider == null) { + c = Cipher.getInstance(jceAlgorithm); + } else { + c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider); + } + } catch (NoSuchAlgorithmException nsae) { + throw new XMLEncryptionException("empty", nsae); + } catch (NoSuchProviderException nspre) { + throw new XMLEncryptionException("empty", nspre); + } catch (NoSuchPaddingException nspae) { + throw new XMLEncryptionException("empty", nspae); + } - Cipher c; - try { - if (_requestedJCEProvider == null) - c = Cipher.getInstance(jceAlgorithm); - else - c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider); - } catch (NoSuchAlgorithmException nsae) { - throw new XMLEncryptionException("empty", nsae); - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - - // Calculate the IV length and copy out - - // For now, we only work with Block ciphers, so this will work. - // This should probably be put into the JCE mapper. - - int ivLen = c.getBlockSize(); - byte[] ivBytes = new byte[ivLen]; - - // You may be able to pass the entire piece in to IvParameterSpec - // and it will only take the first x bytes, but no way to be certain - // that this will work for every JCE provider, so lets copy the - // necessary bytes into a dedicated array. + // Calculate the IV length and copy out - System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); - IvParameterSpec iv = new IvParameterSpec(ivBytes); + // For now, we only work with Block ciphers, so this will work. + // This should probably be put into the JCE mapper. - try { - c.init(_cipherMode, _key, iv); - } catch (InvalidKeyException ike) { - throw new XMLEncryptionException("empty", ike); - } catch (InvalidAlgorithmParameterException iape) { - throw new XMLEncryptionException("empty", iape); - } + int ivLen = c.getBlockSize(); + String alg = encryptedData.getEncryptionMethod().getAlgorithm(); + if (AES_128_GCM.equals(alg) || AES_192_GCM.equals(alg) || AES_256_GCM.equals(alg)) { + ivLen = 12; + } + byte[] ivBytes = new byte[ivLen]; + + // You may be able to pass the entire piece in to IvParameterSpec + // and it will only take the first x bytes, but no way to be certain + // that this will work for every JCE provider, so lets copy the + // necessary bytes into a dedicated array. - byte[] plainBytes; + System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen); + IvParameterSpec iv = new IvParameterSpec(ivBytes); try { - plainBytes = c.doFinal(encryptedBytes, - ivLen, - encryptedBytes.length - ivLen); + c.init(cipherMode, key, iv); + } catch (InvalidKeyException ike) { + throw new XMLEncryptionException("empty", ike); + } catch (InvalidAlgorithmParameterException iape) { + throw new XMLEncryptionException("empty", iape); + } + try { + return c.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen); } catch (IllegalBlockSizeException ibse) { throw new XMLEncryptionException("empty", ibse); } catch (BadPaddingException bpe) { throw new XMLEncryptionException("empty", bpe); } - - return (plainBytes); } - /* - * Expose the interface for creating XML Encryption objects - */ + /* + * Expose the interface for creating XML Encryption objects + */ /** * Creates an EncryptedData Element. * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *

      - * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. + * The newEncryptedData and newEncryptedKey methods create fairly complete + * elements that are immediately useable. All the other create* methods + * return bare elements that still need to be built upon. + *

      + * An EncryptionMethod will still need to be added however + * + * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of + * CipherData this EncryptedData will contain. * @param value the Base 64 encoded, encrypted text to wrap in the * EncryptedData or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedData Element. * * * @throws XMLEncryptionException */ - - public EncryptedData createEncryptedData(int type, String value) throws - XMLEncryptionException { + public EncryptedData createEncryptedData(int type, String value) throws XMLEncryptionException { EncryptedData result = null; CipherData data = null; switch (type) { - case CipherData.REFERENCE_TYPE: - CipherReference cipherReference = _factory.newCipherReference( - value); - data = _factory.newCipherData(type); - data.setCipherReference(cipherReference); - result = _factory.newEncryptedData(data); - break; - case CipherData.VALUE_TYPE: - CipherValue cipherValue = _factory.newCipherValue(value); - data = _factory.newCipherData(type); - data.setCipherValue(cipherValue); - result = _factory.newEncryptedData(data); + case CipherData.REFERENCE_TYPE: + CipherReference cipherReference = factory.newCipherReference(value); + data = factory.newCipherData(type); + data.setCipherReference(cipherReference); + result = factory.newEncryptedData(data); + break; + case CipherData.VALUE_TYPE: + CipherValue cipherValue = factory.newCipherValue(value); + data = factory.newCipherData(type); + data.setCipherValue(cipherValue); + result = factory.newEncryptedData(data); } - return (result); + return result; } /** * Creates an EncryptedKey Element. * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *

      - * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. + * The newEncryptedData and newEncryptedKey methods create fairly complete + * elements that are immediately useable. All the other create* methods + * return bare elements that still need to be built upon. + *

      + * An EncryptionMethod will still need to be added however + * + * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of + * CipherData this EncryptedData will contain. * @param value the Base 64 encoded, encrypted text to wrap in the * EncryptedKey or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedKey Element. * * * @throws XMLEncryptionException */ - - public EncryptedKey createEncryptedKey(int type, String value) throws - XMLEncryptionException { + public EncryptedKey createEncryptedKey(int type, String value) throws XMLEncryptionException { EncryptedKey result = null; CipherData data = null; switch (type) { - case CipherData.REFERENCE_TYPE: - CipherReference cipherReference = _factory.newCipherReference( - value); - data = _factory.newCipherData(type); - data.setCipherReference(cipherReference); - result = _factory.newEncryptedKey(data); - break; - case CipherData.VALUE_TYPE: - CipherValue cipherValue = _factory.newCipherValue(value); - data = _factory.newCipherData(type); - data.setCipherValue(cipherValue); - result = _factory.newEncryptedKey(data); + case CipherData.REFERENCE_TYPE: + CipherReference cipherReference = factory.newCipherReference(value); + data = factory.newCipherData(type); + data.setCipherReference(cipherReference); + result = factory.newEncryptedKey(data); + break; + case CipherData.VALUE_TYPE: + CipherValue cipherValue = factory.newCipherValue(value); + data = factory.newCipherData(type); + data.setCipherValue(cipherValue); + result = factory.newEncryptedKey(data); } - return (result); + return result; } - /** - * Create an AgreementMethod object - * - * @param algorithm Algorithm of the agreement method - * @return - */ - - public AgreementMethod createAgreementMethod(String algorithm) { - return (_factory.newAgreementMethod(algorithm)); - } - - /** - * Create a CipherData object - * - * @param type Type of this CipherData (either VALUE_TUPE or - * REFERENCE_TYPE) - * @return - */ - - public CipherData createCipherData(int type) { - return (_factory.newCipherData(type)); - } - - /** - * Create a CipherReference object - * - * @return - * @param uri The URI that the reference will refer - */ - - public CipherReference createCipherReference(String uri) { - return (_factory.newCipherReference(uri)); - } - - /** - * Create a CipherValue element - * - * @param value The value to set the ciphertext to - * @return - */ - - public CipherValue createCipherValue(String value) { - return (_factory.newCipherValue(value)); - } - - /** - * Create an EncryptedMethod object - * - * @param algorithm Algorithm for the encryption - * @return - */ - public EncryptionMethod createEncryptionMethod(String algorithm) { - return (_factory.newEncryptionMethod(algorithm)); - } - - /** - * Create an EncryptedProperties element - * @return - */ - public EncryptionProperties createEncryptionProperties() { - return (_factory.newEncryptionProperties()); - } - - /** - * Create a new EncryptionProperty element - * @return - */ - public EncryptionProperty createEncryptionProperty() { - return (_factory.newEncryptionProperty()); - } - - /** - * Create a new ReferenceList object - * @return - * @param type - */ - public ReferenceList createReferenceList(int type) { - return (_factory.newReferenceList(type)); - } - - /** - * Create a new Transforms object - *

      - * Note: A context document must have been set - * elsewhere (possibly via a call to doFinal). If not, use the - * createTransforms(Document) method. - * @return - */ - - public Transforms createTransforms() { - return (_factory.newTransforms()); - } - - /** - * Create a new Transforms object - * - * Because the handling of Transforms is currently done in the signature - * code, the creation of a Transforms object requires a - * context document. - * - * @param doc Document that will own the created Transforms node - * @return - */ - public Transforms createTransforms(Document doc) { - return (_factory.newTransforms(doc)); - } + /** + * Create an AgreementMethod object + * + * @param algorithm Algorithm of the agreement method + * @return a new AgreementMethod + */ + public AgreementMethod createAgreementMethod(String algorithm) { + return factory.newAgreementMethod(algorithm); + } /** - * Converts Strings into Nodes and visa versa. - *

      - * NOTE: For internal use only. + * Create a CipherData object * - * @author Axl Mattheus + * @param type Type of this CipherData (either VALUE_TUPE or + * REFERENCE_TYPE) + * @return a new CipherData */ + public CipherData createCipherData(int type) { + return factory.newCipherData(type); + } - private class Serializer { - /** - * Initialize the XMLSerializer with the specified context - * Document. - *

      - * Setup OutputFormat in a way that the serialization does not - * modifiy the contents, that is it shall not do any pretty printing - * and so on. This would destroy the original content before - * encryption. If that content was signed before encryption and the - * serialization modifies the content the signature verification will - * fail. - */ - Serializer() { - } + /** + * Create a CipherReference object + * + * @param uri The URI that the reference will refer + * @return a new CipherReference + */ + public CipherReference createCipherReference(String uri) { + return factory.newCipherReference(uri); + } - /** - * Returns a String representation of the specified - * Document. - *

      - * Refer also to comments about setup of format. - * - * @param document the Document to serialize. - * @return the String representation of the serilaized - * Document. - * @throws Exception - */ - String serialize(Document document) throws Exception { - return canonSerialize(document); - } + /** + * Create a CipherValue element + * + * @param value The value to set the ciphertext to + * @return a new CipherValue + */ + public CipherValue createCipherValue(String value) { + return factory.newCipherValue(value); + } - /** - * Returns a String representation of the specified - * Element. - *

      - * Refer also to comments about setup of format. - * - * @param element the Element to serialize. - * @return the String representation of the serilaized - * Element. - * @throws Exception - */ - String serialize(Element element) throws Exception { - return canonSerialize(element); - } + /** + * Create an EncryptionMethod object + * + * @param algorithm Algorithm for the encryption + * @return a new EncryptionMethod + */ + public EncryptionMethod createEncryptionMethod(String algorithm) { + return factory.newEncryptionMethod(algorithm); + } - /** - * Returns a String representation of the specified - * NodeList. - *

      - * This is a special case because the NodeList may represent a - * DocumentFragment. A document fragement may be a - * non-valid XML document (refer to appropriate description of - * W3C) because it my start with a non-element node, e.g. a text - * node. - *

      - * The methods first converts the node list into a document fragment. - * Special care is taken to not destroy the current document, thus - * the method clones the nodes (deep cloning) before it appends - * them to the document fragment. - *

      - * Refer also to comments about setup of format. - * - * @param content the NodeList to serialize. - * @return the String representation of the serilaized - * NodeList. - * @throws Exception - */ - String serialize(NodeList content) throws Exception { //XMLEncryptionException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - _canon.setWriter(baos); - _canon.notReset(); - for (int i = 0; i < content.getLength(); i++) { - _canon.canonicalizeSubtree(content.item(i)); - } - baos.close(); - return baos.toString("UTF-8"); - } + /** + * Create an EncryptionProperties element + * @return a new EncryptionProperties + */ + public EncryptionProperties createEncryptionProperties() { + return factory.newEncryptionProperties(); + } - /** - * Use the Canoncializer to serialize the node - * @param node - * @return - * @throws Exception - */ - String canonSerialize(Node node) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - _canon.setWriter(baos); - _canon.notReset(); - _canon.canonicalizeSubtree(node); - baos.close(); - return baos.toString("UTF-8"); - } - /** - * @param source - * @param ctx - * @return - * @throws XMLEncryptionException - * - */ - DocumentFragment deserialize(String source, Node ctx) throws XMLEncryptionException { - DocumentFragment result; - final String tagname = "fragment"; - - // Create the context to parse the document against - StringBuffer sb; - - sb = new StringBuffer(); - sb.append("<"+tagname); - - // Run through each node up to the document node and find any - // xmlns: nodes - - Node wk = ctx; - - while (wk != null) { - - NamedNodeMap atts = wk.getAttributes(); - int length; - if (atts != null) - length = atts.getLength(); - else - length = 0; - - for (int i = 0 ; i < length ; ++i) { - Node att = atts.item(i); - if (att.getNodeName().startsWith("xmlns:") || - att.getNodeName().equals("xmlns")) { - - // Check to see if this node has already been found - Node p = ctx; - boolean found = false; - while (p != wk) { - NamedNodeMap tstAtts = p.getAttributes(); - if (tstAtts != null && - tstAtts.getNamedItem(att.getNodeName()) != null) { - found = true; - break; - } - p = p.getParentNode(); - } - if (found == false) { - - // This is an attribute node - sb.append(" " + att.getNodeName() + "=\"" + - att.getNodeValue() + "\""); - } - } - } - wk = wk.getParentNode(); - } - sb.append(">" + source + ""); - String fragment = sb.toString(); + /** + * Create a new EncryptionProperty element + * @return a new EncryptionProperty + */ + public EncryptionProperty createEncryptionProperty() { + return factory.newEncryptionProperty(); + } - try { - DocumentBuilderFactory dbf = - DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document d = db.parse( - new InputSource(new StringReader(fragment))); - - Element fragElt = (Element) _contextDocument.importNode( - d.getDocumentElement(), true); - result = _contextDocument.createDocumentFragment(); - Node child = fragElt.getFirstChild(); - while (child != null) { - fragElt.removeChild(child); - result.appendChild(child); - child = fragElt.getFirstChild(); - } - // String outp = serialize(d); - - } catch (SAXException se) { - throw new XMLEncryptionException("empty", se); - } catch (ParserConfigurationException pce) { - throw new XMLEncryptionException("empty", pce); - } catch (IOException ioe) { - throw new XMLEncryptionException("empty", ioe); - } + /** + * Create a new ReferenceList object + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList + */ + public ReferenceList createReferenceList(int type) { + return factory.newReferenceList(type); + } - return (result); - } + /** + * Create a new Transforms object + *

      + * Note: A context document must have been set + * elsewhere (possibly via a call to doFinal). If not, use the + * createTransforms(Document) method. + * @return a new Transforms + */ + public Transforms createTransforms() { + return factory.newTransforms(); } + /** + * Create a new Transforms object + * + * Because the handling of Transforms is currently done in the signature + * code, the creation of a Transforms object requires a + * context document. + * + * @param doc Document that will own the created Transforms node + * @return a new Transforms + */ + public Transforms createTransforms(Document doc) { + return factory.newTransforms(doc); + } /** * @@ -2020,201 +1994,110 @@ private class Factory { /** * @param algorithm - * @return - * + * @return a new AgreementMethod */ AgreementMethod newAgreementMethod(String algorithm) { - return (new AgreementMethodImpl(algorithm)); + return new AgreementMethodImpl(algorithm); } /** * @param type - * @return + * @return a new CipherData * */ CipherData newCipherData(int type) { - return (new CipherDataImpl(type)); + return new CipherDataImpl(type); } /** * @param uri - * @return - * + * @return a new CipherReference */ CipherReference newCipherReference(String uri) { - return (new CipherReferenceImpl(uri)); + return new CipherReferenceImpl(uri); } /** * @param value - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(String value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - /** - * - + /* CipherValue newCipherValue(byte[] value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - */ + */ + /** * @param data - * @return - * + * @return a new EncryptedData */ EncryptedData newEncryptedData(CipherData data) { - return (new EncryptedDataImpl(data)); + return new EncryptedDataImpl(data); } /** * @param data - * @return - * + * @return a new EncryptedKey */ EncryptedKey newEncryptedKey(CipherData data) { - return (new EncryptedKeyImpl(data)); + return new EncryptedKeyImpl(data); } /** * @param algorithm - * @return - * + * @return a new EncryptionMethod */ EncryptionMethod newEncryptionMethod(String algorithm) { - return (new EncryptionMethodImpl(algorithm)); - } - - /** - * @return - * - */ - EncryptionProperties newEncryptionProperties() { - return (new EncryptionPropertiesImpl()); - } - - /** - * @return - * - */ - EncryptionProperty newEncryptionProperty() { - return (new EncryptionPropertyImpl()); - } - - /** - * @param type - * @return - * - */ - ReferenceList newReferenceList(int type) { - return (new ReferenceListImpl(type)); - } - - /** - * @return - * - */ - Transforms newTransforms() { - return (new TransformsImpl()); - } - - /** - * @param doc - * @return - * - */ - Transforms newTransforms(Document doc) { - return (new TransformsImpl(doc)); + return new EncryptionMethodImpl(algorithm); } - /** - * @param element - * @return - * @throws XMLEncryptionException - * - */ - // - // - // - // - // - // - // - // - // - // - // - AgreementMethod newAgreementMethod(Element element) throws - XMLEncryptionException { - if (null == element) { - throw new NullPointerException("element is null"); - } - - String algorithm = element.getAttributeNS(null, - EncryptionConstants._ATT_ALGORITHM); - AgreementMethod result = newAgreementMethod(algorithm); - - Element kaNonceElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KA_NONCE).item(0); - if (null != kaNonceElement) { - result.setKANonce(kaNonceElement.getNodeValue().getBytes()); - } - // TODO: /////////////////////////////////////////////////////////// - // Figure out how to make this pesky line work.. - // - - // TODO: Work out how to handle relative URI - - Element originatorKeyInfoElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ORIGINATORKEYINFO).item(0); - if (null != originatorKeyInfoElement) { - try { - result.setOriginatorKeyInfo( - new KeyInfo(originatorKeyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - } + /** + * @return a new EncryptionProperties + */ + EncryptionProperties newEncryptionProperties() { + return new EncryptionPropertiesImpl(); + } - // TODO: Work out how to handle relative URI + /** + * @return a new EncryptionProperty + */ + EncryptionProperty newEncryptionProperty() { + return new EncryptionPropertyImpl(); + } - Element recipientKeyInfoElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_RECIPIENTKEYINFO).item(0); - if (null != recipientKeyInfoElement) { - try { - result.setRecipientKeyInfo( - new KeyInfo(recipientKeyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - } + /** + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList + */ + ReferenceList newReferenceList(int type) { + return new ReferenceListImpl(type); + } + + /** + * @return a new Transforms + */ + Transforms newTransforms() { + return new TransformsImpl(); + } - return (result); + /** + * @param doc + * @return a new Transforms + */ + Transforms newTransforms(Document doc) { + return new TransformsImpl(doc); } /** * @param element - * @return + * @return a new CipherData * @throws XMLEncryptionException - * */ - // - // - // - // - // - // - // - CipherData newCipherData(Element element) throws - XMLEncryptionException { + CipherData newCipherData(Element element) throws XMLEncryptionException { if (null == element) { throw new NullPointerException("element is null"); } @@ -2222,8 +2105,9 @@ int type = 0; Element e = null; if (element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0) { + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0 + ) { type = CipherData.VALUE_TYPE; e = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, @@ -2244,100 +2128,67 @@ result.setCipherReference(newCipherReference(e)); } - return (result); + return result; } /** * @param element - * @return + * @return a new CipherReference * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - CipherReference newCipherReference(Element element) throws - XMLEncryptionException { - - Attr URIAttr = - element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); - CipherReference result = new CipherReferenceImpl(URIAttr); + CipherReference newCipherReference(Element element) throws XMLEncryptionException { - // Find any Transforms + Attr uriAttr = + element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); + CipherReference result = new CipherReferenceImpl(uriAttr); - NodeList transformsElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_TRANSFORMS); - Element transformsElement = - (Element) transformsElements.item(0); - - if (transformsElement != null) { - logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); - try { - result.setTransforms(new TransformsImpl(transformsElement)); - } - catch (XMLSignatureException xse) { - throw new XMLEncryptionException("empty", xse); - } catch (InvalidTransformException ite) { - throw new XMLEncryptionException("empty", ite); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } + // Find any Transforms + NodeList transformsElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS); + Element transformsElement = (Element) transformsElements.item(0); - } + if (transformsElement != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); + } + try { + result.setTransforms(new TransformsImpl(transformsElement)); + } catch (XMLSignatureException xse) { + throw new XMLEncryptionException("empty", xse); + } catch (InvalidTransformException ite) { + throw new XMLEncryptionException("empty", ite); + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("empty", xse); + } + } - return result; + return result; } /** * @param element - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(Element element) { String value = XMLUtils.getFullTextChildrenFromElement(element); - CipherValue result = newCipherValue(value); - - return (result); + return newCipherValue(value); } /** * @param element - * @return + * @return a new EncryptedData * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - EncryptedData newEncryptedData(Element element) throws - XMLEncryptionException { + EncryptedData newEncryptedData(Element element) throws XMLEncryptionException { EncryptedData result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA); // Need to get the last CipherData found, as earlier ones will // be for elements in the KeyInfo lists @@ -2349,22 +2200,17 @@ result = newEncryptedData(data); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType( - element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding( - element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); + result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding( element.getAttributeNS(null, Constants._ATT_ENCODING)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod( - encryptionMethodElement)); + result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); } // BFL 16/7/03 - simple implementation @@ -2374,12 +2220,8 @@ (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("Error loading Key Info", - xse); - } + KeyInfo ki = newKeyInfo(keyInfoElement); + result.setKeyInfo(ki); } // TODO: Implement @@ -2389,85 +2231,49 @@ EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } - return (result); + return result; } /** * @param element - * @return + * @return a new EncryptedKey * @throws XMLEncryptionException - * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - EncryptedKey newEncryptedKey(Element element) throws - XMLEncryptionException { + EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException { EncryptedKey result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA); Element dataElement = (Element) dataElements.item(dataElements.getLength() - 1); CipherData data = newCipherData(dataElement); result = newEncryptedKey(data); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType( - element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding( - element.getAttributeNS(null, Constants._ATT_ENCODING)); - result.setRecipient(element.getAttributeNS( - null, EncryptionConstants._ATT_RECIPIENT)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); + result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding(element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setRecipient(element.getAttributeNS(null, EncryptionConstants._ATT_RECIPIENT)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod( - encryptionMethodElement)); + result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); } Element keyInfoElement = (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException - ("Error loading Key Info", xse); - } + KeyInfo ki = newKeyInfo(keyInfoElement); + result.setKeyInfo(ki); } // TODO: Implement @@ -2477,12 +2283,13 @@ EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } Element referenceListElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_REFERENCELIST).item(0); if (null != referenceListElement) { result.setReferenceList(newReferenceList(referenceListElement)); @@ -2493,34 +2300,44 @@ EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CARRIEDKEYNAME).item(0); if (null != carriedNameElement) { - result.setCarriedName - (carriedNameElement.getFirstChild().getNodeValue()); + result.setCarriedName(carriedNameElement.getFirstChild().getNodeValue()); } - return (result); + return result; } /** * @param element - * @return - * + * @return a new KeyInfo + * @throws XMLEncryptionException + */ + KeyInfo newKeyInfo(Element element) throws XMLEncryptionException { + try { + KeyInfo ki = new KeyInfo(element, null); + ki.setSecureValidation(secureValidation); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + ki.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + return ki; + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("Error loading Key Info", xse); + } + } + + /** + * @param element + * @return a new EncryptionMethod */ - // - // - // - // - // - // - // - // EncryptionMethod newEncryptionMethod(Element element) { - String algorithm = element.getAttributeNS( - null, EncryptionConstants._ATT_ALGORITHM); - EncryptionMethod result = newEncryptionMethod(algorithm); + String encAlgorithm = element.getAttributeNS(null, EncryptionConstants._ATT_ALGORITHM); + EncryptionMethod result = newEncryptionMethod(encAlgorithm); Element keySizeElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_KEYSIZE).item(0); if (null != keySizeElement) { result.setKeySize( @@ -2530,183 +2347,128 @@ Element oaepParamsElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_OAEPPARAMS).item(0); if (null != oaepParamsElement) { - result.setOAEPparams( - oaepParamsElement.getNodeValue().getBytes()); + try { + String oaepParams = oaepParamsElement.getFirstChild().getNodeValue(); + result.setOAEPparams(Base64.decode(oaepParams.getBytes("UTF-8"))); + } catch(UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported", e); + } catch (Base64DecodingException e) { + throw new RuntimeException("BASE-64 decoding error", e); + } + } + + Element digestElement = + (Element) element.getElementsByTagNameNS( + Constants.SignatureSpecNS, Constants._TAG_DIGESTMETHOD).item(0); + if (digestElement != null) { + String digestAlgorithm = digestElement.getAttributeNS(null, "Algorithm"); + result.setDigestAlgorithm(digestAlgorithm); + } + + Element mgfElement = + (Element) element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpec11NS, EncryptionConstants._TAG_MGF).item(0); + if (mgfElement != null && !XMLCipher.RSA_OAEP.equals(algorithm)) { + String mgfAlgorithm = mgfElement.getAttributeNS(null, "Algorithm"); + result.setMGFAlgorithm(mgfAlgorithm); } // TODO: Make this mess work // - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperties */ - // - // - // - // - // - // - // EncryptionProperties newEncryptionProperties(Element element) { EncryptionProperties result = newEncryptionProperties(); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); NodeList encryptionPropertyList = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONPROPERTY); - for(int i = 0; i < encryptionPropertyList.getLength(); i++) { + for (int i = 0; i < encryptionPropertyList.getLength(); i++) { Node n = encryptionPropertyList.item(i); if (null != n) { - result.addEncryptionProperty( - newEncryptionProperty((Element) n)); + result.addEncryptionProperty(newEncryptionProperty((Element) n)); } } - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperty */ - // - // - // - // - // - // - // - // - // EncryptionProperty newEncryptionProperty(Element element) { EncryptionProperty result = newEncryptionProperty(); - result.setTarget( - element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); + result.setTarget(element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); // TODO: Make this lot work... // // TODO: Make this work... // - return (result); + return result; } /** * @param element - * @return - * + * @return a new ReferenceList */ - // - // - // - // - // - // - // - // ReferenceList newReferenceList(Element element) { int type = 0; if (null != element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_DATAREFERENCE).item(0)) { type = ReferenceList.DATA_REFERENCE; } else if (null != element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_KEYREFERENCE).item(0)) { type = ReferenceList.KEY_REFERENCE; - } else { - // complain } ReferenceList result = new ReferenceListImpl(type); NodeList list = null; switch (type) { case ReferenceList.DATA_REFERENCE: - list = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_DATAREFERENCE); + list = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_DATAREFERENCE); for (int i = 0; i < list.getLength() ; i++) { String uri = ((Element) list.item(i)).getAttribute("URI"); result.add(result.newDataReference(uri)); } break; case ReferenceList.KEY_REFERENCE: - list = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYREFERENCE); + list = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_KEYREFERENCE); for (int i = 0; i < list.getLength() ; i++) { String uri = ((Element) list.item(i)).getAttribute("URI"); result.add(result.newKeyReference(uri)); } } - return (result); - } - - /** - * @param element - * @return - * - */ - Transforms newTransforms(Element element) { - return (null); - } - - /** - * @param agreementMethod - * @return - * - */ - Element toElement(AgreementMethod agreementMethod) { - return ((AgreementMethodImpl) agreementMethod).toElement(); - } - - /** - * @param cipherData - * @return - * - */ - Element toElement(CipherData cipherData) { - return ((CipherDataImpl) cipherData).toElement(); - } - - /** - * @param cipherReference - * @return - * - */ - Element toElement(CipherReference cipherReference) { - return ((CipherReferenceImpl) cipherReference).toElement(); - } - - /** - * @param cipherValue - * @return - * - */ - Element toElement(CipherValue cipherValue) { - return ((CipherValueImpl) cipherValue).toElement(); + return result; } /** * @param encryptedData - * @return - * + * @return the XML Element form of that EncryptedData */ Element toElement(EncryptedData encryptedData) { return ((EncryptedDataImpl) encryptedData).toElement(); @@ -2714,64 +2476,20 @@ /** * @param encryptedKey - * @return - * + * @return the XML Element form of that EncryptedKey */ Element toElement(EncryptedKey encryptedKey) { return ((EncryptedKeyImpl) encryptedKey).toElement(); } - - /** - * @param encryptionMethod - * @return - * - */ - Element toElement(EncryptionMethod encryptionMethod) { - return ((EncryptionMethodImpl) encryptionMethod).toElement(); - } - - /** - * @param encryptionProperties - * @return - * - */ - Element toElement(EncryptionProperties encryptionProperties) { - return ((EncryptionPropertiesImpl) encryptionProperties).toElement(); - } - + /** - * @param encryptionProperty - * @return - * + * @param referenceList + * @return the XML Element form of that ReferenceList */ - Element toElement(EncryptionProperty encryptionProperty) { - return ((EncryptionPropertyImpl) encryptionProperty).toElement(); - } - Element toElement(ReferenceList referenceList) { return ((ReferenceListImpl) referenceList).toElement(); } - /** - * @param transforms - * @return - * - */ - Element toElement(Transforms transforms) { - return ((TransformsImpl) transforms).toElement(); - } - - // - // - // - // - // - // - // - // - // - // - // private class AgreementMethodImpl implements AgreementMethod { private byte[] kaNonce = null; private List agreementMethodInformation = null; @@ -2787,15 +2505,16 @@ URI tmpAlgorithm = null; try { tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException fmue) { - //complain? + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } algorithmURI = tmpAlgorithm.toString(); } /** @inheritDoc */ public byte[] getKANonce() { - return (kaNonce); + return kaNonce; } /** @inheritDoc */ @@ -2805,7 +2524,7 @@ /** @inheritDoc */ public Iterator getAgreementMethodInformation() { - return (agreementMethodInformation.iterator()); + return agreementMethodInformation.iterator(); } /** @inheritDoc */ @@ -2820,7 +2539,7 @@ /** @inheritDoc */ public KeyInfo getOriginatorKeyInfo() { - return (originatorKeyInfo); + return originatorKeyInfo; } /** @inheritDoc */ @@ -2830,7 +2549,7 @@ /** @inheritDoc */ public KeyInfo getRecipientKeyInfo() { - return (recipientKeyInfo); + return recipientKeyInfo; } /** @inheritDoc */ @@ -2840,70 +2559,10 @@ /** @inheritDoc */ public String getAlgorithm() { - return (algorithmURI); - } - - /** @param algorithm*/ - public void setAlgorithm(String algorithm) { - URI tmpAlgorithm = null; - try { - tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException mfue) { - //complain - } - algorithmURI = tmpAlgorithm.toString(); - } - - // - // - // - // - // - // - // - // - // - // - // - Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_AGREEMENTMETHOD); - result.setAttributeNS( - null, EncryptionConstants._ATT_ALGORITHM, algorithmURI); - if (null != kaNonce) { - result.appendChild( - ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KA_NONCE)).appendChild( - _contextDocument.createTextNode(new String(kaNonce))); - } - if (!agreementMethodInformation.isEmpty()) { - Iterator itr = agreementMethodInformation.iterator(); - while (itr.hasNext()) { - result.appendChild(itr.next()); - } - } - if (null != originatorKeyInfo) { - result.appendChild(originatorKeyInfo.getElement()); - } - if (null != recipientKeyInfo) { - result.appendChild(recipientKeyInfo.getElement()); - } - - return (result); + return algorithmURI; } } - // - // - // - // - // - // - // private class CipherDataImpl implements CipherData { private static final String valueMessage = "Data type is reference type."; @@ -2922,16 +2581,16 @@ /** @inheritDoc */ public CipherValue getCipherValue() { - return (cipherValue); + return cipherValue; } /** @inheritDoc */ - public void setCipherValue(CipherValue value) throws - XMLEncryptionException { + public void setCipherValue(CipherValue value) throws XMLEncryptionException { if (cipherType == REFERENCE_TYPE) { - throw new XMLEncryptionException("empty", - new UnsupportedOperationException(valueMessage)); + throw new XMLEncryptionException( + "empty", new UnsupportedOperationException(valueMessage) + ); } cipherValue = value; @@ -2939,15 +2598,16 @@ /** @inheritDoc */ public CipherReference getCipherReference() { - return (cipherReference); + return cipherReference; } /** @inheritDoc */ public void setCipherReference(CipherReference reference) throws - XMLEncryptionException { + XMLEncryptionException { if (cipherType == VALUE_TYPE) { - throw new XMLEncryptionException("empty", - new UnsupportedOperationException(referenceMessage)); + throw new XMLEncryptionException( + "empty", new UnsupportedOperationException(referenceMessage) + ); } cipherReference = reference; @@ -2955,77 +2615,59 @@ /** @inheritDoc */ public int getDataType() { - return (cipherType); + return cipherType; } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERDATA + ); if (cipherType == VALUE_TYPE) { - result.appendChild( - ((CipherValueImpl) cipherValue).toElement()); + result.appendChild(((CipherValueImpl) cipherValue).toElement()); } else if (cipherType == REFERENCE_TYPE) { - result.appendChild( - ((CipherReferenceImpl) cipherReference).toElement()); - } else { - // complain + result.appendChild(((CipherReferenceImpl) cipherReference).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class CipherReferenceImpl implements CipherReference { private String referenceURI = null; private Transforms referenceTransforms = null; - private Attr referenceNode = null; + private Attr referenceNode = null; /** * @param uri */ public CipherReferenceImpl(String uri) { - /* Don't check validity of URI as may be "" */ + /* Don't check validity of URI as may be "" */ referenceURI = uri; - referenceNode = null; + referenceNode = null; } - /** - * @param uri - */ - public CipherReferenceImpl(Attr uri) { - referenceURI = uri.getNodeValue(); - referenceNode = uri; - } + /** + * @param uri + */ + public CipherReferenceImpl(Attr uri) { + referenceURI = uri.getNodeValue(); + referenceNode = uri; + } /** @inheritDoc */ public String getURI() { - return (referenceURI); + return referenceURI; } /** @inheritDoc */ - public Attr getURIAsAttr() { - return (referenceNode); - } + public Attr getURIAsAttr() { + return referenceNode; + } /** @inheritDoc */ public Transforms getTransforms() { - return (referenceTransforms); + return referenceTransforms; } /** @inheritDoc */ @@ -3033,91 +2675,53 @@ referenceTransforms = transforms; } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERREFERENCE); - result.setAttributeNS( - null, EncryptionConstants._ATT_URI, referenceURI); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE + ); + result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI); if (null != referenceTransforms) { - result.appendChild( - ((TransformsImpl) referenceTransforms).toElement()); + result.appendChild(((TransformsImpl) referenceTransforms).toElement()); } - return (result); + return result; } } private class CipherValueImpl implements CipherValue { - private String cipherValue = null; - - // public CipherValueImpl(byte[] value) { - // cipherValue = value; - // } + private String cipherValue = null; /** * @param value */ public CipherValueImpl(String value) { - // cipherValue = value.getBytes(); - cipherValue = value; + cipherValue = value; } /** @inheritDoc */ - public String getValue() { - return (cipherValue); + public String getValue() { + return cipherValue; } - // public void setValue(byte[] value) { - // public void setValue(String value) { - // cipherValue = value; - // } - /** @inheritDoc */ + /** @inheritDoc */ public void setValue(String value) { - // cipherValue = value.getBytes(); - cipherValue = value; + cipherValue = value; } Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE); - result.appendChild(_contextDocument.createTextNode( - cipherValue)); - - return (result); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERVALUE + ); + result.appendChild(contextDocument.createTextNode(cipherValue)); + + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedDataImpl extends EncryptedTypeImpl implements - EncryptedData { + private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData { + /** * @param data */ @@ -3125,94 +2729,49 @@ super(data); } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA); + Element result = + ElementProxy.createElementForFamily( + contextDocument, EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDDATA + ); if (null != super.getId()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ID, super.getId()); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); } if (null != super.getType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, super.getType()); + result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { result.setAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE, - super.getMimeType()); + null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() + ); } if (null != super.getEncoding()) { result.setAttributeNS( - null, EncryptionConstants._ATT_ENCODING, - super.getEncoding()); + null, EncryptionConstants._ATT_ENCODING, super.getEncoding() + ); } if (null != super.getEncryptionMethod()) { - result.appendChild(((EncryptionMethodImpl) - super.getEncryptionMethod()).toElement()); + result.appendChild( + ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement() + ); } if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement()); + result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); } - result.appendChild( - ((CipherDataImpl) super.getCipherData()).toElement()); + result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); if (null != super.getEncryptionProperties()) { result.appendChild(((EncryptionPropertiesImpl) super.getEncryptionProperties()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedKeyImpl extends EncryptedTypeImpl implements - EncryptedKey { + private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey { private String keyRecipient = null; private ReferenceList referenceList = null; private String carriedName = null; @@ -3226,7 +2785,7 @@ /** @inheritDoc */ public String getRecipient() { - return (keyRecipient); + return keyRecipient; } /** @inheritDoc */ @@ -3236,7 +2795,7 @@ /** @inheritDoc */ public ReferenceList getReferenceList() { - return (referenceList); + return referenceList; } /** @inheritDoc */ @@ -3246,7 +2805,7 @@ /** @inheritDoc */ public String getCarriedName() { - return (carriedName); + return carriedName; } /** @inheritDoc */ @@ -3254,84 +2813,60 @@ carriedName = name; } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDKEY); + Element result = + ElementProxy.createElementForFamily( + contextDocument, EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDKEY + ); if (null != super.getId()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ID, super.getId()); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); } if (null != super.getType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, super.getType()); + result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { - result.setAttributeNS(null, - EncryptionConstants._ATT_MIMETYPE, super.getMimeType()); + result.setAttributeNS( + null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() + ); } if (null != super.getEncoding()) { - result.setAttributeNS(null, Constants._ATT_ENCODING, - super.getEncoding()); + result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding()); } if (null != getRecipient()) { - result.setAttributeNS(null, - EncryptionConstants._ATT_RECIPIENT, getRecipient()); + result.setAttributeNS( + null, EncryptionConstants._ATT_RECIPIENT, getRecipient() + ); } if (null != super.getEncryptionMethod()) { result.appendChild(((EncryptionMethodImpl) super.getEncryptionMethod()).toElement()); } if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement()); + result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); } - result.appendChild( - ((CipherDataImpl) super.getCipherData()).toElement()); + result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); if (null != super.getEncryptionProperties()) { result.appendChild(((EncryptionPropertiesImpl) super.getEncryptionProperties()).toElement()); } if (referenceList != null && !referenceList.isEmpty()) { - result.appendChild(((ReferenceListImpl) - getReferenceList()).toElement()); + result.appendChild(((ReferenceListImpl)getReferenceList()).toElement()); } if (null != carriedName) { - Element element = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CARRIEDKEYNAME); - Node node = _contextDocument.createTextNode(carriedName); + Element element = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_CARRIEDKEYNAME + ); + Node node = contextDocument.createTextNode(carriedName); element.appendChild(node); result.appendChild(element); } - return (result); + return result; } } @@ -3345,32 +2880,40 @@ private CipherData cipherData = null; private EncryptionProperties encryptionProperties = null; + /** + * Constructor. + * @param data + */ protected EncryptedTypeImpl(CipherData data) { cipherData = data; } - /** - * - * @return + + /** + * + * @return the Id */ public String getId() { - return (id); + return id; } + /** - * + * * @param id */ public void setId(String id) { this.id = id; } + /** - * - * @return + * + * @return the type */ public String getType() { - return (type); + return type; } + /** - * + * * @param type */ public void setType(String type) { @@ -3380,35 +2923,39 @@ URI tmpType = null; try { tmpType = new URI(type); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.type = tmpType.toString(); } } + /** - * - * @return + * + * @return the MimeType */ public String getMimeType() { - return (mimeType); + return mimeType; } /** - * + * * @param type */ public void setMimeType(String type) { mimeType = type; } + /** - * - * @return + * + * @return the encoding */ public String getEncoding() { - return (encoding); + return encoding; } + /** - * + * * @param encoding */ public void setEncoding(String encoding) { @@ -3418,251 +2965,274 @@ URI tmpEncoding = null; try { tmpEncoding = new URI(encoding); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.encoding = tmpEncoding.toString(); } } + /** - * - * @return + * + * @return the EncryptionMethod */ public EncryptionMethod getEncryptionMethod() { - return (encryptionMethod); + return encryptionMethod; } + /** - * + * * @param method */ public void setEncryptionMethod(EncryptionMethod method) { encryptionMethod = method; } + /** - * - * @return + * + * @return the KeyInfo */ public KeyInfo getKeyInfo() { - return (keyInfo); + return keyInfo; } + /** - * + * * @param info */ public void setKeyInfo(KeyInfo info) { keyInfo = info; } + /** - * - * @return + * + * @return the CipherData */ public CipherData getCipherData() { - return (cipherData); + return cipherData; } + /** - * - * @return + * + * @return the EncryptionProperties */ public EncryptionProperties getEncryptionProperties() { - return (encryptionProperties); + return encryptionProperties; } + /** - * + * * @param properties */ - public void setEncryptionProperties( - EncryptionProperties properties) { + public void setEncryptionProperties(EncryptionProperties properties) { encryptionProperties = properties; } } - // - // - // - // - // - // - // - // private class EncryptionMethodImpl implements EncryptionMethod { private String algorithm = null; private int keySize = Integer.MIN_VALUE; private byte[] oaepParams = null; private List encryptionMethodInformation = null; + private String digestAlgorithm = null; + private String mgfAlgorithm = null; + /** - * + * Constructor. * @param algorithm */ public EncryptionMethodImpl(String algorithm) { URI tmpAlgorithm = null; try { tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.algorithm = tmpAlgorithm.toString(); encryptionMethodInformation = new LinkedList(); } + /** @inheritDoc */ public String getAlgorithm() { - return (algorithm); + return algorithm; } + /** @inheritDoc */ public int getKeySize() { - return (keySize); + return keySize; } + /** @inheritDoc */ public void setKeySize(int size) { keySize = size; } + /** @inheritDoc */ public byte[] getOAEPparams() { - return (oaepParams); + return oaepParams; } + /** @inheritDoc */ public void setOAEPparams(byte[] params) { oaepParams = params; } + + /** @inheritDoc */ + public void setDigestAlgorithm(String digestAlgorithm) { + this.digestAlgorithm = digestAlgorithm; + } + + /** @inheritDoc */ + public String getDigestAlgorithm() { + return digestAlgorithm; + } + + /** @inheritDoc */ + public void setMGFAlgorithm(String mgfAlgorithm) { + this.mgfAlgorithm = mgfAlgorithm; + } + + /** @inheritDoc */ + public String getMGFAlgorithm() { + return mgfAlgorithm; + } + /** @inheritDoc */ public Iterator getEncryptionMethodInformation() { - return (encryptionMethodInformation.iterator()); + return encryptionMethodInformation.iterator(); } + /** @inheritDoc */ public void addEncryptionMethodInformation(Element info) { encryptionMethodInformation.add(info); } + /** @inheritDoc */ public void removeEncryptionMethodInformation(Element info) { encryptionMethodInformation.remove(info); } - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONMETHOD); - result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, - algorithm); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD + ); + result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm); if (keySize > 0) { result.appendChild( - ElementProxy.createElementForFamily(_contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYSIZE).appendChild( - _contextDocument.createTextNode( - String.valueOf(keySize)))); + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_KEYSIZE + ).appendChild(contextDocument.createTextNode(String.valueOf(keySize)))); } if (null != oaepParams) { - result.appendChild( - ElementProxy.createElementForFamily(_contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_OAEPPARAMS).appendChild( - _contextDocument.createTextNode( - new String(oaepParams)))); + Element oaepElement = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_OAEPPARAMS + ); + oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams))); + result.appendChild(oaepElement); + } + if (digestAlgorithm != null) { + Element digestElement = + XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD); + digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm); + result.appendChild(digestElement); + } + if (mgfAlgorithm != null) { + Element mgfElement = + XMLUtils.createElementInEncryption11Space( + contextDocument, EncryptionConstants._TAG_MGF + ); + mgfElement.setAttributeNS(null, "Algorithm", mgfAlgorithm); + mgfElement.setAttributeNS( + Constants.NamespaceSpecNS, + "xmlns:" + ElementProxy.getDefaultPrefix(EncryptionConstants.EncryptionSpec11NS), + EncryptionConstants.EncryptionSpec11NS + ); + result.appendChild(mgfElement); } - if (!encryptionMethodInformation.isEmpty()) { - Iterator itr = encryptionMethodInformation.iterator(); + Iterator itr = encryptionMethodInformation.iterator(); + while (itr.hasNext()) { result.appendChild(itr.next()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class EncryptionPropertiesImpl implements EncryptionProperties { private String id = null; private List encryptionProperties = null; + /** - * - * + * Constructor. */ public EncryptionPropertiesImpl() { encryptionProperties = new LinkedList(); } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public Iterator getEncryptionProperties() { - return (encryptionProperties.iterator()); + return encryptionProperties.iterator(); } + /** @inheritDoc */ public void addEncryptionProperty(EncryptionProperty property) { encryptionProperties.add(property); } + /** @inheritDoc */ public void removeEncryptionProperty(EncryptionProperty property) { encryptionProperties.remove(property); } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTIES); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTIES + ); if (null != id) { result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); } Iterator itr = getEncryptionProperties(); while (itr.hasNext()) { - result.appendChild(((EncryptionPropertyImpl) - itr.next()).toElement()); + result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // private class EncryptionPropertyImpl implements EncryptionProperty { private String target = null; private String id = null; - private HashMap attributeMap = new HashMap(); + private Map attributeMap = new HashMap(); private List encryptionInformation = null; /** - * - * + * Constructor. */ public EncryptionPropertyImpl() { encryptionInformation = new LinkedList(); } + /** @inheritDoc */ public String getTarget() { - return (target); + return target; } + /** @inheritDoc */ public void setTarget(String target) { if (target == null || target.length() == 0) { @@ -3670,163 +3240,144 @@ } else if (target.startsWith("#")) { /* * This is a same document URI reference. Do not parse, - * because com.sun.org.apache.xml.internal.utils.URI considers this an - * illegal URI because it has no scheme. + * because it has no scheme. */ this.target = target; } else { URI tmpTarget = null; try { tmpTarget = new URI(target); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.target = tmpTarget.toString(); } } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public String getAttribute(String attribute) { return attributeMap.get(attribute); } + /** @inheritDoc */ public void setAttribute(String attribute, String value) { attributeMap.put(attribute, value); } + /** @inheritDoc */ public Iterator getEncryptionInformation() { - return (encryptionInformation.iterator()); + return encryptionInformation.iterator(); } + /** @inheritDoc */ public void addEncryptionInformation(Element info) { encryptionInformation.add(info); } + /** @inheritDoc */ public void removeEncryptionInformation(Element info) { encryptionInformation.remove(info); } - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTY); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTY + ); if (null != target) { - result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, - target); + result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, target); } if (null != id) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, - id); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); } // TODO: figure out the anyAttribyte stuff... // TODO: figure out the any stuff... - return (result); + return result; } } - // - // - // - // - // - private class TransformsImpl extends - com.sun.org.apache.xml.internal.security.transforms.Transforms - implements Transforms { - - /** - * Construct Transforms - */ + private class TransformsImpl extends com.sun.org.apache.xml.internal.security.transforms.Transforms + implements Transforms { - public TransformsImpl() { - super(_contextDocument); - } - /** - * - * @param doc - */ - public TransformsImpl(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - this._doc = doc; - this._constructionElement = createElementForFamilyLocal(this._doc, - this.getBaseNamespace(), this.getBaseLocalName()); - } - /** - * - * @param element - * @throws XMLSignatureException - * @throws InvalidTransformException - * @throws XMLSecurityException - * @throws TransformationException - */ - public TransformsImpl(Element element) - throws XMLSignatureException, - InvalidTransformException, - XMLSecurityException, - TransformationException { + /** + * Construct Transforms + */ + public TransformsImpl() { + super(contextDocument); + } - super(element, ""); + /** + * + * @param doc + */ + public TransformsImpl(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - } + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal( + this.doc, this.getBaseNamespace(), this.getBaseLocalName() + ); + } /** - * - * @return + * + * @param element + * @throws XMLSignatureException + * @throws InvalidTransformException + * @throws XMLSecurityException + * @throws TransformationException */ - public Element toElement() { + public TransformsImpl(Element element) + throws XMLSignatureException, InvalidTransformException, + XMLSecurityException, TransformationException { + super(element, ""); + } - if (_doc == null) - _doc = _contextDocument; + /** + * + * @return the XML Element form of that Transforms + */ + public Element toElement() { + if (doc == null) { + doc = contextDocument; + } - return getElement(); - } + return getElement(); + } /** @inheritDoc */ - public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { - return (this); - } - + public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { + return this; + } - // Over-ride the namespace + // Over-ride the namespace /** @inheritDoc */ - public String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } - + public String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } - // - // - // - // - // - // - // - // private class ReferenceListImpl implements ReferenceList { private Class sentry; private List references; + /** - * + * Constructor. * @param type */ public ReferenceListImpl(int type) { @@ -3839,13 +3390,15 @@ } references = new LinkedList(); } + /** @inheritDoc */ public void add(Reference reference) { if (!reference.getClass().equals(sentry)) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(); } - references.add(reference); + references.add(reference); } + /** @inheritDoc */ public void remove(Reference reference) { if (!reference.getClass().equals(sentry)) { @@ -3853,39 +3406,45 @@ } references.remove(reference); } + /** @inheritDoc */ public int size() { - return (references.size()); + return references.size(); } + /** @inheritDoc */ public boolean isEmpty() { - return (references.isEmpty()); + return references.isEmpty(); } + /** @inheritDoc */ public Iterator getReferences() { - return (references.iterator()); + return references.iterator(); } Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_REFERENCELIST); + Element result = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_REFERENCELIST + ); Iterator eachReference = references.iterator(); while (eachReference.hasNext()) { Reference reference = eachReference.next(); - result.appendChild( - ((ReferenceImpl) reference).toElement()); + result.appendChild(((ReferenceImpl) reference).toElement()); } - return (result); + return result; } + /** @inheritDoc */ public Reference newDataReference(String uri) { - return (new DataReference(uri)); + return new DataReference(uri); } + /** @inheritDoc */ public Reference newKeyReference(String uri) { - return (new KeyReference(uri)); + return new KeyReference(uri); } /** @@ -3898,68 +3457,81 @@ private String uri; private List referenceInformation; - ReferenceImpl(String _uri) { - this.uri = _uri; + ReferenceImpl(String uri) { + this.uri = uri; referenceInformation = new LinkedList(); } + + /** @inheritDoc */ + public abstract String getType(); + /** @inheritDoc */ public String getURI() { - return (uri); + return uri; } + /** @inheritDoc */ public Iterator getElementRetrievalInformation() { - return (referenceInformation.iterator()); + return referenceInformation.iterator(); } + /** @inheritDoc */ - public void setURI(String _uri) { - this.uri = _uri; + public void setURI(String uri) { + this.uri = uri; } + /** @inheritDoc */ public void removeElementRetrievalInformation(Element node) { referenceInformation.remove(node); } + /** @inheritDoc */ public void addElementRetrievalInformation(Element node) { referenceInformation.add(node); } + /** - * - * @return + * @return the XML Element form of that Reference */ - public abstract Element toElement(); - - Element toElement(String tagName) { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - tagName); + public Element toElement() { + String tagName = getType(); + Element result = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + tagName + ); result.setAttribute(EncryptionConstants._ATT_URI, uri); // TODO: Need to martial referenceInformation // Figure out how to make this work.. // - return (result); + return result; } } private class DataReference extends ReferenceImpl { + DataReference(String uri) { super(uri); } + /** @inheritDoc */ - public Element toElement() { - return super.toElement(EncryptionConstants._TAG_DATAREFERENCE); + public String getType() { + return EncryptionConstants._TAG_DATAREFERENCE; } } private class KeyReference extends ReferenceImpl { + KeyReference(String uri) { - super (uri); + super(uri); } + /** @inheritDoc */ - public Element toElement() { - return super.toElement(EncryptionConstants._TAG_KEYREFERENCE); + public String getType() { + return EncryptionConstants._TAG_KEYREFERENCE; } } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java 2013-06-28 11:33:23.638737781 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java 2013-06-28 11:33:23.462743259 -0400 @@ -2,23 +2,24 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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.encryption; import java.io.IOException; @@ -32,7 +33,6 @@ import org.w3c.dom.Attr; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * XMLCipherInput is used to wrap input passed into the * XMLCipher encryption operations. @@ -49,78 +49,80 @@ */ public class XMLCipherInput { - private static java.util.logging.Logger logger = - java.util.logging.Logger.getLogger(XMLCipher.class.getName()); + private static java.util.logging.Logger logger = + java.util.logging.Logger.getLogger(XMLCipherInput.class.getName()); - /** The data we are working with */ - private CipherData _cipherData; + /** The data we are working with */ + private CipherData cipherData; - /** MODES */ - private int _mode; - - /** - * Constructor for processing encrypted octets - * - * @param data The CipherData object to read the bytes from - * @throws XMLEncryptionException {@link XMLEncryptionException} - */ - - public XMLCipherInput(CipherData data) throws XMLEncryptionException { - - _cipherData = data; - _mode = XMLCipher.DECRYPT_MODE; - if (_cipherData == null) { - throw new XMLEncryptionException("CipherData is null"); - } + /** MODES */ + private int mode; + + private boolean secureValidation; + /** + * Constructor for processing encrypted octets + * + * @param data The CipherData object to read the bytes from + * @throws XMLEncryptionException {@link XMLEncryptionException} + */ + public XMLCipherInput(CipherData data) throws XMLEncryptionException { + cipherData = data; + mode = XMLCipher.DECRYPT_MODE; + if (cipherData == null) { + throw new XMLEncryptionException("CipherData is null"); } + } - /** - * Constructor for processing encrypted octets - * - * @param input The EncryptedType object to read - * the bytes from. - * @throws XMLEncryptionException {@link XMLEncryptionException} - */ - - public XMLCipherInput(EncryptedType input) throws XMLEncryptionException { - - _cipherData = ((input == null) ? null : input.getCipherData()); - _mode = XMLCipher.DECRYPT_MODE; - if (_cipherData == null) { - throw new XMLEncryptionException("CipherData is null"); - } - + /** + * Constructor for processing encrypted octets + * + * @param input The EncryptedType object to read + * the bytes from. + * @throws XMLEncryptionException {@link XMLEncryptionException} + */ + public XMLCipherInput(EncryptedType input) throws XMLEncryptionException { + cipherData = ((input == null) ? null : input.getCipherData()); + mode = XMLCipher.DECRYPT_MODE; + if (cipherData == null) { + throw new XMLEncryptionException("CipherData is null"); } + } + + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } - /** - * Dereferences the input and returns it as a single byte array. - * - * @throws XMLEncryptionException + /** + * Dereferences the input and returns it as a single byte array. + * + * @throws XMLEncryptionException * @return The decripted bytes. - */ - - public byte[] getBytes() throws XMLEncryptionException { - - if (_mode == XMLCipher.DECRYPT_MODE) { - return getDecryptBytes(); - } - return null; + */ + public byte[] getBytes() throws XMLEncryptionException { + if (mode == XMLCipher.DECRYPT_MODE) { + return getDecryptBytes(); } + return null; + } /** * Internal method to get bytes in decryption mode - * @return the decripted bytes + * @return the decrypted bytes * @throws XMLEncryptionException */ private byte[] getDecryptBytes() throws XMLEncryptionException { - String base64EncodedEncryptedOctets = null; - if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) { + if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) { // Fun time! - logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); - CipherReference cr = _cipherData.getCipherReference(); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); + } + CipherReference cr = cipherData.getCipherReference(); // Need to wrap the uri in an Attribute node so that we can // Pass to the resource resolvers @@ -129,26 +131,33 @@ XMLSignatureInput input = null; try { - ResourceResolver resolver = - ResourceResolver.getInstance(uriAttr, null); - input = resolver.resolve(uriAttr, null); + ResourceResolver resolver = + ResourceResolver.getInstance(uriAttr, null, secureValidation); + input = resolver.resolve(uriAttr, null, secureValidation); } catch (ResourceResolverException ex) { throw new XMLEncryptionException("empty", ex); - } + } if (input != null) { - logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + } } else { - logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + } } // Lets see if there are any transforms Transforms transforms = cr.getTransforms(); if (transforms != null) { - logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + } try { com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms = transforms.getDSTransforms(); + dsTransforms.setSecureValidation(secureValidation); input = dsTransforms.performTransforms(input); } catch (TransformationException ex) { throw new XMLEncryptionException("empty", ex); @@ -163,23 +172,21 @@ throw new XMLEncryptionException("empty", ex); } - // retrieve the cipher text - } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) { - base64EncodedEncryptedOctets = - _cipherData.getCipherValue().getValue(); + // retrieve the cipher text + } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) { + base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue(); } else { throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); } - logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + } - byte[] encryptedBytes = null; try { - encryptedBytes = Base64.decode(base64EncodedEncryptedOctets); + return Base64.decode(base64EncodedEncryptedOctets); } catch (Base64DecodingException bde) { throw new XMLEncryptionException("empty", bde); } - - return (encryptedBytes); } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java 2013-06-28 11:33:24.326716366 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java 2013-06-28 11:33:24.162721470 -0400 @@ -2,104 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; - /** * Constants */ public interface XMLCipherParameters { - /** */ - public static final String AES_128 = + String AES_128 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; - /** */ - public static final String AES_256 = + String AES_256 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; - /** */ - public static final String AES_192 = + String AES_192 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; - /** */ - public static final String RSA_1_5 = + String RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; - /** */ - public static final String RSA_OAEP = + String RSA_OAEP = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; - /** */ - public static final String DIFFIE_HELLMAN = + String DIFFIE_HELLMAN = "http://www.w3.org/2001/04/xmlenc#dh"; - /** */ - public static final String TRIPLEDES_KEYWRAP = + String TRIPLEDES_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; - /** */ - public static final String AES_128_KEYWRAP = + String AES_128_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; - /** */ - public static final String AES_256_KEYWRAP = + String AES_256_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes256"; - /** */ - public static final String AES_192_KEYWRAP = + String AES_192_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes192"; - /** */ - public static final String SHA1 = + String SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1"; - /** */ - public static final String SHA256 = + String SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"; - /** */ - public static final String SHA512 = + String SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512"; - /** */ - public static final String RIPEMD_160 = + String RIPEMD_160 = "http://www.w3.org/2001/04/xmlenc#ripemd160"; - /** */ - public static final String XML_DSIG = + String XML_DSIG = "http://www.w3.org/2000/09/xmldsig#"; - /** */ - public static final String N14C_XML = + String N14C_XML = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; - /** */ - public static final String N14C_XML_CMMNTS = + String N14C_XML_CMMNTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** */ - public static final String EXCL_XML_N14C = + String EXCL_XML_N14C = "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** */ - public static final String EXCL_XML_N14C_CMMNTS = + String EXCL_XML_N14C_CMMNTS = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java 2013-06-28 11:33:24.942697193 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java 2013-06-28 11:33:24.746703292 -0400 @@ -2,73 +2,79 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.encryption; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; /** - * + * */ public class XMLEncryptionException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * * - * - */ - public XMLEncryptionException() { - super(); - } - /** - * - * @param _msgID - */ - public XMLEncryptionException(String _msgID) { - super(_msgID); - } - /** - * - * @param _msgID - * @param exArgs - */ - public XMLEncryptionException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - /** - * - * @param _msgID - * @param _originalException - */ - public XMLEncryptionException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - /** - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLEncryptionException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + */ + public XMLEncryptionException() { + super(); + } + + /** + * + * @param msgID + */ + public XMLEncryptionException(String msgID) { + super(msgID); + } + + /** + * + * @param msgID + * @param exArgs + */ + public XMLEncryptionException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * + * @param msgID + * @param originalException + */ + public XMLEncryptionException(String msgID, Exception originalException) { + super(msgID, originalException); + + } + + /** + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLEncryptionException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java 2013-06-28 11:33:25.582677270 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java 2013-06-28 11:33:25.410682625 -0400 @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.exceptions; - - -/** - * - * - * - * - * @author Christian Geuer-Pollmann - * - */ public class AlgorithmAlreadyRegisteredException extends XMLSecurityException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor AlgorithmAlreadyRegisteredException - * - */ - public AlgorithmAlreadyRegisteredException() { - super(); - } - - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - */ - public AlgorithmAlreadyRegisteredException(String _msgID) { - super(_msgID); - } - - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - */ - public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param _originalException - */ - public AlgorithmAlreadyRegisteredException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor AlgorithmAlreadyRegisteredException + * + */ + public AlgorithmAlreadyRegisteredException() { + super(); + } + + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + */ + public AlgorithmAlreadyRegisteredException(String msgID) { + super(msgID); + } + + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param exArgs + */ + public AlgorithmAlreadyRegisteredException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param originalException + */ + public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public AlgorithmAlreadyRegisteredException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java 2013-06-28 11:33:26.302654859 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java 2013-06-28 11:33:26.090661459 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.exceptions; - - /** * This Exception is thrown if decoding of Base64 data fails. * @@ -29,58 +29,54 @@ */ public class Base64DecodingException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor Base64DecodingException - * - */ - public Base64DecodingException() { - super(); - } - - /** - * Constructor Base64DecodingException - * - * @param _msgID - */ - public Base64DecodingException(String _msgID) { - super(_msgID); - } - - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param exArgs - */ - public Base64DecodingException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param _originalException - */ - public Base64DecodingException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public Base64DecodingException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + private static final long serialVersionUID = 1L; + + /** + * Constructor Base64DecodingException + * + */ + public Base64DecodingException() { + super(); + } + + /** + * Constructor Base64DecodingException + * + * @param msgID + */ + public Base64DecodingException(String msgID) { + super(msgID); + } + + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param exArgs + */ + public Base64DecodingException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param originalException + */ + public Base64DecodingException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java 2013-06-28 11:33:26.914635813 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java 2013-06-28 11:33:26.734641415 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.exceptions; - - import java.io.PrintStream; import java.io.PrintWriter; import java.text.MessageFormat; @@ -29,7 +29,6 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; - /** * The mother of all Exceptions in this bundle. It allows exceptions to have * their messages translated to the different locales. @@ -64,186 +63,154 @@ */ public class XMLSecurityException extends Exception { - - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** Field originalException */ - protected Exception originalException = null; - - /** Field msgID */ - protected String msgID; - - /** - * Constructor XMLSecurityException - * - */ - public XMLSecurityException() { - - super("Missing message string"); - - this.msgID = null; - this.originalException = null; - } - - /** - * Constructor XMLSecurityException - * - * @param _msgID - */ - public XMLSecurityException(String _msgID) { - - super(I18n.getExceptionMessage(_msgID)); - - this.msgID = _msgID; - this.originalException = null; - } - - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - */ - public XMLSecurityException(String _msgID, Object exArgs[]) { - - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); - - this.msgID = _msgID; - this.originalException = null; - } - - /** - * Constructor XMLSecurityException - * - * @param _originalException - */ - public XMLSecurityException(Exception _originalException) { - - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); - - this.originalException = _originalException; - } - - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityException(String _msgID, Exception _originalException) { - - super(I18n.getExceptionMessage(_msgID, _originalException)); - - this.msgID = _msgID; - this.originalException = _originalException; - } - - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityException(String _msgID, Object exArgs[], - Exception _originalException) { - - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); - - this.msgID = _msgID; - this.originalException = _originalException; - } - - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { - - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.printStackTrace(System.err); - } - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - - super.printStackTrace(printwriter); - - if (this.originalException != null) { - this.originalException.printStackTrace(printwriter); - } - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - - super.printStackTrace(printstream); - - if (this.originalException != null) { - this.originalException.printStackTrace(printstream); - } - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - return originalException; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** Field msgID */ + protected String msgID; + + /** + * Constructor XMLSecurityException + * + */ + public XMLSecurityException() { + super("Missing message string"); + + this.msgID = null; + } + + /** + * Constructor XMLSecurityException + * + * @param msgID + */ + public XMLSecurityException(String msgID) { + super(I18n.getExceptionMessage(msgID)); + + this.msgID = msgID; + } + + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityException(String msgID, Object exArgs[]) { + + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); + + this.msgID = msgID; + } + + /** + * Constructor XMLSecurityException + * + * @param originalException + */ + public XMLSecurityException(Exception originalException) { + + super("Missing message ID to locate message string in resource bundle \"" + + Constants.exceptionMessagesResourceBundleBase + + "\". Original Exception was a " + + originalException.getClass().getName() + " and message " + + originalException.getMessage(), originalException); + } + + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param originalException + */ + public XMLSecurityException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); + + this.msgID = msgID; + } + + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); + + this.msgID = msgID; + } + + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } + + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); + + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } + + if (super.getCause() != null) { + message = message + "\nOriginal Exception was " + super.getCause().toString(); + } + + return message; + } + + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } + + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } + + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } + + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java 2013-06-28 11:33:27.558615766 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java 2013-06-28 11:33:27.394620869 -0400 @@ -1,3 +1,25 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.exceptions; import java.io.PrintStream; @@ -39,186 +61,152 @@ * * @author Christian Geuer-Pollmann */ -public class XMLSecurityRuntimeException - extends RuntimeException { - /** +public class XMLSecurityRuntimeException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** Field msgID */ + protected String msgID; + + /** + * Constructor XMLSecurityRuntimeException * */ - private static final long serialVersionUID = 1L; + public XMLSecurityRuntimeException() { + super("Missing message string"); + + this.msgID = null; + } + + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + */ + public XMLSecurityRuntimeException(String msgID) { + super(I18n.getExceptionMessage(msgID)); + + this.msgID = msgID; + } + + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[]) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); + + this.msgID = msgID; + } + + /** + * Constructor XMLSecurityRuntimeException + * + * @param originalException + */ + public XMLSecurityRuntimeException(Exception originalException) { + super("Missing message ID to locate message string in resource bundle \"" + + Constants.exceptionMessagesResourceBundleBase + + "\". Original Exception was a " + + originalException.getClass().getName() + " and message " + + originalException.getMessage(), originalException); + } + + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); + + this.msgID = msgID; + } + + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); + + this.msgID = msgID; + } + + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } + + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); + + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } + + if (this.getCause() != null) { + message = message + "\nOriginal Exception was " + this.getCause().toString(); + } - /** Field originalException */ - protected Exception originalException = null; + return message; + } - /** Field msgID */ - protected String msgID; + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } + + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - /** - * Constructor XMLSecurityRuntimeException - * - */ - public XMLSecurityRuntimeException() { - - super("Missing message string"); - - this.msgID = null; - this.originalException = null; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - */ - public XMLSecurityRuntimeException(String _msgID) { - - super(I18n.getExceptionMessage(_msgID)); - - this.msgID = _msgID; - this.originalException = null; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[]) { - - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); - - this.msgID = _msgID; - this.originalException = null; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param _originalException - */ - public XMLSecurityRuntimeException(Exception _originalException) { - - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); - - this.originalException = _originalException; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Exception _originalException) { - - super(I18n.getExceptionMessage(_msgID, _originalException)); - - this.msgID = _msgID; - this.originalException = _originalException; - } - - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[], - Exception _originalException) { - - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); - - this.msgID = _msgID; - this.originalException = _originalException; - } - - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { - - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.printStackTrace(System.err); - } - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - - super.printStackTrace(printwriter); - - if (this.originalException != null) { - this.originalException.printStackTrace(printwriter); - } - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - - super.printStackTrace(printstream); - - if (this.originalException != null) { - this.originalException.printStackTrace(printstream); - } - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - return originalException; - } -} + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } + + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } + +} \ No newline at end of file --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java 2013-06-28 11:33:28.638582150 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java 2013-06-28 11:33:28.470587377 -0400 @@ -2,89 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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 { -/** - * - * @author $Author: mullan $ - */ -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 _msgID - * @param _originalException - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Object exArgs[], Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + 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 msgID + * @param originalException + */ + public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public ContentHandlerAlreadyRegisteredException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java 2013-06-28 11:33:29.294561731 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java 2013-06-28 11:33:29.130566833 -0400 @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -35,6 +35,8 @@ import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; 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; @@ -49,9 +51,8 @@ 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.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; +import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; @@ -60,7 +61,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * This class stand for KeyInfo Element that may contain keys, names, * certificates and other public key management information, @@ -91,1002 +91,1197 @@ * The containsXXX() methods return whether the KeyInfo * contains the corresponding type. * - * @author $Author: mullan $ */ public class KeyInfo extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(KeyInfo.class.getName()); - List x509Datas=null; - List encryptedKeys=null; - static final List nullList; + // We need at least one StorageResolver otherwise + // the KeyResolvers would not be called. + // The default StorageResolver is null. + + private List x509Datas = null; + private List encryptedKeys = null; + + private static final List nullList; static { List list = new ArrayList(1); list.add(null); - nullList = Collections.unmodifiableList(list); + nullList = java.util.Collections.unmodifiableList(list); } - /** - * Constructor KeyInfo - * @param doc - */ - public KeyInfo(Document doc) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - - } - - /** - * Constructor KeyInfo - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyInfo(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - } - - /** - * Sets the Id attribute - * - * @param Id ID - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Method addKeyName - * - * @param keynameString - */ - public void addKeyName(String keynameString) { - this.add(new KeyName(this._doc, keynameString)); - } - - /** - * Method add - * - * @param keyname - */ - public void add(KeyName keyname) { - - this._constructionElement.appendChild(keyname.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addKeyValue - * - * @param pk - */ - public void addKeyValue(PublicKey pk) { - this.add(new KeyValue(this._doc, pk)); - } - - /** - * Method addKeyValue - * - * @param unknownKeyValueElement - */ - public void addKeyValue(Element unknownKeyValueElement) { - this.add(new KeyValue(this._doc, unknownKeyValueElement)); - } - - /** - * Method add - * - * @param dsakeyvalue - */ - public void add(DSAKeyValue dsakeyvalue) { - this.add(new KeyValue(this._doc, dsakeyvalue)); - } - - /** - * Method add - * - * @param rsakeyvalue - */ - public void add(RSAKeyValue rsakeyvalue) { - this.add(new KeyValue(this._doc, rsakeyvalue)); - } - - /** - * Method add - * - * @param pk - */ - public void add(PublicKey pk) { - this.add(new KeyValue(this._doc, pk)); - } - - /** - * Method add - * - * @param keyvalue - */ - public void add(KeyValue keyvalue) { - this._constructionElement.appendChild(keyvalue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addMgmtData - * - * @param mgmtdata - */ - public void addMgmtData(String mgmtdata) { - this.add(new MgmtData(this._doc, mgmtdata)); - } - - /** - * Method add - * - * @param mgmtdata - */ - public void add(MgmtData mgmtdata) { - this._constructionElement.appendChild(mgmtdata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addPGPData - * - * @param pgpdata - */ - public void add(PGPData pgpdata) { - this._constructionElement.appendChild(pgpdata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addRetrievalMethod - * - * @param URI - * @param transforms - * @param Type - */ - public void addRetrievalMethod(String URI, Transforms transforms, - String Type) { - this.add(new RetrievalMethod(this._doc, URI, transforms, Type)); - } - - /** - * Method add - * - * @param retrievalmethod - */ - public void add(RetrievalMethod retrievalmethod) { - this._constructionElement.appendChild(retrievalmethod.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method add - * - * @param spkidata - */ - public void add(SPKIData spkidata) { - this._constructionElement.appendChild(spkidata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addX509Data - * - * @param x509data - */ - public void add(X509Data x509data) { - if (x509Datas==null) - x509Datas=new ArrayList(); - x509Datas.add(x509data); - this._constructionElement.appendChild(x509data.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addEncryptedKey - * - * @param encryptedKey - * @throws XMLEncryptionException - */ - - public void add(EncryptedKey encryptedKey) - throws XMLEncryptionException { - if (encryptedKeys==null) - encryptedKeys=new ArrayList(); - encryptedKeys.add(encryptedKey); - XMLCipher cipher = XMLCipher.getInstance(); - this._constructionElement.appendChild(cipher.martial(encryptedKey)); - } - - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method lengthKeyName - * - * @return the number of the KeyName tags - */ - public int lengthKeyName() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME); - } - - /** - * Method lengthKeyValue - * - *@return the number of the KeyValue tags - */ - public int lengthKeyValue() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE); - } - - /** - * Method lengthMgmtData - * - *@return the number of the MgmtData tags - */ - public int lengthMgmtData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA); - } - - /** - * Method lengthPGPData - * - *@return the number of the PGPDat. tags - */ - public int lengthPGPData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA); - } - - /** - * Method lengthRetrievalMethod - * - *@return the number of the RetrievalMethod tags - */ - public int lengthRetrievalMethod() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_RETRIEVALMETHOD); - } - - /** - * Method lengthSPKIData - * - *@return the number of the SPKIData tags - */ - public int lengthSPKIData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA); - } - - /** - * Method lengthX509Data - * - *@return the number of the X509Data tags - */ - public int lengthX509Data() { - if (x509Datas!=null) { - return x509Datas.size(); - } - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); - } - - /** - * Method lengthUnknownElement - * NOTE posibly buggy. - *@return the number of the UnknownElement tags - */ - public int lengthUnknownElement() { - - int res = 0; - NodeList nl = this._constructionElement.getChildNodes(); - - for (int i = 0; i < nl.getLength(); i++) { - Node current = nl.item(i); - - /** - * $todo$ using this method, we don't see unknown Elements - * from Signature NS; revisit - */ - if ((current.getNodeType() == Node.ELEMENT_NODE) - && current.getNamespaceURI() - .equals(Constants.SignatureSpecNS)) { - res++; - } - } - - return res; - } - - /** - * Method itemKeyName - * - * @param i - * @return the asked KeyName element, null if the index is too big - * @throws XMLSecurityException - */ - public KeyName itemKeyName(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_KEYNAME,i); - - if (e != null) { - return new KeyName(e, this._baseURI); - } - return null; - } - - /** - * Method itemKeyValue - * - * @param i - * @return the asked KeyValue element, null if the index is too big - * @throws XMLSecurityException - */ - public KeyValue itemKeyValue(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_KEYVALUE,i); - - if (e != null) { - return new KeyValue(e, this._baseURI); - } - return null; - } - - /** - * Method itemMgmtData - * - * @param i - *@return the asked MgmtData element, null if the index is too big - * @throws XMLSecurityException - */ - public MgmtData itemMgmtData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_MGMTDATA,i); - - if (e != null) { - return new MgmtData(e, this._baseURI); - } - return null; - } - - /** - * Method itemPGPData - * - * @param i - *@return the asked PGPData element, null if the index is too big - * @throws XMLSecurityException - */ - public PGPData itemPGPData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_PGPDATA,i); - - if (e != null) { - return new PGPData(e, this._baseURI); - } - return null; - } - - /** - * Method itemRetrievalMethod - * - * @param i - *@return the asked RetrievalMethod element, null if the index is too big - * @throws XMLSecurityException - */ - public RetrievalMethod itemRetrievalMethod(int i) - throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_RETRIEVALMETHOD,i); - - if (e != null) { - return new RetrievalMethod(e, this._baseURI); - } - return null; - } - - /** - * Method itemSPKIData - * - * @param i - *@return the asked SPKIData element, null if the index is too big - * @throws XMLSecurityException - */ - public SPKIData itemSPKIData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_SPKIDATA,i); - - if (e != null) { - return new SPKIData(e, this._baseURI); - } - return null; - } - - /** - * Method itemX509Data - *@return the asked X509Data element, null if the index is too big - * @param i - * - * @throws XMLSecurityException - */ - public X509Data itemX509Data(int i) throws XMLSecurityException { - if (x509Datas!=null) { - return x509Datas.get(i); - } - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509DATA,i); - - if (e != null) { - return new X509Data(e, this._baseURI); - } - return null; - } - - /** - * Method itemEncryptedKey - * - * @param i - * @return the asked EncryptedKey element, null if the index is too big - * @throws XMLSecurityException - */ - - public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { - if (encryptedKeys!=null) { - return encryptedKeys.get(i); - } - Element e = - XMLUtils.selectXencNode(this._constructionElement.getFirstChild(), - EncryptionConstants._TAG_ENCRYPTEDKEY,i); - - if (e != null) { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, null); - return cipher.loadEncryptedKey(e); - } - return null; - } + /** Field storageResolvers */ + private List storageResolvers = nullList; + + /** + * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s + */ + private List internalKeyResolvers = new ArrayList(); + + private boolean secureValidation; - /** - * Method itemUnknownElement - * - * @param i index - * @return the element number of the unknown elemens - */ - public Element itemUnknownElement(int i) { - - NodeList nl = this._constructionElement.getChildNodes(); - int res = 0; - - for (int j = 0; j < nl.getLength(); j++) { - Node current = nl.item(j); - - /** - * $todo$ using this method, we don't see unknown Elements - * from Signature NS; revisit - */ - if ((current.getNodeType() == Node.ELEMENT_NODE) - && current.getNamespaceURI() - .equals(Constants.SignatureSpecNS)) { - res++; - - if (res == i) { - return (Element) current; - } - } - } - - return null; - } - - /** - * Method isEmpty - * - * @return true if the element has no descedants. - */ - public boolean isEmpty() { - return this._constructionElement.getFirstChild()==null; - } - - /** - * Method containsKeyName - * - * @return If the KeyInfo contains a KeyName node - */ - public boolean containsKeyName() { - return this.lengthKeyName() > 0; - } - - /** - * Method containsKeyValue - * - * @return If the KeyInfo contains a KeyValue node - */ - public boolean containsKeyValue() { - return this.lengthKeyValue() > 0; - } - - /** - * Method containsMgmtData - * - * @return If the KeyInfo contains a MgmtData node - */ - public boolean containsMgmtData() { - return this.lengthMgmtData() > 0; - } - - /** - * Method containsPGPData - * - * @return If the KeyInfo contains a PGPData node - */ - public boolean containsPGPData() { - return this.lengthPGPData() > 0; - } - - /** - * Method containsRetrievalMethod - * - * @return If the KeyInfo contains a RetrievalMethod node - */ - public boolean containsRetrievalMethod() { - return this.lengthRetrievalMethod() > 0; - } - - /** - * Method containsSPKIData - * - * @return If the KeyInfo contains a SPKIData node - */ - public boolean containsSPKIData() { - return this.lengthSPKIData() > 0; - } - - /** - * Method containsUnknownElement - * - * @return If the KeyInfo contains a UnknownElement node - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } - - /** - * Method containsX509Data - * - * @return If the KeyInfo contains a X509Data node - */ - public boolean containsX509Data() { - return this.lengthX509Data() > 0; - } - - /** - * This method returns the public key. - * - * @return If the KeyInfo contains a PublicKey node - * @throws KeyResolverException - */ - - public PublicKey getPublicKey() throws KeyResolverException { - - PublicKey pk = this.getPublicKeyFromInternalResolvers(); - - if (pk != null) { - log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); - - return pk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); - - pk = this.getPublicKeyFromStaticResolvers(); - - if (pk != null) { - log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); - - return pk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); + /** + * Constructor KeyInfo + * @param doc + */ + public KeyInfo(Document doc) { + super(doc); - return null; - } + XMLUtils.addReturnToElement(this.constructionElement); + } /** - * Searches the library wide keyresolvers for public keys + * Constructor KeyInfo * - * @return The public key contained in this Node. - * @throws KeyResolverException + * @param element + * @param baseURI + * @throws XMLSecurityException */ - PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException { - Iterator it = KeyResolver.iterator(); - while (it.hasNext()) { - KeyResolverSpi keyResolver = it.next(); - Node currentChild = this._constructionElement.getFirstChild(); - String uri = this.getBaseURI(); - while (currentChild != null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (StorageResolver storage : _storageResolvers) { - PublicKey pk = - keyResolver.engineLookupAndResolvePublicKey( - (Element) currentChild, uri, storage - ); + public KeyInfo(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + + Attr attr = element.getAttributeNodeNS(null, "Id"); + if (attr != null) { + element.setIdAttributeNode(attr, true); + } + } + + /** + * Set whether secure processing is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } - if (pk != null) { - return pk; - } - } - } - currentChild = currentChild.getNextSibling(); - } + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); } - return null; } - /** - * Searches the per-KeyInfo keyresolvers for public keys - * - * @return The publick contained in this Node. - * @throws KeyResolverException - */ - PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { - int length=lengthInternalKeyResolver(); - int storageLength=this._storageResolvers.size(); - for (int i = 0; i < length; i++) { - KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - PublicKey pk = keyResolver - .engineLookupAndResolvePublicKey((Element) currentChild, uri, storage); - - if (pk != null) { - return pk; - } - } - } - currentChild=currentChild.getNextSibling(); - } - } - - return null; - } - - /** - * Method getX509Certificate - * - * @return The certificate contined in this KeyInfo - * @throws KeyResolverException - */ - public X509Certificate getX509Certificate() throws KeyResolverException { - - // First search using the individual resolvers from the user - X509Certificate cert = this.getX509CertificateFromInternalResolvers(); - - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could find a X509Certificate using the per-KeyInfo key resolvers"); - - return cert; - } - log.log(java.util.logging.Level.FINE, - "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); - - - // Then use the system-wide Resolvers - cert = this.getX509CertificateFromStaticResolvers(); - - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could find a X509Certificate using the system-wide key resolvers"); - - return cert; - } - log.log(java.util.logging.Level.FINE, - "I couldn't find a X509Certificate using the system-wide key resolvers"); + /** + * Method addKeyName + * + * @param keynameString + */ + public void addKeyName(String keynameString) { + this.add(new KeyName(this.doc, keynameString)); + } + /** + * Method add + * + * @param keyname + */ + public void add(KeyName keyname) { + this.constructionElement.appendChild(keyname.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - return null; - } + /** + * Method addKeyValue + * + * @param pk + */ + public void addKeyValue(PublicKey pk) { + this.add(new KeyValue(this.doc, pk)); + } /** - * This method uses each System-wide {@link KeyResolver} to search the - * child elements. Each combination of {@link KeyResolver} and child element - * is checked against all {@link StorageResolver}s. + * Method addKeyValue * - * @return The certificate contained in this KeyInfo - * @throws KeyResolverException + * @param unknownKeyValueElement */ - X509Certificate getX509CertificateFromStaticResolvers() - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "Start getX509CertificateFromStaticResolvers() with " + KeyResolver.length() - + " resolvers" - ); - } - String uri = this.getBaseURI(); - Iterator it = KeyResolver.iterator(); - while (it.hasNext()) { - KeyResolverSpi keyResolver = it.next(); - X509Certificate cert = applyCurrentResolver(uri, keyResolver); - if (cert != null) { - return cert; - } - } - return null; + public void addKeyValue(Element unknownKeyValueElement) { + this.add(new KeyValue(this.doc, unknownKeyValueElement)); } - private X509Certificate applyCurrentResolver( - String uri, KeyResolverSpi keyResolver - ) throws KeyResolverException { - Node currentChild = this._constructionElement.getFirstChild(); - while (currentChild != null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (StorageResolver storage : _storageResolvers) { - X509Certificate cert = - keyResolver.engineLookupResolveX509Certificate( - (Element) currentChild, uri, storage - ); + /** + * Method add + * + * @param dsakeyvalue + */ + public void add(DSAKeyValue dsakeyvalue) { + this.add(new KeyValue(this.doc, dsakeyvalue)); + } - if (cert != null) { - return cert; - } - } - } - currentChild = currentChild.getNextSibling(); + /** + * Method add + * + * @param rsakeyvalue + */ + public void add(RSAKeyValue rsakeyvalue) { + this.add(new KeyValue(this.doc, rsakeyvalue)); + } + + /** + * Method add + * + * @param pk + */ + public void add(PublicKey pk) { + this.add(new KeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param keyvalue + */ + public void add(KeyValue keyvalue) { + this.constructionElement.appendChild(keyvalue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addMgmtData + * + * @param mgmtdata + */ + public void addMgmtData(String mgmtdata) { + this.add(new MgmtData(this.doc, mgmtdata)); + } + + /** + * Method add + * + * @param mgmtdata + */ + public void add(MgmtData mgmtdata) { + this.constructionElement.appendChild(mgmtdata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addPGPData + * + * @param pgpdata + */ + public void add(PGPData pgpdata) { + this.constructionElement.appendChild(pgpdata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addRetrievalMethod + * + * @param uri + * @param transforms + * @param Type + */ + public void addRetrievalMethod(String uri, Transforms transforms, String Type) { + this.add(new RetrievalMethod(this.doc, uri, transforms, Type)); + } + + /** + * Method add + * + * @param retrievalmethod + */ + public void add(RetrievalMethod retrievalmethod) { + this.constructionElement.appendChild(retrievalmethod.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method add + * + * @param spkidata + */ + public void add(SPKIData spkidata) { + this.constructionElement.appendChild(spkidata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addX509Data + * + * @param x509data + */ + public void add(X509Data x509data) { + if (x509Datas == null) { + x509Datas = new ArrayList(); } - return null; + x509Datas.add(x509data); + this.constructionElement.appendChild(x509data.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** - * Method getX509CertificateFromInternalResolvers + * Method addEncryptedKey * - * @return The certificate contined in this KeyInfo - * @throws KeyResolverException + * @param encryptedKey + * @throws XMLEncryptionException */ - X509Certificate getX509CertificateFromInternalResolvers() - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "Start getX509CertificateFromInternalResolvers() with " - + this.lengthInternalKeyResolver() + " resolvers" - ); + + public void add(EncryptedKey encryptedKey) throws XMLEncryptionException { + if (encryptedKeys == null) { + encryptedKeys = new ArrayList(); } - String uri = this.getBaseURI(); - for (KeyResolverSpi keyResolver : _internalKeyResolvers) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); - } - X509Certificate cert = applyCurrentResolver(uri, keyResolver); - if (cert != null) { - return cert; - } + encryptedKeys.add(encryptedKey); + XMLCipher cipher = XMLCipher.getInstance(); + this.constructionElement.appendChild(cipher.martial(encryptedKey)); + } + + /** + * Method addDEREncodedKeyValue + * + * @param pk + * @throws XMLSecurityException + */ + public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException { + this.add(new DEREncodedKeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param derEncodedKeyValue + */ + public void add(DEREncodedKeyValue derEncodedKeyValue) { + this.constructionElement.appendChild(derEncodedKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addKeyInfoReference + * + * @param URI + * @throws XMLSecurityException + */ + public void addKeyInfoReference(String URI) throws XMLSecurityException { + this.add(new KeyInfoReference(this.doc, URI)); + } + + /** + * Method add + * + * @param keyInfoReference + */ + public void add(KeyInfoReference keyInfoReference) { + this.constructionElement.appendChild(keyInfoReference.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method lengthKeyName + * + * @return the number of the KeyName tags + */ + public int lengthKeyName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME); + } + + /** + * Method lengthKeyValue + * + *@return the number of the KeyValue tags + */ + public int lengthKeyValue() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE); + } + + /** + * Method lengthMgmtData + * + *@return the number of the MgmtData tags + */ + public int lengthMgmtData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA); + } + + /** + * Method lengthPGPData + * + *@return the number of the PGPDat. tags + */ + public int lengthPGPData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA); + } + + /** + * Method lengthRetrievalMethod + * + *@return the number of the RetrievalMethod tags + */ + public int lengthRetrievalMethod() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_RETRIEVALMETHOD); + } + + /** + * Method lengthSPKIData + * + *@return the number of the SPKIData tags + */ + public int lengthSPKIData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA); + } + + /** + * Method lengthX509Data + * + *@return the number of the X509Data tags + */ + public int lengthX509Data() { + if (x509Datas != null) { + return x509Datas.size(); } + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); + } - return null; + /** + * Method lengthDEREncodedKeyValue + * + *@return the number of the DEREncodedKeyValue tags + */ + public int lengthDEREncodedKeyValue() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_DERENCODEDKEYVALUE); } - /** - * This method returns a secret (symmetric) key. This is for XML Encryption. - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - public SecretKey getSecretKey() throws KeyResolverException { - SecretKey sk = this.getSecretKeyFromInternalResolvers(); - - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers"); - - return sk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); - - - sk = this.getSecretKeyFromStaticResolvers(); - - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); - - return sk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers"); - - - return null; - } - - /** - * Searches the library wide keyresolvers for Secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - - SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException { - final int length=KeyResolver.length(); - int storageLength=this._storageResolvers.size(); - Iterator it = KeyResolver.iterator(); - for (int i = 0; i < length; i++) { - KeyResolverSpi keyResolver = it.next(); - - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - - SecretKey sk = - keyResolver.engineLookupAndResolveSecretKey((Element) currentChild, - uri, - storage); - - if (sk != null) { - return sk; - } - } - } - currentChild=currentChild.getNextSibling(); - } - } - return null; - } - - /** - * Searches the per-KeyInfo keyresolvers for secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - - SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException { - int storageLength=this._storageResolvers.size(); - for (int i = 0; i < this.lengthInternalKeyResolver(); i++) { - KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + /** + * Method lengthKeyInfoReference + * + *@return the number of the KeyInfoReference tags + */ + public int lengthKeyInfoReference() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_KEYINFOREFERENCE); + } - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - - SecretKey sk = keyResolver - .engineLookupAndResolveSecretKey((Element) currentChild, uri, storage); - - if (sk != null) { - return sk; - } - } - } - currentChild=currentChild.getNextSibling(); - } - } - - return null; - } - - /** - * Stores the individual (per-KeyInfo) {@link KeyResolver}s - */ - List _internalKeyResolvers = new ArrayList(); - - /** - * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo - * object. - * - * @param realKeyResolver - */ - public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { - if (_internalKeyResolvers==null) { - _internalKeyResolvers=new ArrayList(); - } - this._internalKeyResolvers.add(realKeyResolver); - } - - /** - * Method lengthInternalKeyResolver - * @return the length of the key - */ - int lengthInternalKeyResolver() { - if (_internalKeyResolvers==null) - return 0; - return this._internalKeyResolvers.size(); - } - - /** - * Method itemInternalKeyResolver - * - * @param i the index - * @return the KeyResolverSpi for the index. - */ - KeyResolverSpi itemInternalKeyResolver(int i) { - return this._internalKeyResolvers.get(i); - } - - /** Field _storageResolvers */ - private List _storageResolvers = nullList; - - /** - * Method addStorageResolver - * - * @param storageResolver - */ - public void addStorageResolver(StorageResolver storageResolver) { - if (_storageResolvers == nullList ){ - _storageResolvers=new ArrayList(); - } - this._storageResolvers.add(storageResolver); - - } - - //J- - static boolean _alreadyInitialized = false; - /** init the keyinfo (Still needed?)*/ - public static void init() { + /** + * Method lengthUnknownElement + * NOTE possibly buggy. + * @return the number of the UnknownElement tags + */ + public int lengthUnknownElement() { + int res = 0; + NodeList nl = this.constructionElement.getChildNodes(); - if (!KeyInfo._alreadyInitialized) { - if (KeyInfo.log == null) { + for (int i = 0; i < nl.getLength(); i++) { + Node current = nl.item(i); /** - * $todo$ why the hell does the static initialization from the - * start not work ? + * $todo$ using this method, we don't see unknown Elements + * from Signature NS; revisit */ - KeyInfo.log = - java.util.logging.Logger.getLogger(KeyInfo.class.getName()); + if ((current.getNodeType() == Node.ELEMENT_NODE) + && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + res++; + } + } + + return res; + } + + /** + * Method itemKeyName + * + * @param i + * @return the asked KeyName element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyName itemKeyName(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_KEYNAME, i); + + if (e != null) { + return new KeyName(e, this.baseURI); + } + return null; + } + + /** + * Method itemKeyValue + * + * @param i + * @return the asked KeyValue element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyValue itemKeyValue(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_KEYVALUE, i); + + if (e != null) { + return new KeyValue(e, this.baseURI); + } + return null; + } - log.log(java.util.logging.Level.SEVERE, "Had to assign log in the init() function"); - } + /** + * Method itemMgmtData + * + * @param i + * @return the asked MgmtData element, null if the index is too big + * @throws XMLSecurityException + */ + public MgmtData itemMgmtData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_MGMTDATA, i); + + if (e != null) { + return new MgmtData(e, this.baseURI); + } + return null; + } - // KeyInfo._contentHandlerHash = new HashMap(10); - KeyInfo._alreadyInitialized = true; - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYINFO; - } + /** + * Method itemPGPData + * + * @param i + * @return the asked PGPData element, null if the index is too big + * @throws XMLSecurityException + */ + public PGPData itemPGPData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_PGPDATA, i); + + if (e != null) { + return new PGPData(e, this.baseURI); + } + return null; + } + + /** + * Method itemRetrievalMethod + * + * @param i + *@return the asked RetrievalMethod element, null if the index is too big + * @throws XMLSecurityException + */ + public RetrievalMethod itemRetrievalMethod(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_RETRIEVALMETHOD, i); + + if (e != null) { + return new RetrievalMethod(e, this.baseURI); + } + return null; + } + + /** + * Method itemSPKIData + * + * @param i + * @return the asked SPKIData element, null if the index is too big + * @throws XMLSecurityException + */ + public SPKIData itemSPKIData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_SPKIDATA, i); + + if (e != null) { + return new SPKIData(e, this.baseURI); + } + return null; + } + + /** + * Method itemX509Data + * + * @param i + * @return the asked X509Data element, null if the index is too big + * @throws XMLSecurityException + */ + public X509Data itemX509Data(int i) throws XMLSecurityException { + if (x509Datas != null) { + return x509Datas.get(i); + } + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509DATA, i); + + if (e != null) { + return new X509Data(e, this.baseURI); + } + return null; + } + + /** + * Method itemEncryptedKey + * + * @param i + * @return the asked EncryptedKey element, null if the index is too big + * @throws XMLSecurityException + */ + public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { + if (encryptedKeys != null) { + return encryptedKeys.get(i); + } + Element e = + XMLUtils.selectXencNode( + this.constructionElement.getFirstChild(), EncryptionConstants._TAG_ENCRYPTEDKEY, i); + + if (e != null) { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, null); + return cipher.loadEncryptedKey(e); + } + return null; + } + + /** + * Method itemDEREncodedKeyValue + * + * @param i + * @return the asked DEREncodedKeyValue element, null if the index is too big + * @throws XMLSecurityException + */ + public DEREncodedKeyValue itemDEREncodedKeyValue(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_DERENCODEDKEYVALUE, i); + + if (e != null) { + return new DEREncodedKeyValue(e, this.baseURI); + } + return null; + } + + /** + * Method itemKeyInfoReference + * + * @param i + * @return the asked KeyInfoReference element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyInfoReference itemKeyInfoReference(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_KEYINFOREFERENCE, i); + + if (e != null) { + return new KeyInfoReference(e, this.baseURI); + } + return null; + } + + /** + * Method itemUnknownElement + * + * @param i index + * @return the element number of the unknown elements + */ + public Element itemUnknownElement(int i) { + NodeList nl = this.constructionElement.getChildNodes(); + int res = 0; + + for (int j = 0; j < nl.getLength(); j++) { + Node current = nl.item(j); + + /** + * $todo$ using this method, we don't see unknown Elements + * from Signature NS; revisit + */ + if ((current.getNodeType() == Node.ELEMENT_NODE) + && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + res++; + + if (res == i) { + return (Element) current; + } + } + } + + return null; + } + + /** + * Method isEmpty + * + * @return true if the element has no descendants. + */ + public boolean isEmpty() { + return this.constructionElement.getFirstChild() == null; + } + + /** + * Method containsKeyName + * + * @return If the KeyInfo contains a KeyName node + */ + public boolean containsKeyName() { + return this.lengthKeyName() > 0; + } + + /** + * Method containsKeyValue + * + * @return If the KeyInfo contains a KeyValue node + */ + public boolean containsKeyValue() { + return this.lengthKeyValue() > 0; + } + + /** + * Method containsMgmtData + * + * @return If the KeyInfo contains a MgmtData node + */ + public boolean containsMgmtData() { + return this.lengthMgmtData() > 0; + } + + /** + * Method containsPGPData + * + * @return If the KeyInfo contains a PGPData node + */ + public boolean containsPGPData() { + return this.lengthPGPData() > 0; + } + + /** + * Method containsRetrievalMethod + * + * @return If the KeyInfo contains a RetrievalMethod node + */ + public boolean containsRetrievalMethod() { + return this.lengthRetrievalMethod() > 0; + } + + /** + * Method containsSPKIData + * + * @return If the KeyInfo contains a SPKIData node + */ + public boolean containsSPKIData() { + return this.lengthSPKIData() > 0; + } + + /** + * Method containsUnknownElement + * + * @return If the KeyInfo contains a UnknownElement node + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** + * Method containsX509Data + * + * @return If the KeyInfo contains a X509Data node + */ + public boolean containsX509Data() { + return this.lengthX509Data() > 0; + } + + /** + * Method containsDEREncodedKeyValue + * + * @return If the KeyInfo contains a DEREncodedKeyValue node + */ + public boolean containsDEREncodedKeyValue() { + return this.lengthDEREncodedKeyValue() > 0; + } + + /** + * Method containsKeyInfoReference + * + * @return If the KeyInfo contains a KeyInfoReference node + */ + public boolean containsKeyInfoReference() { + return this.lengthKeyInfoReference() > 0; + } + + /** + * This method returns the public key. + * + * @return If the KeyInfo contains a PublicKey node + * @throws KeyResolverException + */ + public PublicKey getPublicKey() throws KeyResolverException { + PublicKey pk = this.getPublicKeyFromInternalResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); + } + + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); + } + + pk = this.getPublicKeyFromStaticResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); + } + + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); + } + + return null; + } + + /** + * Searches the library wide KeyResolvers for public keys + * + * @return The public key contained in this Node. + * @throws KeyResolverException + */ + PublicKey getPublicKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + PublicKey pk = + keyResolver.engineLookupAndResolvePublicKey( + (Element) currentChild, uri, storage + ); + + if (pk != null) { + return pk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } + + /** + * Searches the per-KeyInfo KeyResolvers for public keys + * + * @return The public key contained in this Node. + * @throws KeyResolverException + */ + PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + PublicKey pk = + keyResolver.engineLookupAndResolvePublicKey( + (Element) currentChild, uri, storage + ); + + if (pk != null) { + return pk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } + + return null; + } + + /** + * Method getX509Certificate + * + * @return The certificate contained in this KeyInfo + * @throws KeyResolverException + */ + public X509Certificate getX509Certificate() throws KeyResolverException { + // First search using the individual resolvers from the user + X509Certificate cert = this.getX509CertificateFromInternalResolvers(); + + if (cert != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the per-KeyInfo key resolvers"); + } + + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); + } + + // Then use the system-wide Resolvers + cert = this.getX509CertificateFromStaticResolvers(); + + if (cert != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the system-wide key resolvers"); + } + + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers"); + } + + return null; + } + + /** + * This method uses each System-wide {@link KeyResolver} to search the + * child elements. Each combination of {@link KeyResolver} and child element + * is checked against all {@link StorageResolver}s. + * + * @return The certificate contained in this KeyInfo + * @throws KeyResolverException + */ + X509Certificate getX509CertificateFromStaticResolvers() + throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Start getX509CertificateFromStaticResolvers() with " + KeyResolver.length() + + " resolvers" + ); + } + String uri = this.getBaseURI(); + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); + X509Certificate cert = applyCurrentResolver(uri, keyResolver); + if (cert != null) { + return cert; + } + } + return null; + } + + private X509Certificate applyCurrentResolver( + String uri, KeyResolverSpi keyResolver + ) throws KeyResolverException { + Node currentChild = this.constructionElement.getFirstChild(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + X509Certificate cert = + keyResolver.engineLookupResolveX509Certificate( + (Element) currentChild, uri, storage + ); + + if (cert != null) { + return cert; + } + } + } + currentChild = currentChild.getNextSibling(); + } + return null; + } + + /** + * Method getX509CertificateFromInternalResolvers + * + * @return The certificate contained in this KeyInfo + * @throws KeyResolverException + */ + X509Certificate getX509CertificateFromInternalResolvers() + throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Start getX509CertificateFromInternalResolvers() with " + + this.lengthInternalKeyResolver() + " resolvers" + ); + } + String uri = this.getBaseURI(); + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + X509Certificate cert = applyCurrentResolver(uri, keyResolver); + if (cert != null) { + return cert; + } + } + + return null; + } + + /** + * This method returns a secret (symmetric) key. This is for XML Encryption. + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + public SecretKey getSecretKey() throws KeyResolverException { + SecretKey sk = this.getSecretKeyFromInternalResolvers(); + + if (sk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers"); + } + + return sk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); + } + + sk = this.getSecretKeyFromStaticResolvers(); + + if (sk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); + } + + return sk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers"); + } + + return null; + } + + /** + * Searches the library wide KeyResolvers for Secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); + + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + SecretKey sk = + keyResolver.engineLookupAndResolveSecretKey( + (Element) currentChild, uri, storage + ); + + if (sk != null) { + return sk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } + + /** + * Searches the per-KeyInfo KeyResolvers for secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + + SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + SecretKey sk = + keyResolver.engineLookupAndResolveSecretKey( + (Element) currentChild, uri, storage + ); + + if (sk != null) { + return sk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } + + return null; + } + + /** + * This method returns a private key. This is for Key Transport in XML Encryption. + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + public PrivateKey getPrivateKey() throws KeyResolverException { + PrivateKey pk = this.getPrivateKeyFromInternalResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a private key using the per-KeyInfo key resolvers"); + } + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); + } + + pk = this.getPrivateKeyFromStaticResolvers(); + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a private key using the system-wide key resolvers"); + } + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a private key using the system-wide key resolvers"); + } + + return null; + } + + /** + * Searches the library wide KeyResolvers for Private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); + + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + // not using StorageResolvers at the moment + // since they cannot return private keys + PrivateKey pk = + keyResolver.engineLookupAndResolvePrivateKey( + (Element) currentChild, uri, null + ); + + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } + + /** + * Searches the per-KeyInfo KeyResolvers for private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + // not using StorageResolvers at the moment + // since they cannot return private keys + PrivateKey pk = + keyResolver.engineLookupAndResolvePrivateKey( + (Element) currentChild, uri, null + ); + + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } + + return null; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo + * object. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + this.internalKeyResolvers.add(realKeyResolver); + } + + /** + * Method lengthInternalKeyResolver + * @return the length of the key + */ + int lengthInternalKeyResolver() { + return this.internalKeyResolvers.size(); + } + + /** + * Method itemInternalKeyResolver + * + * @param i the index + * @return the KeyResolverSpi for the index. + */ + KeyResolverSpi itemInternalKeyResolver(int i) { + return this.internalKeyResolvers.get(i); + } + + /** + * Method addStorageResolver + * + * @param storageResolver + */ + public void addStorageResolver(StorageResolver storageResolver) { + if (storageResolvers == nullList) { + // Replace the default null StorageResolver + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(storageResolver); + } + + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFO; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java 2013-06-28 11:33:30.038538572 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java 2013-06-28 11:33:29.870543803 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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; @@ -31,57 +31,53 @@ 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 for com.sun.org.apache.xml.internal.security.keys package. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public 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 " - : "") + "\""); - } - } + 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 " : "") + "\""); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java 2013-06-28 11:33:30.714517532 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java 2013-06-28 11:33:30.542522883 -0400 @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; - - - - /** - * Empty interface just to identify Elements that can be cildren of ds:KeyInfo. + * Empty interface just to identify Elements that can be children of ds:KeyInfo. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public interface KeyInfoContent { } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java 2013-06-28 11:33:31.418495616 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java 2013-06-28 11:33:31.218501844 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -27,46 +29,44 @@ import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyName extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor KeyName - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyName(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor KeyName - * - * @param doc - * @param keyName - */ - public KeyName(Document doc, String keyName) { - - super(doc); - - this.addText(keyName); - } - - /** - * Method getKeyName - * - * @return key name - */ - public String getKeyName() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYNAME; - } + /** + * Constructor KeyName + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyName(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor KeyName + * + * @param doc + * @param keyName + */ + public KeyName(Document doc, String keyName) { + super(doc); + + this.addText(keyName); + } + + /** + * Method getKeyName + * + * @return key name + */ + public String getKeyName() { + return this.getTextFromTextChild(); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYNAME; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java 2013-06-28 11:33:32.018476941 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java 2013-06-28 11:33:31.850482171 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -36,10 +38,10 @@ * validating the signature. Structured formats for defining DSA (REQUIRED) * and RSA (RECOMMENDED) public keys are defined in Signature Algorithms * (section 6.4). The KeyValue element may include externally defined public - * keys values represented as PCDATA or element types from an external + * keys values represented as PCDATA or element types from an external * namespace. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { @@ -50,12 +52,11 @@ * @param dsaKeyValue */ public KeyValue(Document doc, DSAKeyValue dsaKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(dsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(dsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -65,12 +66,11 @@ * @param rsaKeyValue */ public KeyValue(Document doc, RSAKeyValue rsaKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(rsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(rsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -80,12 +80,11 @@ * @param unknownKeyValue */ public KeyValue(Document doc, Element unknownKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(unknownKeyValue); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(unknownKeyValue); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -95,21 +94,20 @@ * @param pk */ public KeyValue(Document doc, PublicKey pk) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); if (pk instanceof java.security.interfaces.DSAPublicKey) { - DSAKeyValue dsa = new DSAKeyValue(this._doc, pk); + DSAKeyValue dsa = new DSAKeyValue(this.doc, pk); - this._constructionElement.appendChild(dsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(dsa.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } else if (pk instanceof java.security.interfaces.RSAPublicKey) { - RSAKeyValue rsa = new RSAKeyValue(this._doc, pk); + RSAKeyValue rsa = new RSAKeyValue(this.doc, pk); - this._constructionElement.appendChild(rsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(rsa.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -120,8 +118,7 @@ * @param BaseURI * @throws XMLSecurityException */ - public KeyValue(Element element, String BaseURI) - throws XMLSecurityException { + public KeyValue(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } @@ -132,22 +129,21 @@ * @throws XMLSecurityException */ public PublicKey getPublicKey() throws XMLSecurityException { - - Element rsa = XMLUtils.selectDsNode - (this._constructionElement.getFirstChild(), - Constants._TAG_RSAKEYVALUE,0); + Element rsa = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); if (rsa != null) { - RSAKeyValue kv = new RSAKeyValue(rsa, this._baseURI); + RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI); return kv.getPublicKey(); } - Element dsa = XMLUtils.selectDsNode - (this._constructionElement.getFirstChild(), - Constants._TAG_DSAKEYVALUE,0); + Element dsa = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); if (dsa != null) { - DSAKeyValue kv = new DSAKeyValue(dsa, this._baseURI); + DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI); return kv.getPublicKey(); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java 2013-06-28 11:33:32.726454902 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java 2013-06-28 11:33:32.534460881 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -27,47 +29,45 @@ import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class MgmtData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor MgmtData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public MgmtData(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor MgmtData - * - * @param doc - * @param mgmtData - */ - public MgmtData(Document doc, String mgmtData) { - - super(doc); - - this.addText(mgmtData); - } - - /** - * Method getMgmtData - * - * @return the managment data - */ - public String getMgmtData() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_MGMTDATA; - } + /** + * Constructor MgmtData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public MgmtData(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor MgmtData + * + * @param doc + * @param mgmtData + */ + public MgmtData(Document doc, String mgmtData) { + super(doc); + + this.addText(mgmtData); + } + + /** + * Method getMgmtData + * + * @return the managment data + */ + public String getMgmtData() { + return this.getTextFromTextChild(); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_MGMTDATA; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java 2013-06-28 11:33:33.342435731 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java 2013-06-28 11:33:33.182440711 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -26,25 +28,24 @@ import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ * $todo$ Implement */ public class PGPData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor PGPData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public PGPData(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor PGPData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public PGPData(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_PGPDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_PGPDATA; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java 2013-06-28 11:33:34.002415186 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java 2013-06-28 11:33:33.830420539 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -30,118 +32,104 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class RetrievalMethod extends SignatureElementProxy - implements KeyInfoContent { +public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent { - //J- /** DSA retrieval */ - public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; - /** RSA retrieval */ - public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue"; - /** PGP retrieval */ - public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData"; - /** SPKI retrieval */ - public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData"; - /** MGMT retrieval */ - public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData"; - /** X509 retrieval */ - public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data"; - /** RAWX509 retrieval */ - public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate"; - //J+ - - /** - * Constructor RetrievalMethod - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public RetrievalMethod(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor RetrievalMethod - * - * @param doc - * @param URI - * @param transforms - * @param Type - */ - public RetrievalMethod(Document doc, String URI, Transforms transforms, - String Type) { - - super(doc); - - this._constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); - - if (Type != null) { - this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type); - } - - if (transforms != null) { - this._constructionElement.appendChild(transforms.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - } - - /** - * Method getURIAttr - * - * @return the URI attribute - */ - public Attr getURIAttr() { - return this._constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); - } - - /** - * Method getURI - * - * - * @return URI string - */ - public String getURI() { - return this.getURIAttr().getNodeValue(); - } - - /** @return the type*/ - public String getType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_TYPE); - } - - /** - * Method getTransforms - * - * - * @throws XMLSecurityException - * @return the transforamitons - */ - public Transforms getTransforms() throws XMLSecurityException { - - try { - Element transformsElem = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants - ._TAG_TRANSFORMS, 0); - - if (transformsElem != null) { - return new Transforms(transformsElem, this._baseURI); - } - - return null; - } catch (XMLSignatureException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_RETRIEVALMETHOD; - } + public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; + /** RSA retrieval */ + public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue"; + /** PGP retrieval */ + public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData"; + /** SPKI retrieval */ + public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData"; + /** MGMT retrieval */ + public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData"; + /** X509 retrieval */ + public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data"; + /** RAWX509 retrieval */ + public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate"; + + /** + * Constructor RetrievalMethod + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public RetrievalMethod(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor RetrievalMethod + * + * @param doc + * @param URI + * @param transforms + * @param Type + */ + public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) { + super(doc); + + this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); + + if (Type != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type); + } + + if (transforms != null) { + this.constructionElement.appendChild(transforms.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + } + + /** + * Method getURIAttr + * + * @return the URI attribute + */ + public Attr getURIAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); + } + + /** + * Method getURI + * + * @return URI string + */ + public String getURI() { + return this.getURIAttr().getNodeValue(); + } + + /** @return the type*/ + public String getType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE); + } + + /** + * Method getTransforms + * + * @throws XMLSecurityException + * @return the transformations + */ + public Transforms getTransforms() throws XMLSecurityException { + try { + Element transformsElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0); + + if (transformsElem != null) { + return new Transforms(transformsElem, this.baseURI); + } + + return null; + } catch (XMLSignatureException ex) { + throw new XMLSecurityException("empty", ex); + } + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_RETRIEVALMETHOD; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java 2013-06-28 11:33:34.690393770 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java 2013-06-28 11:33:34.510399372 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -26,26 +28,25 @@ import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ * $todo$ implement */ public class SPKIData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor SPKIData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SPKIData(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor SPKIData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SPKIData(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_SPKIDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_SPKIDATA; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java 2013-06-28 11:33:35.362372853 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java 2013-06-28 11:33:35.198377960 -0400 @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; - - import java.math.BigInteger; import java.security.cert.X509Certificate; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509CRL; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; @@ -38,447 +39,501 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; - -/** - * - * @author $Author: mullan $ - */ public class X509Data extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509Data.class.getName()); - /** - * Constructor X509Data - * - * @param doc - */ - public X509Data(Document doc) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Constructor X509Data - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public X509Data(Element element, String BaseURI) - throws XMLSecurityException { - - super(element, BaseURI); - Node sibling=this._constructionElement.getFirstChild(); - while (sibling!=null) { - if (sibling.getNodeType()!=Node.ELEMENT_NODE) { - sibling=sibling.getNextSibling(); - continue; - } - return; - } - /* No Elements found */ - Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; - throw new XMLSecurityException("xml.WrongContent", exArgs); - } - - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, - BigInteger X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } - - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } - - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } - - /** - * Method add - * - * @param xmlX509IssuerSerial - */ - public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { - - this._constructionElement - .appendChild(xmlX509IssuerSerial.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addSKI - * - * @param skiBytes - */ - public void addSKI(byte[] skiBytes) { - this.add(new XMLX509SKI(this._doc, skiBytes)); - } - - /** - * Method addSKI - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addSKI(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509SKI(this._doc, x509certificate)); - } - - /** - * Method add - * - * @param xmlX509SKI - */ - public void add(XMLX509SKI xmlX509SKI) { - this._constructionElement.appendChild(xmlX509SKI.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addSubjectName - * - * @param subjectName - */ - public void addSubjectName(String subjectName) { - this.add(new XMLX509SubjectName(this._doc, subjectName)); - } - - /** - * Method addSubjectName - * - * @param x509certificate - */ - public void addSubjectName(X509Certificate x509certificate) { - this.add(new XMLX509SubjectName(this._doc, x509certificate)); - } - - /** - * Method add - * - * @param xmlX509SubjectName - */ - public void add(XMLX509SubjectName xmlX509SubjectName) { - this._constructionElement.appendChild(xmlX509SubjectName.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addCertificate - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addCertificate(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509Certificate(this._doc, x509certificate)); - } - - /** - * Method addCertificate - * - * @param x509certificateBytes - */ - public void addCertificate(byte[] x509certificateBytes) { - this.add(new XMLX509Certificate(this._doc, x509certificateBytes)); - } - - /** - * Method add - * - * @param xmlX509Certificate - */ - public void add(XMLX509Certificate xmlX509Certificate) { - this._constructionElement.appendChild(xmlX509Certificate.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addCRL - * - * @param crlBytes - */ - public void addCRL(byte[] crlBytes) { - this.add(new XMLX509CRL(this._doc, crlBytes)); - } - - /** - * Method add - * - * @param xmlX509CRL - */ - public void add(XMLX509CRL xmlX509CRL) { - this._constructionElement.appendChild(xmlX509CRL.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method lengthIssuerSerial - * - * @return the number of IssuerSerial elements in this X509Data - */ - public int lengthIssuerSerial() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509ISSUERSERIAL); - } - - /** - * Method lengthSKI - * - * @return the number of SKI elements in this X509Data - */ - public int lengthSKI() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); - } - - /** - * Method lengthSubjectName - * - * @return the number of SubjectName elements in this X509Data - */ - public int lengthSubjectName() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509SUBJECTNAME); - } - - /** - * Method lengthCertificate - * - * @return the number of Certificate elements in this X509Data - */ - public int lengthCertificate() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509CERTIFICATE); - } - - /** - * Method lengthCRL - * - * @return the number of CRL elements in this X509Data - */ - public int lengthCRL() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); - } - - /** - * Method lengthUnknownElement - * - * @return the number of UnknownElement elements in this X509Data - */ - public int lengthUnknownElement() { - - int result = 0; - Node n=this._constructionElement.getFirstChild(); - while (n!=null){ - - if ((n.getNodeType() == Node.ELEMENT_NODE) - &&!n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { - result += 1; - } - n=n.getNextSibling(); - } - - return result; - } - - /** - * Method itemIssuerSerial - * - * @param i - * @return the X509IssuerSerial, null if not present - * @throws XMLSecurityException - */ - public XMLX509IssuerSerial itemIssuerSerial(int i) - throws XMLSecurityException { - - Element e = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509ISSUERSERIAL,i); - - if (e != null) { - return new XMLX509IssuerSerial(e, this._baseURI); - } - return null; - } - - /** - * Method itemSKI - * - * @param i - * @return the X509SKI, null if not present - * @throws XMLSecurityException - */ - public XMLX509SKI itemSKI(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SKI,i); - - if (e != null) { - return new XMLX509SKI(e, this._baseURI); - } - return null; - } - - /** - * Method itemSubjectName - * - * @param i - * @return the X509SubjectName, null if not present - * @throws XMLSecurityException - */ - public XMLX509SubjectName itemSubjectName(int i) - throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SUBJECTNAME,i); - - if (e != null) { - return new XMLX509SubjectName(e, this._baseURI); - } - return null; - } - - /** - * Method itemCertificate - * - * @param i - * @return the X509Certifacte, null if not present - * @throws XMLSecurityException - */ - public XMLX509Certificate itemCertificate(int i) - throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509CERTIFICATE,i); - - if (e != null) { - return new XMLX509Certificate(e, this._baseURI); - } - return null; - } - - /** - * Method itemCRL - * - * @param i - * @return the X509CRL, null if not present - * @throws XMLSecurityException - */ - public XMLX509CRL itemCRL(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509CRL,i); - - if (e != null) { - return new XMLX509CRL(e, this._baseURI); - } - return null; - } - - /** - * Method itemUnknownElement - * - * @param i - * @return the Unknown Element at i - * TODO implement - **/ - public Element itemUnknownElement(int i) { - log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i); - return null; - } - - /** - * Method containsIssuerSerial - * - * @return true if this X509Data contains a IssuerSerial - */ - public boolean containsIssuerSerial() { - return this.lengthIssuerSerial() > 0; - } - - /** - * Method containsSKI - * - * @return true if this X509Data contains a SKI - */ - public boolean containsSKI() { - return this.lengthSKI() > 0; - } - - /** - * Method containsSubjectName - * - * @return true if this X509Data contains a SubjectName - */ - public boolean containsSubjectName() { - return this.lengthSubjectName() > 0; - } - - /** - * Method containsCertificate - * - * @return true if this X509Data contains a Certificate - */ - public boolean containsCertificate() { - return this.lengthCertificate() > 0; - } - - /** - * Method containsCRL - * - * @return true if this X509Data contains a CRL - */ - public boolean containsCRL() { - return this.lengthCRL() > 0; - } - - /** - * Method containsUnknownElement - * - * @return true if this X509Data contains an UnknownElement - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509DATA; - } + /** + * Constructor X509Data + * + * @param doc + */ + public X509Data(Document doc) { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Constructor X509Data + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public X509Data(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + + Node sibling = this.constructionElement.getFirstChild(); + while (sibling != null) { + if (sibling.getNodeType() != Node.ELEMENT_NODE) { + sibling = sibling.getNextSibling(); + continue; + } + return; + } + /* No Elements found */ + Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; + throw new XMLSecurityException("xml.WrongContent", exArgs); + } + + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } + + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } + + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } + + /** + * Method add + * + * @param xmlX509IssuerSerial + */ + public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { + + this.constructionElement.appendChild(xmlX509IssuerSerial.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addSKI + * + * @param skiBytes + */ + public void addSKI(byte[] skiBytes) { + this.add(new XMLX509SKI(this.doc, skiBytes)); + } + + /** + * Method addSKI + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addSKI(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509SKI(this.doc, x509certificate)); + } + + /** + * Method add + * + * @param xmlX509SKI + */ + public void add(XMLX509SKI xmlX509SKI) { + this.constructionElement.appendChild(xmlX509SKI.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addSubjectName + * + * @param subjectName + */ + public void addSubjectName(String subjectName) { + this.add(new XMLX509SubjectName(this.doc, subjectName)); + } + + /** + * Method addSubjectName + * + * @param x509certificate + */ + public void addSubjectName(X509Certificate x509certificate) { + this.add(new XMLX509SubjectName(this.doc, x509certificate)); + } + + /** + * Method add + * + * @param xmlX509SubjectName + */ + public void add(XMLX509SubjectName xmlX509SubjectName) { + this.constructionElement.appendChild(xmlX509SubjectName.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addCertificate + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addCertificate(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509Certificate(this.doc, x509certificate)); + } + + /** + * Method addCertificate + * + * @param x509certificateBytes + */ + public void addCertificate(byte[] x509certificateBytes) { + this.add(new XMLX509Certificate(this.doc, x509certificateBytes)); + } + + /** + * Method add + * + * @param xmlX509Certificate + */ + public void add(XMLX509Certificate xmlX509Certificate) { + this.constructionElement.appendChild(xmlX509Certificate.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addCRL + * + * @param crlBytes + */ + public void addCRL(byte[] crlBytes) { + this.add(new XMLX509CRL(this.doc, crlBytes)); + } + + /** + * Method add + * + * @param xmlX509CRL + */ + public void add(XMLX509CRL xmlX509CRL) { + this.constructionElement.appendChild(xmlX509CRL.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addDigest + * + * @param x509certificate + * @param algorithmURI + * @throws XMLSecurityException + */ + public void addDigest(X509Certificate x509certificate, String algorithmURI) + throws XMLSecurityException { + this.add(new XMLX509Digest(this.doc, x509certificate, algorithmURI)); + } + + /** + * Method addDigest + * + * @param x509CertificateDigestByes + * @param algorithmURI + */ + public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) { + this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI)); + } + + /** + * Method add + * + * @param XMLX509Digest + */ + public void add(XMLX509Digest xmlX509Digest) { + this.constructionElement.appendChild(xmlX509Digest.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method lengthIssuerSerial + * + * @return the number of IssuerSerial elements in this X509Data + */ + public int lengthIssuerSerial() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL); + } + + /** + * Method lengthSKI + * + * @return the number of SKI elements in this X509Data + */ + public int lengthSKI() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); + } + + /** + * Method lengthSubjectName + * + * @return the number of SubjectName elements in this X509Data + */ + public int lengthSubjectName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME); + } + + /** + * Method lengthCertificate + * + * @return the number of Certificate elements in this X509Data + */ + public int lengthCertificate() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE); + } + + /** + * Method lengthCRL + * + * @return the number of CRL elements in this X509Data + */ + public int lengthCRL() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); + } + + /** + * Method lengthDigest + * + * @return the number of X509Digest elements in this X509Data + */ + public int lengthDigest() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST); + } + + /** + * Method lengthUnknownElement + * + * @return the number of UnknownElement elements in this X509Data + */ + public int lengthUnknownElement() { + int result = 0; + Node n = this.constructionElement.getFirstChild(); + while (n != null){ + if ((n.getNodeType() == Node.ELEMENT_NODE) + && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + result++; + } + n = n.getNextSibling(); + } + + return result; + } + + /** + * Method itemIssuerSerial + * + * @param i + * @return the X509IssuerSerial, null if not present + * @throws XMLSecurityException + */ + public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i); + + if (e != null) { + return new XMLX509IssuerSerial(e, this.baseURI); + } + return null; + } + + /** + * Method itemSKI + * + * @param i + * @return the X509SKI, null if not present + * @throws XMLSecurityException + */ + public XMLX509SKI itemSKI(int i) throws XMLSecurityException { + + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i); + + if (e != null) { + return new XMLX509SKI(e, this.baseURI); + } + return null; + } + + /** + * Method itemSubjectName + * + * @param i + * @return the X509SubjectName, null if not present + * @throws XMLSecurityException + */ + public XMLX509SubjectName itemSubjectName(int i) throws XMLSecurityException { + + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i); + + if (e != null) { + return new XMLX509SubjectName(e, this.baseURI); + } + return null; + } + + /** + * Method itemCertificate + * + * @param i + * @return the X509Certifacte, null if not present + * @throws XMLSecurityException + */ + public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException { + + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i); + + if (e != null) { + return new XMLX509Certificate(e, this.baseURI); + } + return null; + } + + /** + * Method itemCRL + * + * @param i + * @return the X509CRL, null if not present + * @throws XMLSecurityException + */ + public XMLX509CRL itemCRL(int i) throws XMLSecurityException { + + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i); + + if (e != null) { + return new XMLX509CRL(e, this.baseURI); + } + return null; + } + + /** + * Method itemDigest + * + * @param i + * @return the X509Digest, null if not present + * @throws XMLSecurityException + */ + public XMLX509Digest itemDigest(int i) throws XMLSecurityException { + + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i); + + if (e != null) { + return new XMLX509Digest(e, this.baseURI); + } + return null; + } + + /** + * Method itemUnknownElement + * + * @param i + * @return the Unknown Element at i + * TODO implement + **/ + public Element itemUnknownElement(int i) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:" + i); + } + return null; + } + + /** + * Method containsIssuerSerial + * + * @return true if this X509Data contains a IssuerSerial + */ + public boolean containsIssuerSerial() { + return this.lengthIssuerSerial() > 0; + } + + /** + * Method containsSKI + * + * @return true if this X509Data contains a SKI + */ + public boolean containsSKI() { + return this.lengthSKI() > 0; + } + + /** + * Method containsSubjectName + * + * @return true if this X509Data contains a SubjectName + */ + public boolean containsSubjectName() { + return this.lengthSubjectName() > 0; + } + + /** + * Method containsCertificate + * + * @return true if this X509Data contains a Certificate + */ + public boolean containsCertificate() { + return this.lengthCertificate() > 0; + } + + /** + * Method containsDigest + * + * @return true if this X509Data contains an X509Digest + */ + public boolean containsDigest() { + return this.lengthDigest() > 0; + } + + /** + * Method containsCRL + * + * @return true if this X509Data contains a CRL + */ + public boolean containsCRL() { + return this.lengthCRL() > 0; + } + + /** + * Method containsUnknownElement + * + * @return true if this X509Data contains an UnknownElement + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DATA; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java 2013-06-28 11:33:36.054351315 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java 2013-06-28 11:33:35.886356545 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; @@ -37,104 +39,93 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class DSAKeyValue extends SignatureElementProxy - implements KeyValueContent { +public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** - * Constructor DSAKeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public DSAKeyValue(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor DSAKeyValue - * - * @param doc - * @param P - * @param Q - * @param G - * @param Y - */ - public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, - BigInteger Y) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - this.addBigIntegerElement(P, Constants._TAG_P); - this.addBigIntegerElement(Q, Constants._TAG_Q); - this.addBigIntegerElement(G, Constants._TAG_G); - this.addBigIntegerElement(Y, Constants._TAG_Y); - } - - /** - * Constructor DSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - - if (key instanceof java.security.interfaces.DSAPublicKey) { - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), - Constants._TAG_P); - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), - Constants._TAG_Q); - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), - Constants._TAG_G); - this.addBigIntegerElement(((DSAPublicKey) key).getY(), - Constants._TAG_Y); - } else { - Object exArgs[] = { Constants._TAG_DSAKEYVALUE, - key.getClass().getName() }; - - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } - - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { - - try { - DSAPublicKeySpec pkspec = - new DSAPublicKeySpec(this - .getBigIntegerFromChildElement(Constants._TAG_Y, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants._TAG_P, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants._TAG_Q, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants - ._TAG_G, Constants.SignatureSpecNS)); - KeyFactory dsaFactory = KeyFactory.getInstance("DSA"); - PublicKey pk = dsaFactory.generatePublic(pkspec); - - return pk; - } catch (NoSuchAlgorithmException ex) { - throw new XMLSecurityException("empty", ex); - } catch (InvalidKeySpecException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DSAKEYVALUE; - } + /** + * Constructor DSAKeyValue + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public DSAKeyValue(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } + + /** + * Constructor DSAKeyValue + * + * @param doc + * @param P + * @param Q + * @param G + * @param Y + */ + public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + this.addBigIntegerElement(P, Constants._TAG_P); + this.addBigIntegerElement(Q, Constants._TAG_Q); + this.addBigIntegerElement(G, Constants._TAG_G); + this.addBigIntegerElement(Y, Constants._TAG_Y); + } + + /** + * Constructor DSAKeyValue + * + * @param doc + * @param key + * @throws IllegalArgumentException + */ + public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + + if (key instanceof java.security.interfaces.DSAPublicKey) { + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), Constants._TAG_P); + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), Constants._TAG_Q); + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), Constants._TAG_G); + this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y); + } else { + Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() }; + + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } + + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + DSAPublicKeySpec pkspec = + new DSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_Y, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_P, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_Q, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_G, Constants.SignatureSpecNS + ) + ); + KeyFactory dsaFactory = KeyFactory.getInstance("DSA"); + PublicKey pk = dsaFactory.generatePublic(pkspec); + + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DSAKEYVALUE; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java 2013-06-28 11:33:36.782328656 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java 2013-06-28 11:33:36.594334508 -0400 @@ -2,46 +2,38 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; - - import java.security.PublicKey; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * - * - * - * @author $Author: mullan $ - * - */ public interface KeyValueContent { - /** - * Method getPublicKey - * - * @return the public key - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() - throws XMLSecurityException; + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + PublicKey getPublicKey() throws XMLSecurityException; + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java 2013-06-28 11:33:37.426308608 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java 2013-06-28 11:33:37.218315085 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; @@ -37,93 +39,86 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class RSAKeyValue extends SignatureElementProxy - implements KeyValueContent { +public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** - * Constructor RSAKeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public RSAKeyValue(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor RSAKeyValue - * - * @param doc - * @param modulus - * @param exponent - */ - public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - this.addBigIntegerElement(modulus, Constants._TAG_MODULUS); - this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT); - } - - /** - * Constructor RSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - - if (key instanceof java.security.interfaces.RSAPublicKey ) { - this.addBigIntegerElement(((RSAPublicKey) key).getModulus(), - Constants._TAG_MODULUS); - this.addBigIntegerElement(((RSAPublicKey) key).getPublicExponent(), - Constants._TAG_EXPONENT); - } else { - Object exArgs[] = { Constants._TAG_RSAKEYVALUE, - key.getClass().getName() }; - - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } - - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { - - try { - KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); - - // KeyFactory rsaFactory = KeyFactory.getInstance(JCE_RSA); - RSAPublicKeySpec rsaKeyspec = - new RSAPublicKeySpec(this - .getBigIntegerFromChildElement(Constants._TAG_MODULUS, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants - ._TAG_EXPONENT, Constants.SignatureSpecNS)); - PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); - - return pk; - } catch (NoSuchAlgorithmException ex) { - throw new XMLSecurityException("empty", ex); - } catch (InvalidKeySpecException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_RSAKEYVALUE; - } + /** + * Constructor RSAKeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor RSAKeyValue + * + * @param doc + * @param modulus + * @param exponent + */ + public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + this.addBigIntegerElement(modulus, Constants._TAG_MODULUS); + this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT); + } + + /** + * Constructor RSAKeyValue + * + * @param doc + * @param key + * @throws IllegalArgumentException + */ + public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + + if (key instanceof java.security.interfaces.RSAPublicKey ) { + this.addBigIntegerElement( + ((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS + ); + this.addBigIntegerElement( + ((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT + ); + } else { + Object exArgs[] = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() }; + + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } + + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); + + RSAPublicKeySpec rsaKeyspec = + new RSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_MODULUS, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_EXPONENT, Constants.SignatureSpecNS + ) + ); + PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); + + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_RSAKEYVALUE; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java 2013-06-28 11:33:38.006290558 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java 2013-06-28 11:33:37.842295660 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -26,51 +28,43 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - * - */ -public class XMLX509CRL extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent { - /** - * Constructor XMLX509CRL - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509CRL(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor X509CRL - * - * @param doc - * @param crlBytes - */ - public XMLX509CRL(Document doc, byte[] crlBytes) { - - super(doc); - - this.addBase64Text(crlBytes); - } - - /** - * Method getCRLBytes - * - * @return the CRL bytes - * @throws XMLSecurityException - */ - public byte[] getCRLBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509CRL; - } + /** + * Constructor XMLX509CRL + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509CRL(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor X509CRL + * + * @param doc + * @param crlBytes + */ + public XMLX509CRL(Document doc, byte[] crlBytes) { + super(doc); + + this.addBase64Text(crlBytes); + } + + /** + * Method getCRLBytes + * + * @return the CRL bytes + * @throws XMLSecurityException + */ + public byte[] getCRLBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509CRL; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java 2013-06-28 11:33:38.634271009 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java 2013-06-28 11:33:38.474275988 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -25,6 +27,7 @@ import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Arrays; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; @@ -32,135 +35,134 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class XMLX509Certificate extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent { - /** Field JCA_CERT_ID */ - public static final String JCA_CERT_ID = "X.509"; + /** Field JCA_CERT_ID */ + public static final String JCA_CERT_ID = "X.509"; - /** - * Constructor X509Certificate - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509Certificate(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor X509Certificate - * - * @param doc - * @param certificateBytes - */ - public XMLX509Certificate(Document doc, byte[] certificateBytes) { - - super(doc); - - this.addBase64Text(certificateBytes); - } - - /** - * Constructor XMLX509Certificate - * - * @param doc - * @param x509certificate - * @throws XMLSecurityException - */ - public XMLX509Certificate(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { - - super(doc); - - try { - this.addBase64Text(x509certificate.getEncoded()); - } catch (java.security.cert.CertificateEncodingException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** - * Method getCertificateBytes - * - * @return the certificate bytes - * @throws XMLSecurityException - */ - public byte[] getCertificateBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } - - /** - * Method getX509Certificate - * - * @return the x509 certificate - * @throws XMLSecurityException - */ - public X509Certificate getX509Certificate() throws XMLSecurityException { - - try { - byte certbytes[] = this.getCertificateBytes(); - CertificateFactory certFact = - CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert = - (X509Certificate) certFact - .generateCertificate(new ByteArrayInputStream(certbytes)); - - if (cert != null) { - return cert; - } - - return null; - } catch (CertificateException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** - * Method getPublicKey - * - * @return teh publickey - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() throws XMLSecurityException { - - X509Certificate cert = this.getX509Certificate(); - - if (cert != null) { - return cert.getPublicKey(); - } + /** + * Constructor X509Certificate + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509Certificate(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - return null; - } + /** + * Constructor X509Certificate + * + * @param doc + * @param certificateBytes + */ + public XMLX509Certificate(Document doc, byte[] certificateBytes) { + super(doc); - /** @inheritDoc */ - public boolean equals(Object obj) { + this.addBase64Text(certificateBytes); + } - if (obj == null) { - return false; + /** + * Constructor XMLX509Certificate + * + * @param doc + * @param x509certificate + * @throws XMLSecurityException + */ + public XMLX509Certificate(Document doc, X509Certificate x509certificate) + throws XMLSecurityException { + super(doc); + + try { + this.addBase64Text(x509certificate.getEncoded()); + } catch (java.security.cert.CertificateEncodingException ex) { + throw new XMLSecurityException("empty", ex); } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + } + + /** + * Method getCertificateBytes + * + * @return the certificate bytes + * @throws XMLSecurityException + */ + public byte[] getCertificateBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } + + /** + * Method getX509Certificate + * + * @return the x509 certificate + * @throws XMLSecurityException + */ + public X509Certificate getX509Certificate() throws XMLSecurityException { + try { + byte certbytes[] = this.getCertificateBytes(); + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = + (X509Certificate) certFact.generateCertificate( + new ByteArrayInputStream(certbytes) + ); + + if (cert != null) { + return cert; + } + + return null; + } catch (CertificateException ex) { + throw new XMLSecurityException("empty", ex); + } + } + + /** + * Method getPublicKey + * + * @return the publickey + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + X509Certificate cert = this.getX509Certificate(); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** @inheritDoc */ + public boolean equals(Object obj) { + if (!(obj instanceof XMLX509Certificate)) { return false; } XMLX509Certificate other = (XMLX509Certificate) obj; try { - - /** $todo$ or should be create X509Certificates and use the equals() from the Certs */ - return java.security.MessageDigest.isEqual - (other.getCertificateBytes(), this.getCertificateBytes()); + return Arrays.equals(other.getCertificateBytes(), this.getCertificateBytes()); } catch (XMLSecurityException ex) { return false; } } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509CERTIFICATE; - } + public int hashCode() { + int result = 17; + try { + byte[] bytes = getCertificateBytes(); + for (int i = 0; i < bytes.length; i++) { + result = 31 * result + bytes[i]; + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + return result; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509CERTIFICATE; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java 2013-06-28 11:33:39.302250216 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java 2013-06-28 11:33:39.134255443 -0400 @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - - - /** * Just used for tagging contents that are allowed inside a ds:X509Data Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public interface XMLX509DataContent { } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java 2013-06-28 11:33:39.950230044 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java 2013-06-28 11:33:39.790235027 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -31,17 +33,11 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class XMLX509IssuerSerial extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - XMLX509IssuerSerial.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName()); /** * Constructor XMLX509IssuerSerial @@ -50,8 +46,7 @@ * @param baseURI * @throws XMLSecurityException */ - public XMLX509IssuerSerial(Element element, String baseURI) - throws XMLSecurityException { + public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException { super(element, baseURI); } @@ -62,11 +57,9 @@ * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - BigInteger x509SerialNumber) { - + public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME); addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER); } @@ -78,8 +71,7 @@ * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - String x509SerialNumber) { + public XMLX509IssuerSerial(Document doc, String x509IssuerName, String x509SerialNumber) { this(doc, x509IssuerName, new BigInteger(x509SerialNumber)); } @@ -90,10 +82,8 @@ * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - int x509SerialNumber) { - this(doc, x509IssuerName, - new BigInteger(Integer.toString(x509SerialNumber))); + public XMLX509IssuerSerial(Document doc, String x509IssuerName, int x509SerialNumber) { + this(doc, x509IssuerName, new BigInteger(Integer.toString(x509SerialNumber))); } /** @@ -103,10 +93,11 @@ * @param x509certificate */ public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) { - - this(doc, - RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()), - x509certificate.getSerialNumber()); + this( + doc, + x509certificate.getIssuerX500Principal().getName(), + x509certificate.getSerialNumber() + ); } /** @@ -115,11 +106,11 @@ * @return the serial number */ public BigInteger getSerialNumber() { - - String text = this.getTextFromChildElement - (Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); - if (log.isLoggable(java.util.logging.Level.FINE)) + String text = + this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text); + } return new BigInteger(text); } @@ -139,27 +130,28 @@ * @return the issuer name */ public String getIssuerName() { - - return RFC2253Parser - .normalize(this - .getTextFromChildElement(Constants._TAG_X509ISSUERNAME, - Constants.SignatureSpecNS)); + return RFC2253Parser.normalize( + this.getTextFromChildElement(Constants._TAG_X509ISSUERNAME, Constants.SignatureSpecNS) + ); } /** @inheritDoc */ public boolean equals(Object obj) { - - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509IssuerSerial)) { return false; } XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj; return this.getSerialNumber().equals(other.getSerialNumber()) - && this.getIssuerName().equals(other.getIssuerName()); + && this.getIssuerName().equals(other.getIssuerName()); + } + + public int hashCode() { + int result = 17; + result = 31 * result + getSerialNumber().hashCode(); + result = 31 * result + getIssuerName().hashCode(); + return result; } /** @inheritDoc */ --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java 2013-06-28 11:33:40.570210746 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java 2013-06-28 11:33:40.382216597 -0400 @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; -import java.io.IOException; -import java.io.ByteArrayInputStream; -import java.io.InputStream; import java.security.cert.X509Certificate; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; +import java.util.Arrays; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Base64; @@ -37,14 +35,13 @@ /** * Handles SubjectKeyIdentifier (SKI) for X.509v3. * - * @author $Author: mullan $ - * @see Interface X509Extension + * @see + * Interface X509Extension */ -public class XMLX509SKI extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLX509SKI.class.getName()); /** @@ -53,7 +50,7 @@ * distinct keys used by the same subject to be differentiated * (e.g., as key updating occurs). *
      - * A key identifer shall be unique with respect to all key identifiers + * A key identifier shall be unique with respect to all key identifiers * for the subject with which it is used. This extension is always non-critical. */ public static final String SKI_OID = "2.5.29.14"; @@ -77,7 +74,7 @@ * @throws XMLSecurityException */ public XMLX509SKI(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { + throws XMLSecurityException { super(doc); this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate)); } @@ -89,8 +86,7 @@ * @param BaseURI * @throws XMLSecurityException */ - public XMLX509SKI(Element element, String BaseURI) - throws XMLSecurityException { + public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } @@ -117,15 +113,14 @@ throws XMLSecurityException { if (cert.getVersion() < 3) { - Object exArgs[] = { new Integer(cert.getVersion()) }; - throw new XMLSecurityException("certificate.noSki.lowVersion", - exArgs); + Object exArgs[] = { Integer.valueOf(cert.getVersion()) }; + throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs); } /* - * Gets the DER-encoded OCTET string for the extension value - * (extnValue) identified by the passed-in oid String. The oid - * string is represented by a set of positive whole numbers + * Gets the DER-encoded OCTET string for the extension value + * (extnValue) identified by the passed-in oid String. The oid + * string is represented by a set of positive whole numbers * separated by periods. */ byte[] extensionValue = cert.getExtensionValue(XMLX509SKI.SKI_OID); @@ -134,10 +129,10 @@ } /** - * Strip away first four bytes from the extensionValue + * Strip away first four bytes from the extensionValue * The first two bytes are the tag and length of the extensionValue * OCTET STRING, and the next two bytes are the tag and length of - * the skid OCTET STRING. + * the ski OCTET STRING. */ byte skidValue[] = new byte[extensionValue.length - 4]; @@ -152,23 +147,35 @@ /** @inheritDoc */ public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509SKI)) { return false; } XMLX509SKI other = (XMLX509SKI) obj; try { - return java.security.MessageDigest.isEqual(other.getSKIBytes(), - this.getSKIBytes()); + return Arrays.equals(other.getSKIBytes(), this.getSKIBytes()); } catch (XMLSecurityException ex) { return false; } } + public int hashCode() { + int result = 17; + try { + byte[] bytes = getSKIBytes(); + for (int i = 0; i < bytes.length; i++) { + result = 31 * result + bytes[i]; + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + return result; + + } + /** @inheritDoc */ public String getBaseLocalName() { return Constants._TAG_X509SKI; --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java 2013-06-28 11:33:41.166192194 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java 2013-06-28 11:33:41.006197175 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -30,65 +32,57 @@ import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XMLX509SubjectName extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent { - /** - * Constructor X509SubjectName - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509SubjectName(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Constructor X509SubjectName - * - * @param doc - * @param X509SubjectNameString - */ - public XMLX509SubjectName(Document doc, String X509SubjectNameString) { - - super(doc); - - this.addText(X509SubjectNameString); - } - - /** - * Constructor XMLX509SubjectName - * - * @param doc - * @param x509certificate - */ - public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { - this(doc, - RFC2253Parser.normalize(x509certificate.getSubjectDN().getName())); - } - - /** - * Method getSubjectName - * - * - * @return the subject name - */ - public String getSubjectName() { - return RFC2253Parser.normalize(this.getTextFromTextChild()); - } + /** + * Constructor X509SubjectName + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509SubjectName(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor X509SubjectName + * + * @param doc + * @param X509SubjectNameString + */ + public XMLX509SubjectName(Document doc, String X509SubjectNameString) { + super(doc); + + this.addText(X509SubjectNameString); + } + + /** + * Constructor XMLX509SubjectName + * + * @param doc + * @param x509certificate + */ + public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { + this(doc, x509certificate.getSubjectX500Principal().getName()); + } + + /** + * Method getSubjectName + * + * + * @return the subject name + */ + public String getSubjectName() { + return RFC2253Parser.normalize(this.getTextFromTextChild()); + } /** @inheritDoc */ public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509SubjectName)) { return false; } @@ -97,10 +91,16 @@ String thisSubject = this.getSubjectName(); return thisSubject.equals(otherSubject); - } + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509SUBJECTNAME; - } + public int hashCode() { + int result = 17; + result = 31 * result + this.getSubjectName().hashCode(); + return result; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509SUBJECTNAME; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java 2013-06-28 11:33:41.838171281 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java 2013-06-28 11:33:41.670176507 -0400 @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * - * @author $Author: mullan $ - */ public class InvalidKeyResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor InvalidKeyResolverException - * - */ - public InvalidKeyResolverException() { - super(); - } - - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - */ - public InvalidKeyResolverException(String _msgID) { - super(_msgID); - } - - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param exArgs - */ - public InvalidKeyResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param _originalException - */ - public InvalidKeyResolverException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidKeyResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor InvalidKeyResolverException + * + */ + public InvalidKeyResolverException() { + super(); + } + + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + */ + public InvalidKeyResolverException(String msgID) { + super(msgID); + } + + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param exArgs + */ + public InvalidKeyResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param originalException + */ + public InvalidKeyResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidKeyResolverException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java 2013-06-28 11:33:42.510150360 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java 2013-06-28 11:33:42.338155717 -0400 @@ -31,10 +31,13 @@ import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.KeyInfoReferenceResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509DigestResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver; @@ -49,7 +52,7 @@ public class KeyResolver { /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(KeyResolver.class.getName()); /** Field resolverVector */ @@ -57,10 +60,10 @@ /** Field resolverSpi */ private final KeyResolverSpi resolverSpi; - + /** * Constructor. - * + * * @param keyResolverSpi a KeyResolverSpi instance */ private KeyResolver(KeyResolverSpi keyResolverSpi) { @@ -83,7 +86,7 @@ * @param baseURI * @param storage * @return The certificate represented by the element. - * + * * @throws KeyResolverException */ public static final X509Certificate getX509Certificate( @@ -94,7 +97,7 @@ Object exArgs[] = { (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE)) - ? element.getTagName() : "null") + ? element.getTagName() : "null") }; throw new KeyResolverException("utils.resolver.noClass", exArgs); @@ -111,7 +114,7 @@ Object exArgs[] = { (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE)) - ? element.getTagName() : "null") + ? element.getTagName() : "null") }; throw new KeyResolverException("utils.resolver.noClass", exArgs); @@ -124,7 +127,7 @@ * @param baseURI * @param storage * @return the public key contained in the element - * + * * @throws KeyResolverException */ public static final PublicKey getPublicKey( @@ -152,7 +155,7 @@ Object exArgs[] = { (((element != null) && (element.getNodeType() == Node.ELEMENT_NODE)) - ? element.getTagName() : "null") + ? element.getTagName() : "null") }; throw new KeyResolverException("utils.resolver.noClass", exArgs); @@ -162,18 +165,18 @@ * This method is used for registering {@link KeyResolverSpi}s which are * available to all {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that * personalized {@link KeyResolverSpi}s should only be registered directly - * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using + * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}. - * Please note that this method will create a new copy of the underlying array, as the + * Please note that this method will create a new copy of the underlying array, as the * 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 InstantiationException + * @throws IllegalAccessException + * @throws ClassNotFoundException */ - public static void register(String className, boolean globalResolver) + public static void register(String className, boolean globalResolver) throws ClassNotFoundException, IllegalAccessException, InstantiationException { KeyResolverSpi keyResolverSpi = (KeyResolverSpi) Class.forName(className).newInstance(); @@ -185,9 +188,9 @@ * This method is used for registering {@link KeyResolverSpi}s which are * available to all {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that * personalized {@link KeyResolverSpi}s should only be registered directly - * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using + * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}. - * Please note that this method will create a new copy of the underlying array, as the + * Please note that this method will create a new copy of the underlying array, as the * underlying collection is a CopyOnWriteArrayList. * * @param className @@ -213,21 +216,21 @@ keyResolverSpi.setGlobalResolver(globalResolver); register(keyResolverSpi, true); } - + /** * This method is used for registering {@link KeyResolverSpi}s which are * available to all {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that * personalized {@link KeyResolverSpi}s should only be registered directly - * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using + * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}. - * Please note that this method will create a new copy of the underlying array, as the + * Please note that this method will create a new copy of the underlying array, as the * underlying collection is a CopyOnWriteArrayList. * * @param keyResolverSpi a KeyResolverSpi instance to register * @param start whether to register the KeyResolverSpi at the start of the list or not */ public static void register( - KeyResolverSpi keyResolverSpi, + KeyResolverSpi keyResolverSpi, boolean start ) { KeyResolver resolver = new KeyResolver(keyResolverSpi); @@ -237,22 +240,22 @@ resolverVector.add(resolver); } } - + /** * This method is used for registering {@link KeyResolverSpi}s which are * available to all {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} objects. This means that * personalized {@link KeyResolverSpi}s should only be registered directly - * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using + * to the {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo} using * {@link com.sun.org.apache.xml.internal.security.keys.KeyInfo#registerInternalKeyResolver}. * The KeyResolverSpi instances are not registered as a global resolver. - * + * * * @param classNames - * @throws InstantiationException - * @throws IllegalAccessException - * @throws ClassNotFoundException + * @throws InstantiationException + * @throws IllegalAccessException + * @throws ClassNotFoundException */ - public static void registerClassNames(List classNames) + public static void registerClassNames(List classNames) throws ClassNotFoundException, IllegalAccessException, InstantiationException { List keyResolverList = new ArrayList(classNames.size()); for (String className : classNames) { @@ -263,12 +266,12 @@ } resolverVector.addAll(keyResolverList); } - + /** * This method registers the default resolvers. */ public static void registerDefaultResolvers() { - + List keyResolverList = new ArrayList(); keyResolverList.add(new KeyResolver(new RSAKeyValueResolver())); keyResolverList.add(new KeyResolver(new DSAKeyValueResolver())); @@ -277,7 +280,10 @@ 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())); + resolverVector.addAll(keyResolverList); } @@ -286,9 +292,9 @@ * * @param element * @param baseURI - * @param storage + * @param storage * @return resolved public key from the registered from the elements - * + * * @throws KeyResolverException */ public PublicKey resolvePublicKey( @@ -304,7 +310,7 @@ * @param baseURI * @param storage * @return resolved X509certificate key from the registered from the elements - * + * * @throws KeyResolverException */ public X509Certificate resolveX509Certificate( --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java 2013-06-28 11:33:43.214128451 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java 2013-06-28 11:33:43.042133804 -0400 @@ -2,90 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * - * - * - * @author $Author: mullan $ - * - */ public class KeyResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor KeyResolverException - * - */ - public KeyResolverException() { - super(); - } - - /** - * Constructor KeyResolverException - * - * @param _msgID - */ - public KeyResolverException(String _msgID) { - super(_msgID); - } - - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param exArgs - */ - public KeyResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param _originalException - */ - public KeyResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public KeyResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor KeyResolverException + * + */ + public KeyResolverException() { + super(); + } + + /** + * Constructor KeyResolverException + * + * @param msgID + */ + public KeyResolverException(String msgID) { + super(msgID); + } + + /** + * Constructor KeyResolverException + * + * @param msgID + * @param exArgs + */ + public KeyResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor KeyResolverException + * + * @param msgID + * @param originalException + */ + public KeyResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor KeyResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public KeyResolverException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java 2013-06-28 11:33:43.818109647 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java 2013-06-28 11:33:43.654114754 -0400 @@ -2,24 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.HashMap; @@ -30,78 +33,89 @@ import org.w3c.dom.Element; /** - * This class is abstract class for a child KeyInfo Elemnet. + * This class is an abstract class for a child KeyInfo Element. * - * If you want your KeyResolver, at first you must extend this class, and register + * If you want the your KeyResolver, at firstly you must extend this class, and register * as following in config.xml *

        *  <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
        *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
        * 
      - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public abstract class KeyResolverSpi { - /** - * This method helps the {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} to decide whether a - * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi} is able to perform the requested action. - * - * @param element - * @param BaseURI - * @param storage - * @return - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - throw new UnsupportedOperationException(); - } - - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @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(); + + /** Field properties */ + protected java.util.Map properties = null; + + 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. + * + * @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) { + throw new UnsupportedOperationException(); + } + + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @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(); }; - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolvePublicKey(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolvePublicKey(element, baseURI, storage); } private KeyResolverSpi cloneIfNeeded() throws KeyResolverException { - KeyResolverSpi tmp=this; + KeyResolverSpi tmp = this; if (globalResolver) { - try { - tmp = (KeyResolverSpi) getClass().newInstance(); - } catch (InstantiationException e) { - throw new KeyResolverException("",e); - } catch (IllegalAccessException e) { - throw new KeyResolverException("",e); - } + try { + tmp = getClass().newInstance(); + } catch (InstantiationException e) { + throw new KeyResolverException("", e); + } catch (IllegalAccessException e) { + throw new KeyResolverException("", e); + } } return tmp; } @@ -110,116 +124,138 @@ * Method engineResolveCertificate * * @param element - * @param BaseURI + * @param baseURI * @param storage * @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(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveCertificate - * - * @param element - * @param BaseURI - * @param storage - * @return resolved X509Certificate key from the registered from the elements - * - * @throws KeyResolverException - */ + /** + * Method engineLookupResolveX509Certificate + * + * @param element + * @param baseURI + * @param storage + * @return resolved X509Certificate key from the registered from the elements + * + * @throws KeyResolverException + */ public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveX509Certificate(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveX509Certificate(element, baseURI, storage); } /** * Method engineResolveSecretKey * * @param element - * @param BaseURI + * @param baseURI * @param storage * @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(); - }; + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); + }; + + /** + * Method engineLookupAndResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveSecretKey(element, baseURI, storage); + } - /** - * Method engineResolveSecretKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved SecretKey key from the registered from the elements - * - * @throws KeyResolverException - */ - public SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveSecretKey(element, BaseURI, storage); - } - - /** Field _properties */ - protected java.util.Map _properties = null; - - protected boolean globalResolver=false; - - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) - _properties=new HashMap(); - this._properties.put(key, value); - } - - /** - * Method engineGetProperty - * - * @param key - * @return obtain the property appointed by key - */ - public String engineGetProperty(String key) { - if (_properties==null) - return null; - - return this._properties.get(key); - } - - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understood the property - */ - public boolean understandsProperty(String propertyToTest) { - if (_properties==null) - return false; - - return this._properties.get(propertyToTest)!=null; - } - public void setGlobalResolver(boolean globalResolver) { + /** + * Method engineLookupAndResolvePrivateKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) 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) { + return null; + } + + return properties.get(key); + } + + /** + * 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; - } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java 2013-06-28 11:33:44.518087860 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java 2013-06-28 11:33:44.350093090 -0400 @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; @@ -34,66 +33,70 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class DSAKeyValueResolver extends KeyResolverSpi { - - /** - * 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) { - if (element == null) { - return null; - } - Element dsaKeyElement=null; - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - if (isKeyValue) { - dsaKeyElement = - XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_DSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:DSAKeyValue directly (without KeyValue) - dsaKeyElement = element; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName()); + + + /** + * 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 + ) { + if (element == null) { + return null; + } + Element dsaKeyElement = null; + boolean isKeyValue = + XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + if (isKeyValue) { + dsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:DSAKeyValue directly (without KeyValue) + dsaKeyElement = element; + } + + if (dsaKeyElement == null) { + return null; + } + + try { + DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI); + PublicKey pk = dsaKeyValue.getPublicKey(); + + return pk; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); } + //do nothing + } + + return null; + } + - if (dsaKeyElement == null) { - return null; - } - - try { - DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, - BaseURI); - PublicKey pk = dsaKeyValue.getPublicKey(); - - return pk; - } catch (XMLSecurityException ex) { - //do nothing - } - - return null; - } - - - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage){ - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } + + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java 2013-06-28 11:33:45.202066568 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java 2013-06-28 11:33:45.030071923 -0400 @@ -2,123 +2,149 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; import java.security.Key; import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; import javax.crypto.SecretKey; import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey; import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; +import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** - * The EncryptedKeyResolver is not a generic resolver. It can - * only be for specific instantiations, as the key being unwrapped will - * always be of a particular type and will always have been wrapped by + * The EncryptedKeyResolver is not a generic resolver. It can + * only be for specific instantiations, as the key being unwrapped will + * always be of a particular type and will always have been wrapped by * another key which needs to be recursively resolved. * * The EncryptedKeyResolver can therefore only be instantiated - * with an algorithm. It can also be instantiated with a key (the KEK) or + * with an algorithm. It can also be instantiated with a key (the KEK) or * will search the static KeyResolvers to find the appropriate key. * * @author Berin Lautenbach */ - public class EncryptedKeyResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); - - - Key _kek; - String _algorithm; - - /** - * Constructor for use when a KEK needs to be derived from a KeyInfo - * list - * @param algorithm - */ - public EncryptedKeyResolver(String algorithm) { - _kek = null; - _algorithm=algorithm; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(EncryptedKeyResolver.class.getName()); + + private Key kek; + private String algorithm; + private List internalKeyResolvers; + + /** + * Constructor for use when a KEK needs to be derived from a KeyInfo + * list + * @param algorithm + */ + public EncryptedKeyResolver(String algorithm) { + kek = null; + this.algorithm = algorithm; + } + + /** + * Constructor used for when a KEK has been set + * @param algorithm + * @param kek + */ + public EncryptedKeyResolver(String algorithm, Key kek) { + this.algorithm = algorithm; + this.kek = kek; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to help + * resolve the KEK. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + if (internalKeyResolvers == null) { + internalKeyResolvers = new ArrayList(); } + internalKeyResolvers.add(realKeyResolver); + } - /** - * Constructor used for when a KEK has been set - * @param algorithm - * @param kek - */ - - public EncryptedKeyResolver(String algorithm, Key kek) { - _algorithm = algorithm; - _kek = kek; + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + } - return null; - } + if (element == null) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - SecretKey key=null; - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); - - if (element == null) { - return null; - } - - boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, - EncryptionConstants._TAG_ENCRYPTEDKEY); - - if (isEncryptedKey) { - log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); - try { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, _kek); - EncryptedKey ek = cipher.loadEncryptedKey(element); - key = (SecretKey) cipher.decryptKey(ek, _algorithm); - } - catch (Exception e) {} - } + SecretKey key = null; + boolean isEncryptedKey = + XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY); + if (isEncryptedKey) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); + } + try { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, kek); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + cipher.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + EncryptedKey ek = cipher.loadEncryptedKey(element); + key = (SecretKey) cipher.decryptKey(ek, algorithm); + } catch (XMLEncryptionException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + } - return key; - } + return key; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java 2013-06-28 11:33:45.910044530 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java 2013-06-28 11:33:45.734050012 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -34,69 +34,63 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class RSAKeyValueResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); - - /** Field _rsaKeyElement */ - - - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); - if (element == null) { - return null; - } - - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - Element rsaKeyElement=null; - if (isKeyValue) { - rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_RSAKEYVALUE, 0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:RSAKeyValue directly (without KeyValue) - rsaKeyElement = element; - } - - - if (rsaKeyElement == null) { - return null; - } - - try { - RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, - BaseURI); - - return rsaKeyValue.getPublicKey(); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } - - return null; - } - - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RSAKeyValueResolver.class.getName()); + + + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + if (element == null) { + return null; + } + + boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + Element rsaKeyElement = null; + if (isKeyValue) { + rsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:RSAKeyValue directly (without KeyValue) + rsaKeyElement = element; + } + + if (rsaKeyElement == null) { + return null; + } + + try { + RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI); + + return rsaKeyValue.getPublicKey(); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } + + return null; + } + + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } + + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java 2013-06-28 11:33:46.538024986 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java 2013-06-28 11:33:46.370030215 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.PublicKey; @@ -35,6 +35,8 @@ import java.util.Set; import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -51,11 +53,11 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * The RetrievalMethodResolver can retrieve public keys and certificates from * other locations. The location is specified using the ds:RetrievalMethod @@ -65,252 +67,325 @@ * RetrievalMethodResolver cannot handle itself, resolving of the extracted * element is delegated back to the KeyResolver mechanism. * - * @author $Author: mullan $ modified by Dave Garcia + * @author $Author: raul $ modified by Dave Garcia */ public class RetrievalMethodResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RetrievalMethodResolver.class.getName()); - - /** - * 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; - } - - try { - //Create a retrieval method over the given element - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - //a raw certificate, direct parsing is done! - X509Certificate cert=getRawCertificate(resource); - if (cert != null) { - return cert.getPublicKey(); - } - return null; - }; - Element e = obtainRefrenceElement(resource); - return resolveKey(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - static private Element obtainRefrenceElement(XMLSignatureInput resource) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException { - Element e; - if (resource.isElement()){ - e=(Element) resource.getSubNode(); - } else if (resource.isNodeSet()) { - //Retrieved resource is a nodeSet - e=getDocumentElement(resource.getNodeSet()); - } else { - //Retrieved resource is an inputStream - byte inputBytes[] = resource.getBytes(); - e = getDocFromBytes(inputBytes); - //otherwise, we parse the resource, create an Element and delegate - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); - } - return e; - } - - /** - * 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; - } - - try { - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - X509Certificate cert=getRawCertificate(resource); - return cert; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RetrievalMethodResolver.class.getName()); + + /** + * 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; + } + + try { + // Create a retrieval method over the given element + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + // a raw certificate, direct parsing is done! + X509Certificate cert = getRawCertificate(resource); + if (cert != null) { + return cert.getPublicKey(); + } + return null; + } + Element e = obtainReferenceElement(resource); + + // 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) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; } - Element e = obtainRefrenceElement(resource); - return resolveCertificate(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { + } + + return resolveKey(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private X509Certificate resolveCertificate(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getX509Certificate(e,BaseURI, storage); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private PublicKey resolveKey(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getPublicKey(e,BaseURI, storage); - } - return null; - } - - static private X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException{ - byte inputBytes[] = resource.getBytes(); - // if the resource stores a raw certificate, we have to handle it - CertificateFactory certFact =CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert =(X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); - return cert; - } - /** - * Resolves the input from the given retrieval method - * @return - * @throws XMLSecurityException - */ - static private XMLSignatureInput resolveInput(RetrievalMethod rm,String BaseURI) throws XMLSecurityException{ - Attr uri = rm.getURIAttr(); - //Apply the trnasforms - Transforms transforms = rm.getTransforms(); - ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); - if (resRes != null) { - XMLSignatureInput resource = resRes.resolve(uri, BaseURI); - if (transforms != null) { - log.log(java.util.logging.Level.FINE, "We have Transforms"); - resource = transforms.performTransforms(resource); - } - return resource; - } - return null; - } - - /** - * Parses a byte array and returns the parsed Element. - * - * @param bytes - * @return the Document Element after parsing bytes - * @throws KeyResolverException if something goes wrong - */ - static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { - try { - javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); - org.w3c.dom.Document doc = - db.parse(new java.io.ByteArrayInputStream(bytes)); - return doc.getDocumentElement(); - } catch (org.xml.sax.SAXException ex) { - throw new KeyResolverException("empty", ex); - } catch (java.io.IOException ex) { - throw new KeyResolverException("empty", ex); - } catch (javax.xml.parsers.ParserConfigurationException ex) { - throw new KeyResolverException("empty", ex); - } - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } - - static Element getDocumentElement(Set set) { - Iterator it=set.iterator(); - Element e=null; - while (it.hasNext()) { - Node currentNode=it.next(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) { - e=(Element)currentNode; - break; - } - - } - List parents=new ArrayList(10); - - //Obtain all the parents of the elemnt - while (e != null) { - parents.add(e); - Node n=e.getParentNode(); - if (n == null || n.getNodeType() != Node.ELEMENT_NODE) { - break; - } - e=(Element)n; + } + } + 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; + } + + try { + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + return getRawCertificate(resource); + } + + Element e = obtainReferenceElement(resource); + + // 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) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; } - //Visit them in reverse order. - ListIterator it2=parents.listIterator(parents.size()-1); - Element ele=null; - while (it2.hasPrevious()) { - ele=it2.previous(); - if (set.contains(ele)) { - return ele; - } + } + + return resolveCertificate(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Retrieves a x509Certificate from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static X509Certificate resolveCertificate( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); } - return null; - } + // An element has been provided + if (e != null) { + return KeyResolver.getX509Certificate(e, baseURI, storage); + } + return null; + } + + /** + * Retrieves a PublicKey from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static PublicKey resolveKey( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getPublicKey(e, baseURI, storage); + } + return null; + } + + private static Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + // Retrieved resource is a nodeSet + e = getDocumentElement(resource.getNodeSet()); + } else { + // Retrieved resource is an inputStream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + // otherwise, we parse the resource, create an Element and delegate + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); + } + } + return e; + } + + private static X509Certificate getRawCertificate(XMLSignatureInput resource) + throws CanonicalizationException, IOException, CertificateException { + byte inputBytes[] = resource.getBytes(); + // if the resource stores a raw certificate, we have to handle it + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = (X509Certificate) + certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); + return cert; + } + + /** + * Resolves the input from the given retrieval method + * @return + * @throws XMLSecurityException + */ + private static XMLSignatureInput resolveInput( + RetrievalMethod rm, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + Attr uri = rm.getURIAttr(); + // Apply the transforms + Transforms transforms = rm.getTransforms(); + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + if (transforms != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have Transforms"); + } + resource = transforms.performTransforms(resource); + } + return resource; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } + + private static Element getDocumentElement(Set set) { + Iterator it = set.iterator(); + Element e = null; + while (it.hasNext()) { + Node currentNode = it.next(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + e = (Element) currentNode; + break; + } + } + List parents = new ArrayList(); + + // Obtain all the parents of the elemnt + while (e != null) { + parents.add(e); + Node n = e.getParentNode(); + if (n == null || Node.ELEMENT_NODE != n.getNodeType()) { + break; + } + e = (Element) n; + } + // Visit them in reverse order. + ListIterator it2 = parents.listIterator(parents.size()-1); + Element ele = null; + while (it2.hasPrevious()) { + ele = (Element) it2.previous(); + if (set.contains(ele)) { + return ele; + } + } + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java 2013-06-28 11:33:47.170005311 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java 2013-06-28 11:33:46.998010663 -0400 @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; @@ -35,96 +34,93 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * Resolves Certificates which are directly contained inside a * ds:X509Certificate Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class X509CertificateResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName()); + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, BaseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + + try { + Element[] els = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE); + if ((els == null) || (els.length == 0)) { + Element el = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0); + if (el != null) { + return engineLookupResolveX509Certificate(el, BaseURI, storage); + } + return null; + } - - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); - - if (cert != null) { - return cert.getPublicKey(); - } - - return null; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - try { - Element[] els=XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509CERTIFICATE); - if ((els == null) || (els.length == 0)) { - Element el=XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_X509DATA,0); - if (el!=null) { - return engineLookupResolveX509Certificate(el, BaseURI, storage); - } - return null; - } - - // populate Object array - for (int i = 0; i < els.length; i++) { - XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI); - X509Certificate cert = xmlCert.getX509Certificate(); - if (cert!=null) { - return cert; + // populate Object array + for (int i = 0; i < els.length; i++) { + XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI); + X509Certificate cert = xmlCert.getX509Certificate(); + if (cert != null) { + return cert; + } + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java 2013-06-28 11:33:47.833984646 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java 2013-06-28 11:33:47.645990493 -0400 @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; @@ -35,114 +37,114 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509IssuerSerialResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509IssuerSerialResolver.class.getName()); - - - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); - - if (cert != null) { - return cert.getPublicKey(); - } - - return null; - } - - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - X509Data x509data = null; - try { - x509data = new X509Data(element, BaseURI); - } catch (XMLSignatureException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (x509data == null) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (!x509data.containsIssuerSerial()) { - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - throw ex; - } - - int noOfISS = x509data.lengthIssuerSerial(); - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); - + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName()); + + + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + X509Data x509data = null; + try { + x509data = new X509Data(element, baseURI); + } catch (XMLSignatureException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } catch (XMLSecurityException ex) { if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " - + certSerial.getIssuerName()); - log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " - + certSerial.getSerialNumber().toString()); + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + if (!x509data.containsIssuerSerial()) { + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; } - for (int i=0; i storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString()); + } + + for (int i = 0; i < noOfISS; i++) { + XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element Issuer: " + + xmliss.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Element Serial: " + + xmliss.getSerialNumber().toString()); + } + + if (certSerial.equals(xmliss)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Found Element Issuer: " - + xmliss.getIssuerName()); - log.log(java.util.logging.Level.FINE, "Found Element Serial: " - + xmliss.getSerialNumber().toString()); - } - - if (certSerial.equals(xmliss)) { - log.log(java.util.logging.Level.FINE, "match !!! "); - - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } + + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java 2013-06-28 11:33:48.533962854 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java 2013-06-28 11:33:48.341968832 -0400 @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,124 +37,121 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * - * @author $Author: mullan $ - */ public class X509SKIResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509SKIResolver.class.getName()); - /** - * 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) - throws KeyResolverException { - - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); - - if (cert != null) { - return cert.getPublicKey(); - } - - return null; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - } - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA)) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - /** Field _x509childObject[] */ - XMLX509SKI x509childObject[] = null; - - Element x509childNodes[] = null; - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SKI); - - if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SKI }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = new XMLX509SKI[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SKI(x509childNodes[i], BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); - - for (int i = 0; i < x509childObject.length; i++) { - if (certSKI.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "Return PublicKey from " - + cert.getSubjectDN().getName()); + /** + * 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 + ) throws KeyResolverException { + + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + /** Field _x509childObject[] */ + XMLX509SKI x509childObject[] = null; + + Element x509childNodes[] = null; + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); + + if (!((x509childNodes != null) && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SKI }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; + } + + x509childObject = new XMLX509SKI[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI); + } - return cert; - } + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); + + for (int i = 0; i < x509childObject.length; i++) { + if (certSKI.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName()); + } + + return cert; + } + } } - } - } catch (XMLSecurityException ex) { - throw new KeyResolverException("empty", ex); - } - - return null; - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java 2013-06-28 11:33:49.149943682 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java 2013-06-28 11:33:48.973949162 -0400 @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,133 +37,140 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509SubjectNameResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509SubjectNameResolver.class.getName()); - - - /** - * 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) - throws KeyResolverException { - - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); - - if (cert != null) { - return cert.getPublicKey(); - } - - return null; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - Element[] x509childNodes = null; - XMLX509SubjectName x509childObject[] = null; - - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA) ) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SUBJECTNAME); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName()); + + + /** + * 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 + ) throws KeyResolverException { + + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + Element[] x509childNodes = null; + XMLX509SubjectName x509childObject[] = null; + + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + x509childNodes = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME); if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = - new XMLX509SubjectName[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SubjectName(x509childNodes[i], - BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SubjectName certSN = - new XMLX509SubjectName(element.getOwnerDocument(), cert); - - log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); - - for (int i = 0; i < x509childObject.length; i++) { - log.log(java.util.logging.Level.FINE, "Found Element SN: " - + x509childObject[i].getSubjectName()); - - if (certSN.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "match !!! "); - - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); - } - } - - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; + } + + x509childObject = new XMLX509SubjectName[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SubjectName certSN = + new XMLX509SubjectName(element.getOwnerDocument(), cert); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); + } + + for (int i = 0; i < x509childObject.length; i++) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element SN: " + + x509childObject[i].getSubjectName()); + } + + if (certSN.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } + } + + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java 2013-06-28 11:33:49.789923763 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java 2013-06-28 11:33:49.613929239 -0400 @@ -2,197 +2,187 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; import java.security.KeyStore; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.SingleCertificateResolver; - /** * This class collects customized resolvers for Certificates. - * - * @author $Author: mullan $ */ public class StorageResolver { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(StorageResolver.class.getName()); - /** Field _storageResolvers */ - List _storageResolvers = null; - - /** Field _iterator */ - Iterator _iterator = null; + /** Field storageResolvers */ + private List storageResolvers = null; - /** - * Constructor StorageResolver - * - */ - public StorageResolver() {} - - /** - * Constructor StorageResolver - * - * @param resolver - */ - public StorageResolver(StorageResolverSpi resolver) { - this.add(resolver); - } - - /** - * Method addResolver - * - * @param resolver - */ - public void add(StorageResolverSpi resolver) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._storageResolvers.add(resolver); - - this._iterator = null; - } - - /** - * Constructor StorageResolver - * - * @param keyStore - */ - public StorageResolver(KeyStore keyStore) { - this.add(keyStore); - } - - /** - * Method addKeyStore - * - * @param keyStore - */ - public void add(KeyStore keyStore) { - - try { - this.add(new KeyStoreResolver(keyStore)); - } catch (StorageResolverException ex) { - log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); - } - } - - /** - * Constructor StorageResolver - * - * @param x509certificate - */ - public StorageResolver(X509Certificate x509certificate) { - this.add(x509certificate); - } - - /** - * Method addCertificate - * - * @param x509certificate - */ - public void add(X509Certificate x509certificate) { - this.add(new SingleCertificateResolver(x509certificate)); - } - - /** - * Method getIterator - * @return the iterator for the resolvers. - * - */ - public Iterator getIterator() { - - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } - - return this._iterator; - } - - /** - * Method hasNext - * - * @return true if there is more elements. - */ - public boolean hasNext() { - - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } - - return this._iterator.hasNext(); - } - - /** - * Method next - * - * @return the next element - */ - public X509Certificate next() { - return (X509Certificate) this._iterator.next(); - } - - /** - * Class StorageResolverIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class StorageResolverIterator implements Iterator { - - /** Field _resolvers */ - Iterator _resolvers = null; - - /** - * Constructor FilesystemIterator - * - * @param resolvers - */ - public StorageResolverIterator(Iterator resolvers) { - this._resolvers = resolvers; - } - - /** @inheritDoc */ - public boolean hasNext() { - return _resolvers.hasNext(); - } - - /** @inheritDoc */ - public Object next() { - return _resolvers.next(); - } - - /** - * Method remove - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Constructor StorageResolver + * + */ + public StorageResolver() {} + + /** + * Constructor StorageResolver + * + * @param resolver + */ + public StorageResolver(StorageResolverSpi resolver) { + this.add(resolver); + } + + /** + * Method addResolver + * + * @param resolver + */ + public void add(StorageResolverSpi resolver) { + if (storageResolvers == null) { + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(resolver); + } + + /** + * Constructor StorageResolver + * + * @param keyStore + */ + public StorageResolver(KeyStore keyStore) { + this.add(keyStore); + } + + /** + * Method addKeyStore + * + * @param keyStore + */ + public void add(KeyStore keyStore) { + try { + this.add(new KeyStoreResolver(keyStore)); + } catch (StorageResolverException ex) { + log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); + } + } + + /** + * Constructor StorageResolver + * + * @param x509certificate + */ + public StorageResolver(X509Certificate x509certificate) { + this.add(x509certificate); + } + + /** + * Method addCertificate + * + * @param x509certificate + */ + public void add(X509Certificate x509certificate) { + this.add(new SingleCertificateResolver(x509certificate)); + } + + /** + * Method getIterator + * @return the iterator for the resolvers. + */ + public Iterator getIterator() { + return new StorageResolverIterator(this.storageResolvers.iterator()); + } + + /** + * Class StorageResolverIterator + * This iterates over all the Certificates found in all the resolvers. + */ + static class StorageResolverIterator implements Iterator { + + /** Field resolvers */ + Iterator resolvers = null; + + /** Field currentResolver */ + Iterator currentResolver = null; + + /** + * Constructor StorageResolverIterator + * + * @param resolvers + */ + public StorageResolverIterator(Iterator resolvers) { + this.resolvers = resolvers; + currentResolver = findNextResolver(); + } + + /** @inheritDoc */ + public boolean hasNext() { + if (currentResolver == null) { + return false; + } + + if (currentResolver.hasNext()) { + return true; + } + + currentResolver = findNextResolver(); + return (currentResolver != null); + } + + /** @inheritDoc */ + public Certificate next() { + if (hasNext()) { + return currentResolver.next(); + } + + throw new NoSuchElementException(); + } + + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + + // Find the next storage with at least one element and return its Iterator + private Iterator findNextResolver() { + while (resolvers.hasNext()) { + StorageResolverSpi resolverSpi = resolvers.next(); + Iterator iter = resolverSpi.getIterator(); + if (iter.hasNext()) { + return iter; + } + } + + return null; + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java 2013-06-28 11:33:50.417904215 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java 2013-06-28 11:33:50.245909564 -0400 @@ -2,86 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * @author $Author: mullan $ - */ public class StorageResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor StorageResolverException - * - */ - public StorageResolverException() { - super(); - } - - /** - * Constructor StorageResolverException - * - * @param _msgID - */ - public StorageResolverException(String _msgID) { - super(_msgID); - } - - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - */ - public StorageResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param _originalException - */ - public StorageResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public StorageResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor StorageResolverException + * + */ + public StorageResolverException() { + super(); + } + + /** + * Constructor StorageResolverException + * + * @param msgID + */ + public StorageResolverException(String msgID) { + super(msgID); + } + + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + */ + public StorageResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor StorageResolverException + * + * @param msgID + * @param originalException + */ + public StorageResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public StorageResolverException(String msgID, Object exArgs[], + Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java 2013-06-28 11:33:51.117882423 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java 2013-06-28 11:33:50.925888401 -0400 @@ -2,39 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; - - +import java.security.cert.Certificate; import java.util.Iterator; - -/** - * - * @author $Author: mullan $ - */ public abstract class StorageResolverSpi { - /** - * Method getIterator - * - * @return the iterator for the storage - */ - public abstract Iterator getIterator(); + /** + * Method getIterator + * + * @return the iterator for the storage + */ + public abstract Iterator getIterator(); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java 2013-06-28 11:33:51.741863002 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java 2013-06-28 11:33:51.557868729 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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; @@ -24,6 +26,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; @@ -39,188 +42,188 @@ /** * 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}. - * - * @author $Author: mullan $ + * 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 { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger( - CertsInFilesystemDirectoryResolver.class.getName()); + CertsInFilesystemDirectoryResolver.class.getName() + ); - /** Field _merlinsCertificatesDir */ - String _merlinsCertificatesDir = null; + /** Field merlinsCertificatesDir */ + private String merlinsCertificatesDir = null; - /** Field _certs */ - private List _certs = new ArrayList(); + /** Field certs */ + private List certs = new ArrayList(); - /** Field _iterator */ - Iterator _iterator = null; - - /** - * - * - * @param directoryName - * @throws StorageResolverException - */ - public CertsInFilesystemDirectoryResolver(String directoryName) - throws StorageResolverException { - - this._merlinsCertificatesDir = directoryName; - - this.readCertsFromHarddrive(); - - this._iterator = new FilesystemIterator(this._certs); - } - - /** - * Method readCertsFromHarddrive - * - * @throws StorageResolverException - */ - private void readCertsFromHarddrive() throws StorageResolverException { - - File certDir = new File(this._merlinsCertificatesDir); - ArrayList al = new ArrayList(); - String[] names = certDir.list(); - - 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("empty", ex); - } - - if (cf == null) { - throw new StorageResolverException("empty"); - } - - for (int i = 0; i < al.size(); i++) { - String filename = certDir.getAbsolutePath() + File.separator - + al.get(i); - File file = new File(filename); - boolean added = false; - String dn = null; - - try { - FileInputStream fis = new FileInputStream(file); - X509Certificate cert = - (X509Certificate) cf.generateCertificate(fis); - - fis.close(); - - //add to ArrayList - cert.checkValidity(); - this._certs.add(cert); - - dn = cert.getSubjectDN().getName(); - added = true; - } catch (FileNotFoundException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateNotYetValidException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateExpiredException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } + /** + * @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(); + + 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("empty", ex); + } + + if (cf == null) { + throw new StorageResolverException("empty"); + } + + for (int i = 0; i < al.size(); i++) { + String filename = certDir.getAbsolutePath() + File.separator + al.get(i); + File file = new File(filename); + boolean added = false; + String dn = null; + + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + X509Certificate cert = + (X509Certificate) cf.generateCertificate(fis); + + //add to ArrayList + cert.checkValidity(); + this.certs.add(cert); + + dn = cert.getSubjectX500Principal().getName(); + added = true; + } catch (FileNotFoundException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateNotYetValidException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateExpiredException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } finally { + try { + if (fis != null) { + fis.close(); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } + } - if (added) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (added && log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); - } - } - } - - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } - - /** - * Class FilesystemIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - private static class FilesystemIterator implements Iterator { - - /** Field _certs */ - List _certs = null; - - /** Field _i */ - 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 X509Certificate 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 = 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())= \"" - + Base64.encode(ski) + "\""); - System.out.println("cert.getSerialNumber()= \"" - + cert.getSerialNumber().toString() + "\""); - System.out.println("cert.getSubjectDN().getName()= \"" - + cert.getSubjectDN().getName() + "\""); - System.out.println("cert.getIssuerDN().getName()= \"" - + cert.getIssuerDN().getName() + "\""); - } - } + } + } + } + + /** @inheritDoc */ + public Iterator getIterator() { + return new FilesystemIterator(this.certs); + } + + /** + * Class FilesystemIterator + */ + private static class FilesystemIterator implements Iterator { + + /** Field certs */ + List certs = null; + + /** Field i */ + 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())= \"" + + Base64.encode(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() + "\""); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java 2013-06-28 11:33:52.357843830 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java 2013-06-28 11:33:52.185849179 -0400 @@ -2,147 +2,152 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.cert.X509Certificate; +import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * Makes the Certificates from a JAVA {@link KeyStore} object available to the * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class KeyStoreResolver extends StorageResolverSpi { - /** Field _keyStore */ - KeyStore _keyStore = null; - - /** Field _iterator */ - Iterator _iterator = null; + /** Field keyStore */ + private KeyStore keyStore = null; - /** - * Constructor KeyStoreResolver - * - * @param keyStore is the keystore which contains the Certificates - * @throws StorageResolverException - */ - public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { - this._keyStore = keyStore; - this._iterator = new KeyStoreIterator(this._keyStore); - } - - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } - - /** - * Class KeyStoreIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class KeyStoreIterator implements Iterator { - - /** Field _keyStore */ - KeyStore _keyStore = null; - - /** Field _aliases */ - Enumeration _aliases = null; - - /** - * Constructor KeyStoreIterator - * - * @param keyStore - * @throws StorageResolverException - */ - public KeyStoreIterator(KeyStore keyStore) - throws StorageResolverException { - - try { - this._keyStore = keyStore; - this._aliases = this._keyStore.aliases(); - } catch (KeyStoreException ex) { + /** + * Constructor KeyStoreResolver + * + * @param keyStore is the keystore which contains the Certificates + * @throws StorageResolverException + */ + public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { + this.keyStore = keyStore; + // Do a quick check on the keystore + try { + keyStore.aliases(); + } catch (KeyStoreException ex) { throw new StorageResolverException("generic.EmptyMessage", ex); - } - } + } + } + + /** @inheritDoc */ + public Iterator getIterator() { + return new KeyStoreIterator(this.keyStore); + } + + /** + * Class KeyStoreIterator + */ + static class KeyStoreIterator implements Iterator { + + /** Field keyStore */ + KeyStore keyStore = null; + + /** Field aliases */ + Enumeration aliases = null; + + /** Field nextCert */ + Certificate nextCert = null; + + /** + * Constructor KeyStoreIterator + * + * @param keyStore + */ + public KeyStoreIterator(KeyStore keyStore) { + try { + this.keyStore = keyStore; + this.aliases = this.keyStore.aliases(); + } catch (KeyStoreException ex) { + // empty Enumeration + this.aliases = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public String nextElement() { + return null; + } + }; + } + } + + /** @inheritDoc */ + public boolean hasNext() { + if (nextCert == null) { + nextCert = findNextCert(); + } + + return (nextCert != null); + } + + /** @inheritDoc */ + public Certificate next() { + if (nextCert == null) { + // maybe caller did not call hasNext() + nextCert = findNextCert(); + + if (nextCert == null) { + throw new NoSuchElementException(); + } + } + + Certificate ret = nextCert; + nextCert = null; + return ret; + } + + /** + * Method remove + */ + public void remove() { + 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; + } + } - /** @inheritDoc */ - public boolean hasNext() { - return this._aliases.hasMoreElements(); - } - - /** @inheritDoc */ - @SuppressWarnings("unchecked") - public X509Certificate next() { - - String alias = this._aliases.nextElement(); - - try { - return (X509Certificate)this._keyStore.getCertificate(alias); - } catch (KeyStoreException ex) { return null; - } - } + } + + } - /** - * 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 { - - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - - ks.load( - new java.io.FileInputStream( - "data/com/sun/org/apache/xml/internal/security/samples/input/keystore.jks"), - "xmlsecurity".toCharArray()); - - KeyStoreResolver krs = new KeyStoreResolver(ks); - - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); - - System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski)); - } - } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java 2013-06-28 11:33:52.949825401 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java 2013-06-28 11:33:52.781830627 -0400 @@ -2,102 +2,93 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * This {@link StorageResolverSpi} makes a single {@link X509Certificate} * available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class SingleCertificateResolver extends StorageResolverSpi { - /** Field _certificate */ - X509Certificate _certificate = null; - - /** Field _iterator */ - Iterator _iterator = null; + /** Field certificate */ + private X509Certificate certificate = null; - /** - * - * - * @param x509cert the single {@link X509Certificate} - */ - public SingleCertificateResolver(X509Certificate x509cert) { - this._certificate = x509cert; - this._iterator = new InternalIterator(this._certificate); - } - - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } - - /** - * Class InternalIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class InternalIterator implements Iterator { - - /** Field _alreadyReturned */ - boolean _alreadyReturned = false; - - /** Field _certificate */ - X509Certificate _certificate = null; - - /** - * Constructor InternalIterator - * - * @param x509cert - */ - public InternalIterator(X509Certificate x509cert) { - this._certificate = x509cert; - } - - /** @inheritDoc */ - public boolean hasNext() { - return (!this._alreadyReturned); - } - - /** @inheritDoc */ - public X509Certificate next() { - - this._alreadyReturned = true; - - return this._certificate; - } - - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * @param x509cert the single {@link X509Certificate} + */ + public SingleCertificateResolver(X509Certificate x509cert) { + this.certificate = x509cert; + } + + /** @inheritDoc */ + public Iterator getIterator() { + return new InternalIterator(this.certificate); + } + + /** + * Class InternalIterator + */ + static class InternalIterator implements Iterator { + + /** Field alreadyReturned */ + boolean alreadyReturned = false; + + /** Field certificate */ + X509Certificate certificate = null; + + /** + * Constructor InternalIterator + * + * @param x509cert + */ + public InternalIterator(X509Certificate x509cert) { + this.certificate = x509cert; + } + + /** @inheritDoc */ + public boolean hasNext() { + return !this.alreadyReturned; + } + + /** @inheritDoc */ + public Certificate next() { + if (this.alreadyReturned) { + throw new NoSuchElementException(); + } + this.alreadyReturned = true; + return this.certificate; + } + + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml 2013-06-28 11:33:53.553806599 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml 2013-06-28 11:33:53.385811832 -0400 @@ -52,9 +52,6 @@ - - @@ -78,6 +75,12 @@ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" /> + + + @@ -97,7 +100,7 @@ Description="MD5 message digest from RFC 1321" AlgorithmClass="MessageDigest" RequirementLevel="NOT RECOMMENDED" - SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt" + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" JCEName="MD5"/> + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" + JCEName="SHA1withECDSA"/> + + + + + + @@ -260,7 +284,31 @@ KeyLength="256" RequiredKey="AES" JCEName="AES/CBC/ISO10126Padding"/> - + + + + + + + + JCEName="RSA/ECB/OAEPPadding"/> + + - - - - + @@ -330,32 +378,8 @@ + DESCRIPTION="A simple resolver for requests of XPointer fragments" /> - - - - - - - - - - --- old/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties 2013-06-28 11:33:54.185786930 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties 2013-06-28 11:33:54.017792156 -0400 @@ -5,6 +5,7 @@ algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1} algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm @@ -88,8 +89,13 @@ signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0} signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf. +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler? signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0} @@ -103,6 +109,7 @@ signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen signature.Verification.MissingID = Cannot resolve element with ID {0} signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1} signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten. signature.Verification.SignatureError = Signatur Fehler --- old/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties 2013-06-28 11:33:54.861765887 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties 2013-06-28 11:33:54.697770994 -0400 @@ -1,126 +1,131 @@ -algorithm.alreadyRegistered = URI {0} already assigned to class {1} -algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH -algorithm.ClassDoesNotExist = Class {0} does not exist -algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} -algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. -algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. -algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. -algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms -algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} -algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm -algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} -algorithms.operationOnlyVerification = A public key can only used for verification of a signature. -algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. -attributeValueIllegal = The attribute {0} has value {1} but must be {2} -c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} -c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} -c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} -c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" -c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} -c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} -c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation -c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) -certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} -certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString -certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier -defaultNamespaceCannotBeSetHere = Default namespace cannot be set here -ElementProxy.nullElement = Cannot create an ElementProxy from a null argument -empty = {0} -encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} -encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams -encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt -encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap -encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit -encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. -encryption.RSAOAEP.dataHashWrong = data hash wrong -encryption.RSAOAEP.dataStartWrong = data wrong start {0} -encryption.RSAOAEP.dataTooShort = data too short -encryption.RSAPKCS15.blockTruncated = block truncated -encryption.RSAPKCS15.noDataInBlock = no data in block -encryption.RSAPKCS15.unknownBlockType = unknown block type -encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers -endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. -errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. -errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. -errorMessages.IOException = Other file I/O and similar exceptions. -errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. -errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. -errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} -errorMessages.NotYetImplementedException = Functionality not yet there. -errorMessages.XMLSignatureException = Verification failed for some other reason. -decoding.divisible.four = It should be divisible by four -decoding.general = Error while decoding -FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. -FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} -FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} -FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} -generic.dontHaveConstructionElement = I do not have a construction Element -generic.EmptyMessage = {0} -generic.NotYetImplemented = {0} Not YET implemented ;-(( -java.security.InvalidKeyException = Invalid key -java.security.NoSuchProviderException = Unknown or unsupported provider -java.security.UnknownKeyType = Unknown or unsupported key type {0} -KeyInfo.needKeyResolver = More than one keyResovler have to be registered -KeyInfo.nokey = Cannot get key from {0} -KeyInfo.noKey = Cannot get the public key -KeyInfo.wrongNumberOfObject = Need {0} keyObjects -KeyInfo.wrongUse = This object was made for getting {0} -keyResolver.alreadyRegistered = {1} class has already been registered for {0} -KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} -KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} -KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} -KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} -KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} -KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} -KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} -KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} -KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} -KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} -KeyStore.alreadyRegistered = {0} Class has already been registered for {1} -KeyStore.register = {1} type class register error in class {0} -KeyStore.registerStore.register = Registeration error for type {0} -KeyValue.IllegalArgument = Cannot create a {0} from {1} -namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} -notYetInitialized = The module {0} is not yet initialized -prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} -signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} -signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature -signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first -signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled -signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled -signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set -signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform -signature.Transform.NotYetImplemented = Transform {0} not yet implemented -signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? -signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} -signature.Transform.node = Current Node: {0} -signature.Transform.nodeAndType = Current Node: {0}, type: {1} -signature.Util.BignumNonPositive = bigInteger.signum() must be positive -signature.Util.NonTextNode = Not a text node -signature.Util.TooManyChilds = Too many childs of Type {0} in {1} -signature.Verification.certificateError = Certificate error -signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References -signature.Verification.internalError = Internal error -signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} -signature.Verification.keyStore = KeyStore error -signature.Verification.MissingID = Cannot resolve element with ID {0} -signature.Verification.MissingResources = Cannot resolve external resource {0} -signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected -signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} -signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput -signature.Verification.SignatureError = Signature error -signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} -signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it -signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference -transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. -transform.init.NotInitialized = -transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization -utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 -Base64Decoding = Error while decoding -utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} -xml.WrongContent = Cannot find {0} in {1} -xml.WrongElement = Cannot create a {0} from a {1} element -xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node -xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} +algorithm.alreadyRegistered = URI {0} already assigned to class {1} +algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH +algorithm.ClassDoesNotExist = Class {0} does not exist +algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} +algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. +algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. +algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} +algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms +algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} +algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm +algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} +algorithms.operationOnlyVerification = A public key can only used for verification of a signature. +algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. +attributeValueIllegal = The attribute {0} has value {1} but must be {2} +c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} +c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} +c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} +c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" +c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} +c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} +c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation +c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) +certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} +certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString +certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier +defaultNamespaceCannotBeSetHere = Default namespace cannot be set here +ElementProxy.nullElement = Cannot create an ElementProxy from a null argument +empty = {0} +encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} +encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams +encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt +encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap +encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit +encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. +encryption.RSAOAEP.dataHashWrong = data hash wrong +encryption.RSAOAEP.dataStartWrong = data wrong start {0} +encryption.RSAOAEP.dataTooShort = data too short +encryption.RSAPKCS15.blockTruncated = block truncated +encryption.RSAPKCS15.noDataInBlock = no data in block +encryption.RSAPKCS15.unknownBlockType = unknown block type +encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers +endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. +errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. +errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. +errorMessages.IOException = Other file I/O and similar exceptions. +errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. +errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. +errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} +errorMessages.NotYetImplementedException = Functionality not yet there. +errorMessages.XMLSignatureException = Verification failed for some other reason. +decoding.divisible.four = It should be divisible by four +decoding.general = Error while decoding +FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. +FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} +FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} +FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} +generic.dontHaveConstructionElement = I do not have a construction Element +generic.EmptyMessage = {0} +generic.NotYetImplemented = {0} Not YET implemented ;-(( +java.security.InvalidKeyException = Invalid key +java.security.NoSuchProviderException = Unknown or unsupported provider +java.security.UnknownKeyType = Unknown or unsupported key type {0} +KeyInfo.needKeyResolver = More than one keyResovler have to be registered +KeyInfo.nokey = Cannot get key from {0} +KeyInfo.noKey = Cannot get the public key +KeyInfo.wrongNumberOfObject = Need {0} keyObjects +KeyInfo.wrongUse = This object was made for getting {0} +keyResolver.alreadyRegistered = {1} class has already been registered for {0} +KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} +KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} +KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} +KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} +KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} +KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} +KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} +KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} +KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} +KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} +KeyStore.alreadyRegistered = {0} Class has already been registered for {1} +KeyStore.register = {1} type class register error in class {0} +KeyStore.registerStore.register = Registeration error for type {0} +KeyValue.IllegalArgument = Cannot create a {0} from {1} +namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} +notYetInitialized = The module {0} is not yet initialized +prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} +signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} +signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature +signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled +signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation +signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled +signature.Transform.NotYetImplemented = Transform {0} not yet implemented +signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? +signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} +signature.Transform.node = Current Node: {0} +signature.Transform.nodeAndType = Current Node: {0}, type: {1} +signature.Util.BignumNonPositive = bigInteger.signum() must be positive +signature.Util.NonTextNode = Not a text node +signature.Util.TooManyChilds = Too many childs of Type {0} in {1} +signature.Verification.certificateError = Certificate error +signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References +signature.Verification.internalError = Internal error +signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} +signature.Verification.keyStore = KeyStore error +signature.Verification.MissingID = Cannot resolve element with ID {0} +signature.Verification.MissingResources = Cannot resolve external resource {0} +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected +signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} +signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput +signature.Verification.SignatureError = Signature error +signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} +signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it +signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference +transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. +transform.init.NotInitialized = +transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization +transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element +utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 +Base64Decoding = Error while decoding +utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} +xml.WrongContent = Cannot find {0} in {1} +xml.WrongElement = Cannot create a {0} from a {1} element +xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node +xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java 2013-06-28 11:33:55.529745096 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java 2013-06-28 11:33:55.357750447 -0400 @@ -2,85 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - /** - * Raised when the computed hash value doesn't match the given DigestValue. Additional human readable info is passed to the constructor -- this being the benefit of raising an exception or returning a value. + * Raised when the computed hash value doesn't match the given DigestValue. + * Additional human readable info is passed to the constructor -- this being the benefit + * of raising an exception or returning a value. * * @author Christian Geuer-Pollmann */ public class InvalidDigestValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor InvalidDigestValueException - * - */ - public InvalidDigestValueException() { - super(); - } - - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - */ - public InvalidDigestValueException(String _msgID) { - super(_msgID); - } - - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidDigestValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor InvalidDigestValueException + * + */ + public InvalidDigestValueException() { + super(); + } + + /** + * Constructor InvalidDigestValueException + * + * @param msgID + */ + public InvalidDigestValueException(String msgID) { + super(msgID); + } + + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + */ + public InvalidDigestValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param originalException + */ + public InvalidDigestValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidDigestValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java 2013-06-28 11:33:56.169725171 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java 2013-06-28 11:33:56.005730277 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - /** * Raised if testing the signature value over DigestValue fails because of invalid signature. * @@ -30,58 +30,56 @@ */ public class InvalidSignatureValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor InvalidSignatureValueException - * - */ - public InvalidSignatureValueException() { - super(); - } - - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - */ - public InvalidSignatureValueException(String _msgID) { - super(_msgID); - } - - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor InvalidSignatureValueException + * + */ + public InvalidSignatureValueException() { + super(); + } + + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + */ + public InvalidSignatureValueException(String msgID) { + super(msgID); + } + + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + */ + public InvalidSignatureValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java 2013-06-28 11:33:56.829704630 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java 2013-06-28 11:33:56.669709612 -0400 @@ -2,33 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.Map; +import java.util.Set; import javax.xml.parsers.ParserConfigurationException; @@ -38,7 +38,6 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; @@ -50,523 +49,561 @@ import org.w3c.dom.Node; import org.xml.sax.SAXException; - - /** * Handles <ds:Manifest> elements. *

      This element holds the Reference elements

      - * @author $author: $ */ public class Manifest extends SignatureElementProxy { + + /** + * The maximum number of references per Manifest, if secure validation is enabled. + */ + public static final int MAXIMUM_REFERENCE_COUNT = 30; - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(Manifest.class.getName()); - /** Field _references */ - List _references; - Element[] _referencesEl; - - /** Field verificationResults[] */ - private boolean verificationResults[] = null; - - /** Field _resolverProperties */ - Map _resolverProperties = null; - - /** Field _perManifestResolvers */ - List _perManifestResolvers = null; - - /** - * Consturts {@link Manifest} - * - * @param doc the {@link Document} in which XMLsignature is placed - */ - public Manifest(Document doc) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - - this._references = new ArrayList(); - } - - /** - * Constructor Manifest - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public Manifest(Element element, String BaseURI) - throws XMLSecurityException { - - super(element, BaseURI); - - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - - // check out Reference children - this._referencesEl = XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(), - Constants._TAG_REFERENCE); - int le = this._referencesEl.length; - { - if (le == 0) { - + /** Field references */ + private List references; + private Element[] referencesEl; + + /** Field verificationResults[] */ + private boolean verificationResults[] = null; + + /** Field resolverProperties */ + private Map resolverProperties = null; + + /** Field perManifestResolvers */ + private List perManifestResolvers = null; + + private boolean secureValidation; + + /** + * Constructs {@link Manifest} + * + * @param doc the {@link Document} in which XMLsignature is placed + */ + public Manifest(Document doc) { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + + this.references = new ArrayList(); + } + + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public Manifest(Element element, String baseURI) throws XMLSecurityException { + this(element, baseURI, false); + + } + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @param secureValidation + * @throws XMLSecurityException + */ + public Manifest( + Element element, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + super(element, baseURI); + + Attr attr = element.getAttributeNodeNS(null, "Id"); + if (attr != null) { + element.setIdAttributeNode(attr, true); + } + this.secureValidation = secureValidation; + + // check out Reference children + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + int le = this.referencesEl.length; + if (le == 0) { // At least one Reference must be present. Bad. - Object exArgs[] = { Constants._TAG_REFERENCE, - Constants._TAG_MANIFEST }; + Object exArgs[] = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST }; throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, I18n.translate("xml.WrongContent", exArgs)); - } - } - - // create Vector - this._references = new ArrayList(le); - - for (int i = 0; i < le; i++) { - Element refElem = this._referencesEl[i]; - Attr refAttr = refElem.getAttributeNodeNS(null, "Id"); - if (refAttr != null) { - refElem.setIdAttributeNode(refAttr, true); - } - this._references.add(null); - } - } - - /** - * This addDocument method is used to add a new resource to the - * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built - * from the supplied values. - * - * @param BaseURI the URI of the resource where the XML instance was stored - * @param referenceURI URI attribute in Reference for specifing where data is - * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered list of transformations to be performed. - * @param digestURI The digest algorthim URI to be used. - * @param ReferenceId - * @param ReferenceType - * @throws XMLSignatureException - */ - public void addDocument( - String BaseURI, String referenceURI, Transforms transforms, String digestURI, String ReferenceId, String ReferenceType) - throws XMLSignatureException { - - // the this._doc is handed implicitly by the this.getOwnerDocument() - Reference ref = new Reference(this._doc, BaseURI, referenceURI, this, - transforms, digestURI); - - if (ReferenceId != null) { - ref.setId(ReferenceId); - } - - if (ReferenceType != null) { - ref.setType(ReferenceType); - } - - // add Reference object to our cache vector - this._references.add(ref); - - // add the Element of the Reference object to the Manifest/SignedInfo - this._constructionElement.appendChild(ref.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * The calculation of the DigestValues in the References must be after the - * References are already added to the document and during the signing - * process. This ensures that all neccesary data is in place. - * - * @throws ReferenceNotInitializedException - * @throws XMLSignatureException - */ - public void generateDigestValues() - throws XMLSignatureException, ReferenceNotInitializedException { - - for (int i = 0; i < this.getLength(); i++) { - + } + + if (secureValidation && le > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { le, MAXIMUM_REFERENCE_COUNT }; + + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } + + // create List + this.references = new ArrayList(le); + + for (int i = 0; i < le; i++) { + Element refElem = referencesEl[i]; + Attr refAttr = refElem.getAttributeNodeNS(null, "Id"); + if (refAttr != null) { + refElem.setIdAttributeNode(refAttr, true); + } + this.references.add(null); + } + } + + /** + * This addDocument method is used to add a new resource to the + * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built + * from the supplied values. + * + * @param baseURI the URI of the resource where the XML instance was stored + * @param referenceURI URI attribute in Reference for specifying + * where data is + * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered + * list of transformations to be performed. + * @param digestURI The digest algorithm URI to be used. + * @param referenceId + * @param referenceType + * @throws XMLSignatureException + */ + public void addDocument( + String baseURI, String referenceURI, Transforms transforms, + String digestURI, String referenceId, String referenceType + ) throws XMLSignatureException { + // the this.doc is handed implicitly by the this.getOwnerDocument() + Reference ref = + new Reference(this.doc, baseURI, referenceURI, this, transforms, digestURI); + + if (referenceId != null) { + ref.setId(referenceId); + } + + if (referenceType != null) { + ref.setType(referenceType); + } + + // add Reference object to our cache vector + this.references.add(ref); + + // add the Element of the Reference object to the Manifest/SignedInfo + this.constructionElement.appendChild(ref.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * The calculation of the DigestValues in the References must be after the + * References are already added to the document and during the signing + * process. This ensures that all necessary data is in place. + * + * @throws ReferenceNotInitializedException + * @throws XMLSignatureException + */ + public void generateDigestValues() + throws XMLSignatureException, ReferenceNotInitializedException { + for (int i = 0; i < this.getLength(); i++) { // update the cached Reference object, the Element content is automatically updated - Reference currentRef = this._references.get(i); - + Reference currentRef = this.references.get(i); currentRef.generateDigestValue(); - } - } + } + } - /** - * Return the nonnegative number of added references. - * - * @return the number of references - */ - public int getLength() { - return this._references.size(); - } - - /** - * Return the ith reference. Valid i - * values are 0 to {link@ getSize}-1. - * - * @param i Index of the requested {@link Reference} - * @return the ith reference - * @throws XMLSecurityException - */ - public Reference item(int i) throws XMLSecurityException { - - if (this._references.get(i) == null) { - - // not yet constructed, so _we_ have to - Reference ref = new Reference(_referencesEl[i], this._baseURI, this); - - this._references.set(i, ref); - } - - return this._references.get(i); - - } - - /** - * Sets the Id attribute - * - * @param Id the Id attribute in ds:Manifest - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute in ds:Manifest - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

      This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. The results of the individual reference - * validations are available by using the {@link #getVerificationResult(int)} method - * - * @return true if all References verify, false if one or more do not verify. - * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput} - * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify - * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify() - * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException - * @throws XMLSecurityException - */ - public boolean verifyReferences() - throws MissingResourceFailureException, XMLSecurityException { - return this.verifyReferences(false); - } - - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

      This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. The results of the individual reference - * validations are available by using the {@link #getVerificationResult(int)} method - * - * @param followManifests - * @return true if all References verify, false if one or more do not verify. - * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput} - * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify - * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) - * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException - * @throws XMLSecurityException - */ - public boolean verifyReferences(boolean followManifests) - throws MissingResourceFailureException, XMLSecurityException { - if (_referencesEl==null) { - this._referencesEl = - XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(), - Constants._TAG_REFERENCE); - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "verify " +_referencesEl.length + " References"); - log.log(java.util.logging.Level.FINE, "I am " + (followManifests - ? "" - : "not") + " requested to follow nested Manifests"); - } - boolean verify = true; - - if (_referencesEl.length==0) { - throw new XMLSecurityException("empty"); - } - - this.verificationResults = - new boolean[_referencesEl.length]; - - for (int i = - 0; i < this._referencesEl.length; i++) { - Reference currentRef = - new Reference(_referencesEl[i], this._baseURI, this); - - this._references.set(i, currentRef); - - /* if only one item does not verify, the whole verification fails */ - try { - boolean currentRefVerified = currentRef.verify(); + /** + * Return the nonnegative number of added references. + * + * @return the number of references + */ + public int getLength() { + return this.references.size(); + } + + /** + * Return the ith reference. Valid i + * values are 0 to {link@ getSize}-1. + * + * @param i Index of the requested {@link Reference} + * @return the ith reference + * @throws XMLSecurityException + */ + public Reference item(int i) throws XMLSecurityException { + if (this.references.get(i) == null) { + // not yet constructed, so _we_ have to + Reference ref = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); + + this.references.set(i, ref); + } + + return this.references.get(i); + } + + /** + * Sets the Id attribute + * + * @param Id the Id attribute in ds:Manifest + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute in ds:Manifest + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

      This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify() + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences() + throws MissingResourceFailureException, XMLSecurityException { + return this.verifyReferences(false); + } + + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

      This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @param followManifests + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences(boolean followManifests) + throws MissingResourceFailureException, XMLSecurityException { + if (referencesEl == null) { + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "verify " + referencesEl.length + " References"); + log.log(java.util.logging.Level.FINE, "I am " + (followManifests + ? "" : "not") + " requested to follow nested Manifests"); + } + if (referencesEl.length == 0) { + throw new XMLSecurityException("empty"); + } + if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT }; + + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } + + this.verificationResults = new boolean[referencesEl.length]; + boolean verify = true; + for (int i = 0; i < this.referencesEl.length; i++) { + Reference currentRef = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); + + this.references.set(i, currentRef); + + // if only one item does not verify, the whole verification fails + try { + boolean currentRefVerified = currentRef.verify(); + + this.setVerificationResult(i, currentRefVerified); + + if (!currentRefVerified) { + verify = false; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType()); + } + + // was verification successful till now and do we want to verify the Manifest? + if (verify && followManifests && currentRef.typeIsReferenceToManifest()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest"); + } + + try { + XMLSignatureInput signedManifestNodes = + currentRef.dereferenceURIandPerformTransforms(null); + Set nl = signedManifestNodes.getNodeSet(); + Manifest referencedManifest = null; + Iterator nlIterator = nl.iterator(); + + findManifest: while (nlIterator.hasNext()) { + Node n = nlIterator.next(); + + if ((n.getNodeType() == Node.ELEMENT_NODE) + && ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS) + && ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST) + ) { + try { + referencedManifest = + new Manifest( + (Element)n, signedManifestNodes.getSourceURI(), secureValidation + ); + break findManifest; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // Hm, seems not to be a ds:Manifest + } + } + } - this.setVerificationResult(i, currentRefVerified); + if (referencedManifest == null) { + // The Reference stated that it points to a ds:Manifest + // but we did not find a ds:Manifest in the signed area + throw new MissingResourceFailureException("empty", currentRef); + } - if (!currentRefVerified) { - verify = false; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType()); + referencedManifest.perManifestResolvers = this.perManifestResolvers; + referencedManifest.resolverProperties = this.resolverProperties; - // was verification successful till now and do we want to verify the Manifest? - if (verify && followManifests - && currentRef.typeIsReferenceToManifest()) { - log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest"); - - try { - XMLSignatureInput signedManifestNodes = - currentRef.dereferenceURIandPerformTransforms(null); - Set nl = signedManifestNodes.getNodeSet(); - Manifest referencedManifest = null; - Iterator nlIterator = nl.iterator(); - - findManifest: while (nlIterator.hasNext()) { - Node n = nlIterator.next(); - - if ((n.getNodeType() == Node.ELEMENT_NODE) && ((Element) n) - .getNamespaceURI() - .equals(Constants.SignatureSpecNS) && ((Element) n) - .getLocalName().equals(Constants._TAG_MANIFEST)) { - try { - referencedManifest = - new Manifest((Element) n, - signedManifestNodes.getSourceURI()); + boolean referencedManifestValid = + referencedManifest.verifyReferences(followManifests); - break findManifest; - } catch (XMLSecurityException ex) { + if (!referencedManifestValid) { + verify = false; - // Hm, seems not to be a ds:Manifest + log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)"); + } else { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)"); + } } - } - } + } catch (IOException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } catch (SAXException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } + } + } catch (ReferenceNotInitializedException ex) { + Object exArgs[] = { currentRef.getURI() }; + + throw new MissingResourceFailureException( + "signature.Verification.Reference.NoInput", exArgs, ex, currentRef + ); + } + } - if (referencedManifest == null) { + return verify; + } - // The Reference stated that it points to a ds:Manifest - // but we did not find a ds:Manifest in the signed area - throw new MissingResourceFailureException("empty", - currentRef); - } - - referencedManifest._perManifestResolvers = - this._perManifestResolvers; - referencedManifest._resolverProperties = - this._resolverProperties; - - boolean referencedManifestValid = - referencedManifest.verifyReferences(followManifests); - - if (!referencedManifestValid) { - verify = false; - - log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)"); - } else { - log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)"); - } - } catch (IOException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } catch (SAXException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } + /** + * Method setVerificationResult + * + * @param index + * @param verify + */ + private void setVerificationResult(int index, boolean verify) { + if (this.verificationResults == null) { + this.verificationResults = new boolean[this.getLength()]; + } + + this.verificationResults[index] = verify; + } + + /** + * After verifying a {@link Manifest} or a {@link SignedInfo} using the + * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods, + * the individual results can be retrieved with this method. + * + * @param index an index of into a {@link Manifest} or a {@link SignedInfo} + * @return the results of reference validation at the specified index + * @throws XMLSecurityException + */ + public boolean getVerificationResult(int index) throws XMLSecurityException { + if ((index < 0) || (index > this.getLength() - 1)) { + Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) }; + Exception e = + new IndexOutOfBoundsException( + I18n.translate("signature.Verification.IndexOutOfBounds", exArgs) + ); + + throw new XMLSecurityException("generic.EmptyMessage", e); + } + + if (this.verificationResults == null) { + try { + this.verifyReferences(); + } catch (Exception ex) { + throw new XMLSecurityException("generic.EmptyMessage", ex); } - } catch (ReferenceNotInitializedException ex) { - Object exArgs[] = { currentRef.getURI() }; + } + + return this.verificationResults[index]; + } - throw new MissingResourceFailureException( - "signature.Verification.Reference.NoInput", exArgs, ex, - currentRef); - } - } - - return verify; - } - - /** - * Method setVerificationResult - * - * @param index - * @param verify - */ - private void setVerificationResult(int index, boolean verify) - { - - if (this.verificationResults == null) { - this.verificationResults = new boolean[this.getLength()]; - } - - this.verificationResults[index] = verify; - } - - /** - * After verifying a {@link Manifest} or a {@link SignedInfo} using the - * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods, - * the individual results can be retrieved with this method. - * - * @param index an index of into a {@link Manifest} or a {@link SignedInfo} - * @return the results of reference validation at the specified index - * @throws XMLSecurityException - */ - public boolean getVerificationResult(int index) throws XMLSecurityException { - - if ((index < 0) || (index > this.getLength() - 1)) { - Object exArgs[] = { Integer.toString(index), - Integer.toString(this.getLength()) }; - Exception e = - new IndexOutOfBoundsException(I18n - .translate("signature.Verification.IndexOutOfBounds", exArgs)); - - throw new XMLSecurityException("generic.EmptyMessage", e); - } - - if (this.verificationResults == null) { - try { - this.verifyReferences(); - } catch (Exception ex) { - throw new XMLSecurityException("generic.EmptyMessage", ex); - } - } - - return this.verificationResults[index]; - } - - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolver resolver) { - - if (resolver == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(resolver); - - } - - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolverSpi the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolverSpi resolverSpi) { - - if (resolverSpi == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(new ResourceResolver(resolverSpi)); - - } - - /** - * Used to pass parameters like proxy servers etc to the ResourceResolver - * implementation. - * - * @param key the key - * @param value the value - */ - public void setResolverProperty(String key, String value) { - if (_resolverProperties==null) { - _resolverProperties=new HashMap(10); - } - this._resolverProperties.put(key, value); - } - - /** - * Returns the value at specified key - * - * @param key the key - * @return the value - */ - public String getResolverProperty(String key) { - return this._resolverProperties.get(key); - } - - /** - * Method getSignedContentItem - * - * @param i - * @return The signed content of the i reference. - * - * @throws XMLSignatureException - */ - public byte[] getSignedContentItem(int i) throws XMLSignatureException { - - try { - return this.getReferencedContentAfterTransformsItem(i).getBytes(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } catch (CanonicalizationException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException("empty", ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method getReferencedContentPriorTransformsItem - * - * @param i - * @return The contents before transformation of the reference i. - * @throws XMLSecurityException - */ - public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i) - throws XMLSecurityException { - return this.item(i).getContentsBeforeTransformation(); - } - - /** - * Method getReferencedContentAfterTransformsItem - * - * @param i - * @return The contents after transformation of the reference i. - * @throws XMLSecurityException - */ - public XMLSignatureInput getReferencedContentAfterTransformsItem(int i) - throws XMLSecurityException { - return this.item(i).getContentsAfterTransformation(); - } - - /** - * Method getSignedContentLength - * - * @return The nu,ber of references contained in this reference. - */ - public int getSignedContentLength() { - return this.getLength(); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return Constants._TAG_MANIFEST; - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference element + * + * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of + * {@link ResourceResolverSpi} for retrieving resource. + */ + public void addResourceResolver(ResourceResolver resolver) { + if (resolver == null) { + return; + } + if (perManifestResolvers == null) { + perManifestResolvers = new ArrayList(); + } + this.perManifestResolvers.add(resolver); + } + + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in 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() { + return perManifestResolvers; + } + + /** + * Get the resolver property map + * @return the resolver property map + */ + public Map getResolverProperties() { + return resolverProperties; + } + + /** + * Used to pass parameters like proxy servers etc to the ResourceResolver + * implementation. + * + * @param key the key + * @param value the value + */ + public void setResolverProperty(String key, String value) { + if (resolverProperties == null) { + resolverProperties = new HashMap(10); + } + this.resolverProperties.put(key, value); + } + + /** + * Returns the value at specified key + * + * @param key the key + * @return the value + */ + public String getResolverProperty(String key) { + return this.resolverProperties.get(key); + } + + /** + * Method getSignedContentItem + * + * @param i + * @return The signed content of the i reference. + * + * @throws XMLSignatureException + */ + public byte[] getSignedContentItem(int i) throws XMLSignatureException { + try { + return this.getReferencedContentAfterTransformsItem(i).getBytes(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } catch (CanonicalizationException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new XMLSignatureException("empty", ex); + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Method getReferencedContentPriorTransformsItem + * + * @param i + * @return The contents before transformation of the reference i. + * @throws XMLSecurityException + */ + public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i) + throws XMLSecurityException { + return this.item(i).getContentsBeforeTransformation(); + } + + /** + * Method getReferencedContentAfterTransformsItem + * + * @param i + * @return The contents after transformation of the reference i. + * @throws XMLSecurityException + */ + public XMLSignatureInput getReferencedContentAfterTransformsItem(int i) + throws XMLSecurityException { + return this.item(i).getContentsAfterTransformation(); + } + + /** + * Method getSignedContentLength + * + * @return The number of references contained in this reference. + */ + public int getSignedContentLength() { + return this.getLength(); + } + + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return Constants._TAG_MANIFEST; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java 2013-06-28 11:33:57.561681846 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java 2013-06-28 11:33:57.389687199 -0400 @@ -2,28 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - - - /** * Thrown by {@link com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()} when * testing the signature fails because of uninitialized @@ -34,97 +32,93 @@ */ public class MissingResourceFailureException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** Field uninitializedReference */ - Reference uninitializedReference = null; - - /** - * MissingKeyResourceFailureException constructor. - * @param _msgID - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Reference reference) { - - super(_msgID); - - this.uninitializedReference = reference; - } - - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param exArgs - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Object exArgs[], - Reference reference) { - - super(_msgID, exArgs); - - this.uninitializedReference = reference; - } - - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, - Exception _originalException, - Reference reference) { - - super(_msgID, _originalException); - - this.uninitializedReference = reference; - } - - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Object exArgs[], - Exception _originalException, - Reference reference) { - - super(_msgID, exArgs, _originalException); - - this.uninitializedReference = reference; - } - - /** - * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} - * - * @param reference the Reference object - * @see #getReference - */ - public void setReference(Reference reference) { - this.uninitializedReference = reference; - } - - /** - * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} - * - * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput} - * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification. - * - * @return the Reference object - * @see #setReference - */ - public Reference getReference() { - return this.uninitializedReference; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** Field uninitializedReference */ + private Reference uninitializedReference = null; + + /** + * MissingKeyResourceFailureException constructor. + * @param msgID + * @param reference + * @see #getReference + */ + public MissingResourceFailureException(String msgID, Reference reference) { + super(msgID); + + this.uninitializedReference = reference; + } + + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param exArgs + * @param reference + * @see #getReference + */ + public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) { + super(msgID, exArgs); + + this.uninitializedReference = reference; + } + + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param originalException + * @param reference + * @see #getReference + */ + public MissingResourceFailureException( + String msgID, Exception originalException, Reference reference + ) { + super(msgID, originalException); + + this.uninitializedReference = reference; + } + + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param exArgs + * @param originalException + * @param reference + * @see #getReference + */ + public MissingResourceFailureException( + String msgID, Object exArgs[], Exception originalException, Reference reference + ) { + super(msgID, exArgs, originalException); + + this.uninitializedReference = reference; + } + + /** + * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} + * + * @param reference the Reference object + * @see #getReference + */ + public void setReference(Reference reference) { + this.uninitializedReference = reference; + } + + /** + * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} + * + * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput} + * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification. + * + * @return the Reference object + * @see #setReference + */ + public Reference getReference() { + return this.uninitializedReference; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java 2013-06-28 11:33:58.249660432 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java 2013-06-28 11:33:58.069666033 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; @@ -24,30 +26,30 @@ /** * An interface to tell to the c14n if a node is included or not in the output - * @author raul - * */ public interface NodeFilter { - /** - * Tells if a node must be outputed in c14n. - * @param n - * @return 1 if the node should be outputed. - * 0 if node must not be outputed, - * -1 if the node and all it's child must not be output. - * - */ - public int isNodeInclude(Node n); - /** - * Tells if a node must be outputed in a c14n. - * The caller must assured that this method is always call - * in document order. The implementations can use this - * restriction to optimize the transformation. - * @param n - * @param level the relative level in the tree - * @return 1 if the node should be outputed. - * 0 if node must not be outputed, - * -1 if the node and all it's child must not be output. - */ - public int isNodeIncludeDO(Node n, int level); + + /** + * Tells if a node must be output in c14n. + * @param n + * @return 1 if the node should be output. + * 0 if node must not be output, + * -1 if the node and all it's child must not be output. + * + */ + int isNodeInclude(Node n); + + /** + * Tells if a node must be output in a c14n. + * The caller must assured that this method is always call + * in document order. The implementations can use this + * restriction to optimize the transformation. + * @param n + * @param level the relative level in the tree + * @return 1 if the node should be output. + * 0 if node must not be output, + * -1 if the node and all it's child must not be output. + */ + int isNodeIncludeDO(Node n, int level); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java 2013-06-28 11:33:59.081634530 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java 2013-06-28 11:33:58.897640259 -0400 @@ -2,27 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -38,111 +39,99 @@ */ public class ObjectContainer extends SignatureElementProxy { - /** - * Constructs {@link ObjectContainer} - * - * @param doc the {@link Document} in which Object element is placed - */ - public ObjectContainer(Document doc) { - - super(doc); - } - - /** - * Constructs {@link ObjectContainer} from {@link Element} - * - * @param element is Object element - * @param BaseURI the URI of the resource where the XML instance was stored - * @throws XMLSecurityException - */ - public ObjectContainer(Element element, String BaseURI) - throws XMLSecurityException { - - super(element, BaseURI); - } - - /** - * Sets the Id attribute - * - * @param Id Id attribute - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Sets the MimeType attribute - * - * @param MimeType the MimeType attribute - */ - public void setMimeType(String MimeType) { - - if ( (MimeType != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, - MimeType); - } - } - - /** - * Returns the MimeType attribute - * - * @return the MimeType attribute - */ - public String getMimeType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); - } - - /** - * Sets the Encoding attribute - * - * @param Encoding the Encoding attribute - */ - public void setEncoding(String Encoding) { - - if ((Encoding != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, - Encoding); - } - } - - /** - * Returns the Encoding attribute - * - * @return the Encoding attribute - */ - public String getEncoding() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); - } - - /** - * Adds child Node - * - * @param node child Node - * @return the new node in the tree. - */ - public Node appendChild(Node node) { - - Node result = null; - - result = this._constructionElement.appendChild(node); - - return result; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_OBJECT; - } + /** + * Constructs {@link ObjectContainer} + * + * @param doc the {@link Document} in which Object element is placed + */ + public ObjectContainer(Document doc) { + super(doc); + } + + /** + * Constructs {@link ObjectContainer} from {@link Element} + * + * @param element is Object element + * @param baseURI the URI of the resource where the XML instance was stored + * @throws XMLSecurityException + */ + public ObjectContainer(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } + + /** + * Sets the Id attribute + * + * @param Id Id attribute + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** + * Sets the MimeType attribute + * + * @param MimeType the MimeType attribute + */ + public void setMimeType(String MimeType) { + if (MimeType != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType); + } + } + + /** + * Returns the MimeType attribute + * + * @return the MimeType attribute + */ + public String getMimeType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); + } + + /** + * Sets the Encoding attribute + * + * @param Encoding the Encoding attribute + */ + public void setEncoding(String Encoding) { + if (Encoding != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding); + } + } + + /** + * Returns the Encoding attribute + * + * @return the Encoding attribute + */ + public String getEncoding() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); + } + + /** + * Adds child Node + * + * @param node child Node + * @return the new node in the tree. + */ + public Node appendChild(Node node) { + return this.constructionElement.appendChild(node); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_OBJECT; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java 2013-06-28 11:33:59.689615609 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java 2013-06-28 11:33:59.517620964 -0400 @@ -2,31 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashSet; +import java.util.Iterator; import java.util.Set; import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm; @@ -34,6 +35,10 @@ import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceOctetStreamData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceSubTreeData; import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException; import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; @@ -42,7 +47,6 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; 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; @@ -54,7 +58,6 @@ import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Handles <ds:Reference> elements. * @@ -64,17 +67,17 @@ * *

      Create a new reference

      *
      - * Document _doc;
      + * Document doc;
        * MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
        * Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
        *                               "http://localhost/1.gif",
        *                               (Transforms) null, sha1);
      - * Element refElem = ref.toElement(_doc);
      + * Element refElem = ref.toElement(doc);
        * 
      * *

      Verify a reference

      *
      - * Element refElem = _doc.getElement("Reference"); // PSEUDO
      + * Element refElem = doc.getElement("Reference"); // PSEUDO
        * Reference ref = new Reference(refElem);
        * String url = ref.getURI();
        * ref.setData(new XMLSignatureInput(new FileInputStream(url)));
      @@ -102,690 +105,698 @@
        * @see Manifest
        */
       public class Reference extends SignatureElementProxy {
      +    
      +    /** Field OBJECT_URI */
      +    public static final String OBJECT_URI = Constants.SignatureSpecNS + Constants._TAG_OBJECT;
      +
      +    /** Field MANIFEST_URI */
      +    public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
      +    
      +    /**
      +     * The maximum number of transforms per reference, if secure validation is enabled.
      +     */
      +    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
      +    
      +    private boolean secureValidation;
      +
      +    /**
      +     * Look up useC14N11 system property. If true, an explicit C14N11 transform
      +     * will be added if necessary when generating the signature. See section
      +     * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
      +     */
      +    private static boolean useC14N11 = (
      +        AccessController.doPrivileged(new PrivilegedAction() {
      +            public Boolean run() {
      +                return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
      +            }
      +        })).booleanValue();
       
      -   /**
      -    * Look up useC14N11 system property. If true, an explicit C14N11 transform
      -    * will be added if necessary when generating the signature. See section
      -    * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
      -    */
      -   private static boolean useC14N11 =
      -      AccessController.doPrivileged(new PrivilegedAction() {
      -         public Boolean run() {
      -            return Boolean.getBoolean
      -               ("com.sun.org.apache.xml.internal.security.useC14N11");
      -         }
      -      });
      -
      -/*
      -   static {
      -      try {
      -         useC14N11 = Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11");
      -      } catch (Exception e) {
      -         // ignore exceptions
      -      }
      -   }
      -*/
      -
      -   /** Field CacheSignedNodes */
      -   public final static boolean CacheSignedNodes = false;
      -
      -   /** {@link java.util.logging} logging facility */
      -    static java.util.logging.Logger log =
      +    /** {@link org.apache.commons.logging} logging facility */
      +    private static final java.util.logging.Logger log = 
               java.util.logging.Logger.getLogger(Reference.class.getName());
       
      -   /** Field OBJECT_URI */
      -   public static final String OBJECT_URI = Constants.SignatureSpecNS
      -                                           + Constants._TAG_OBJECT;
      -
      -   /** Field MANIFEST_URI */
      -   public static final String MANIFEST_URI = Constants.SignatureSpecNS
      -                                             + Constants._TAG_MANIFEST;
      -   //J-
      -   Manifest _manifest = null;
      -   XMLSignatureInput _transformsOutput;
      -   //J+
      -
      -private Transforms transforms;
      -
      -private Element digestMethodElem;
      -
      -private Element digestValueElement;
      -
      -   /**
      -    * Constructor Reference
      -    *
      -    * @param doc the {@link Document} in which XMLsignature is placed
      -    * @param BaseURI the URI of the resource where the XML instance will be stored
      -    * @param ReferenceURI URI indicate where is data which will digested
      -    * @param manifest
      -    * @param transforms {@link Transforms} applied to data
      -    * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is applied to the data
      -    * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
      -    * @throws XMLSignatureException
      -    */
      -   protected Reference(Document doc, String BaseURI, String ReferenceURI, Manifest manifest, Transforms transforms, String messageDigestAlgorithm)
      -           throws XMLSignatureException {
      -
      -      super(doc);
      -
      -      XMLUtils.addReturnToElement(this._constructionElement);
      -
      -      this._baseURI = BaseURI;
      -      this._manifest = manifest;
      -
      -      this.setURI(ReferenceURI);
      -
      -      // important: The ds:Reference must be added to the associated ds:Manifest
      -      //            or ds:SignedInfo _before_ the this.resolverResult() is called.
      -      // this._manifest.appendChild(this._constructionElement);
      -      // this._manifest.appendChild(this._doc.createTextNode("\n"));
      -
      -      if (transforms != null) {
      -          this.transforms=transforms;
      -         this._constructionElement.appendChild(transforms.getElement());
      -         XMLUtils.addReturnToElement(this._constructionElement);
      -      }
      -      {
      -         MessageDigestAlgorithm mda =
      -            MessageDigestAlgorithm.getInstance(this._doc,
      -                                               messageDigestAlgorithm);
      -
      -         digestMethodElem=mda.getElement();
      -         this._constructionElement.appendChild(digestMethodElem);
      -         XMLUtils.addReturnToElement(this._constructionElement);
      -      }
      -      {
      -         digestValueElement =
      -            XMLUtils.createElementInSignatureSpace(this._doc,
      -                                                   Constants._TAG_DIGESTVALUE);
      -
      -         this._constructionElement.appendChild(digestValueElement);
      -         XMLUtils.addReturnToElement(this._constructionElement);
      -      }
      -   }
      -
      -
      -   /**
      -    * Build a {@link Reference} from an {@link Element}
      -    *
      -    * @param element Reference element
      -    * @param BaseURI the URI of the resource where the XML instance was stored
      -    * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs. We need this because the Manifest has the individual {@link ResourceResolver}s whcih have been set by the user
      -    * @throws XMLSecurityException
      -    */
      -   protected Reference(Element element, String BaseURI, Manifest manifest)
      -           throws XMLSecurityException {
      -
      -      super(element, BaseURI);
      -      this._baseURI=BaseURI;
      -      Element el=XMLUtils.getNextElement(element.getFirstChild());
      -      if (Constants._TAG_TRANSFORMS.equals(el.getLocalName()) &&
      -                  Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
      -          transforms = new Transforms(el,this._baseURI);
      -          el=XMLUtils.getNextElement(el.getNextSibling());
      -      }
      -      digestMethodElem = el;
      -      digestValueElement =XMLUtils.getNextElement(digestMethodElem.getNextSibling());;
      -      this._manifest = manifest;
      -   }
      -
      -   /**
      -    * Returns {@link MessageDigestAlgorithm}
      -    *
      -    *
      -    * @return {@link MessageDigestAlgorithm}
      -    *
      -    * @throws XMLSignatureException
      -    */
      -   public MessageDigestAlgorithm getMessageDigestAlgorithm()
      -           throws XMLSignatureException {
      -
      -      if (digestMethodElem == null) {
      -         return null;
      -      }
      -
      -      String uri = digestMethodElem.getAttributeNS(null,
      -         Constants._ATT_ALGORITHM);
      -
      -          if (uri == null) {
      -                  return null;
      -          }
      -
      -      return MessageDigestAlgorithm.getInstance(this._doc, uri);
      -   }
      -
      -   /**
      -    * Sets the URI of this Reference element
      -    *
      -    * @param URI the URI of this Reference element
      -    */
      -   public void setURI(String URI) {
      -
      -      if ( URI != null) {
      -         this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
      -                                                  URI);
      -      }
      -   }
      -
      -   /**
      -    * Returns the URI of this Reference element
      -    *
      -    * @return URI the URI of this Reference element
      -    */
      -   public String getURI() {
      -      return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
      -   }
      -
      -   /**
      -    * Sets the Id attribute of this Reference element
      -    *
      -    * @param Id the Id attribute of this Reference element
      -    */
      -   public void setId(String Id) {
      -
      -      if ( Id != null ) {
      -          setLocalIdAttribute(Constants._ATT_ID, Id);
      -      }
      -   }
      -
      -   /**
      -    * Returns the Id attribute of this Reference element
      -    *
      -    * @return Id the Id attribute of this Reference element
      -    */
      -   public String getId() {
      -      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
      -   }
      -
      -   /**
      -    * Sets the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
      -    *
      -    * @param Type the type attribute of the Reference
      -    */
      -   public void setType(String Type) {
      -
      -      if (Type != null) {
      -         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
      -                                                  Type);
      -      }
      -   }
      -
      -   /**
      -    * Return the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
      -    *
      -    * @return the type attribute of the Reference
      -    */
      -   public String getType() {
      -      return this._constructionElement.getAttributeNS(null,
      -              Constants._ATT_TYPE);
      -   }
      -
      -   /**
      -    * Method isReferenceToObject
      -    *
      -    * This returns true if the Type attribute of the
      -    * Refernce element points to a #Object element
      -    *
      -    * @return true if the Reference type indicates that this Reference points to an Object
      -    */
      -   public boolean typeIsReferenceToObject() {
      -
      -      if (Reference.OBJECT_URI.equals(this.getType())) {
      -         return true;
      -      }
      -
      -      return false;
      -   }
      -
      -   /**
      -    * Method isReferenceToManifest
      -    *
      -    * This returns true if the Type attribute of the
      -    * Refernce element points to a #Manifest element
      -    *
      -    * @return true if the Reference type indicates that this Reference points to a {@link Manifest}
      -    */
      -   public boolean typeIsReferenceToManifest() {
      -
      -      if (Reference.MANIFEST_URI.equals(this.getType())) {
      -         return true;
      -      }
      -
      -      return false;
      -   }
      -
      -   /**
      -    * Method setDigestValueElement
      -    *
      -    * @param digestValue
      -    */
      -   private void setDigestValueElement(byte[] digestValue)
      -   {
      -         Node n=digestValueElement.getFirstChild();
      -         while (n!=null) {
      -               digestValueElement.removeChild(n);
      -               n = n.getNextSibling();
      -         }
      -
      -         String base64codedValue = Base64.encode(digestValue);
      -         Text t = this._doc.createTextNode(base64codedValue);
      -
      -         digestValueElement.appendChild(t);
      -   }
      -
      -   /**
      -    * Method generateDigestValue
      -    *
      -    * @throws ReferenceNotInitializedException
      -    * @throws XMLSignatureException
      -    */
      -   public void generateDigestValue()
      -           throws XMLSignatureException, ReferenceNotInitializedException {
      -      this.setDigestValueElement(this.calculateDigest(false));
      -   }
      -
      -   /**
      -    * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
      -    * @return the XMLSignatureInput of the source of this reference
      -    * @throws ReferenceNotInitializedException If the resolver found any
      -    *  problem resolving the reference
      -    */
      -   public XMLSignatureInput getContentsBeforeTransformation()
      -           throws ReferenceNotInitializedException {
      -
      -      try {
      -         Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
      -            Constants._ATT_URI);
      -         String URI;
      -
      -         if (URIAttr == null) {
      -            URI = null;
      -         } else {
      -            URI = URIAttr.getNodeValue();
      -         }
      -
      -         ResourceResolver resolver = ResourceResolver.getInstance(URIAttr,
      -            this._baseURI, this._manifest._perManifestResolvers);
      -
      -         if (resolver == null) {
      -            Object exArgs[] = { URI };
      -
      -            throw new ReferenceNotInitializedException(
      -               "signature.Verification.Reference.NoInput", exArgs);
      -         }
      -
      -         resolver.addProperties(this._manifest._resolverProperties);
      -
      -         XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
      -
      -
      -         return input;
      -      }  catch (ResourceResolverException ex) {
      -         throw new ReferenceNotInitializedException("empty", ex);
      -      } catch (XMLSecurityException ex) {
      -         throw new ReferenceNotInitializedException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * Returns the data which is referenced by the URI attribute. This method
      -    * only works works after a call to verify.
      -    * @return a XMLSignature with a byte array.
      -    * @throws ReferenceNotInitializedException
      -    *
      -    * @deprecated use getContentsBeforeTransformation
      -    */
      -   @Deprecated
      -   public XMLSignatureInput getTransformsInput() throws ReferenceNotInitializedException
      -        {
      -                XMLSignatureInput input=getContentsBeforeTransformation();
      -                XMLSignatureInput result;
      -                try {
      -                        result = new XMLSignatureInput(input.getBytes());
      -                } catch (CanonicalizationException ex) {
      -                         throw new ReferenceNotInitializedException("empty", ex);
      -                } catch (IOException ex) {
      -                         throw new ReferenceNotInitializedException("empty", ex);
      -                }
      -                result.setSourceURI(input.getSourceURI());
      -                return result;
      +    private Manifest manifest;
      +    private XMLSignatureInput transformsOutput;
       
      -   }
      +    private Transforms transforms;
       
      -   private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os)
      -           throws XMLSignatureException {
      +    private Element digestMethodElem;
       
      -      try {
      -         Transforms transforms = this.getTransforms();
      -         XMLSignatureInput output = null;
      -
      -         if (transforms != null) {
      -            output = transforms.performTransforms(input,os);
      -            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
      -
      -            //this._transformsOutput.setSourceURI(output.getSourceURI());
      -         } else {
      -            output = input;
      -         }
      -
      -         return output;
      -      } catch (ResourceResolverException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (CanonicalizationException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (InvalidCanonicalizerException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (TransformationException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (XMLSecurityException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * Returns the XMLSignatureInput which is the result of the Transforms.
      -    * @return a XMLSignatureInput with all transformations applied.
      -    * @throws XMLSignatureException
      -    */
      -   public XMLSignatureInput getContentsAfterTransformation()
      -           throws XMLSignatureException {
      -
      -      XMLSignatureInput input = this.getContentsBeforeTransformation();
      -
      -      return this.getContentsAfterTransformation(input, null);
      -   }
      -
      -   /**
      -    * This method returns the XMLSignatureInput which represents the node set before
      -    * some kind of canonicalization is applied for the first time.
      -    * @return Gets a the node doing everything till the first c14n is needed
      -    *
      -    * @throws XMLSignatureException
      -    */
      -   public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
      -           throws XMLSignatureException {
      -
      -      try {
      -         XMLSignatureInput input = this.getContentsBeforeTransformation();
      -         XMLSignatureInput output = input;
      -         Transforms transforms = this.getTransforms();
      -
      -         if (transforms != null) {
      -            doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
      -               Transform t = transforms.item(i);
      -               String URI = t.getURI();
      -
      -               if (URI.equals(Transforms
      -                       .TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || URI
      -                          .equals(Transforms
      -                             .TRANSFORM_C14N_EXCL_WITH_COMMENTS) || URI
      -                                .equals(Transforms
      -                                   .TRANSFORM_C14N_OMIT_COMMENTS) || URI
      -                                      .equals(Transforms
      -                                         .TRANSFORM_C14N_WITH_COMMENTS)) {
      +    private Element digestValueElement;
      +    
      +    private ReferenceData referenceData;
      +
      +    /**
      +     * Constructor Reference
      +     *
      +     * @param doc the {@link Document} in which XMLsignature is placed
      +     * @param baseURI the URI of the resource where the XML instance will be stored
      +     * @param referenceURI URI indicate where is data which will digested
      +     * @param manifest
      +     * @param transforms {@link Transforms} applied to data
      +     * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is 
      +     * applied to the data
      +     * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
      +     * @throws XMLSignatureException
      +     */
      +    protected Reference(
      +        Document doc, String baseURI, String referenceURI, Manifest manifest, 
      +        Transforms transforms, String messageDigestAlgorithm
      +    ) throws XMLSignatureException {
      +        super(doc);
      +
      +        XMLUtils.addReturnToElement(this.constructionElement);
      +
      +        this.baseURI = baseURI;
      +        this.manifest = manifest;
      +
      +        this.setURI(referenceURI);
      +
      +        // important: The ds:Reference must be added to the associated ds:Manifest
      +        //            or ds:SignedInfo _before_ the this.resolverResult() is called.
      +        // this.manifest.appendChild(this.constructionElement);
      +        // this.manifest.appendChild(this.doc.createTextNode("\n"));
      +
      +        if (transforms != null) {
      +            this.transforms=transforms;
      +            this.constructionElement.appendChild(transforms.getElement());
      +            XMLUtils.addReturnToElement(this.constructionElement);
      +        }
      +        MessageDigestAlgorithm mda =
      +            MessageDigestAlgorithm.getInstance(this.doc, messageDigestAlgorithm);
      +
      +        digestMethodElem = mda.getElement();
      +        this.constructionElement.appendChild(digestMethodElem);
      +        XMLUtils.addReturnToElement(this.constructionElement);
      +
      +        digestValueElement =
      +            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_DIGESTVALUE);
      +
      +        this.constructionElement.appendChild(digestValueElement);
      +        XMLUtils.addReturnToElement(this.constructionElement);
      +    }
      +
      +    
      +    /**
      +     * Build a {@link Reference} from an {@link Element}
      +     *
      +     * @param element Reference element
      +     * @param baseURI the URI of the resource where the XML instance was stored
      +     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
      +     * We need this because the Manifest has the individual {@link ResourceResolver}s which have 
      +     * been set by the user
      +     * @throws XMLSecurityException
      +     */
      +    protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
      +        this(element, baseURI, manifest, false);
      +    }
      +
      +    /**
      +     * Build a {@link Reference} from an {@link Element}
      +     *
      +     * @param element Reference element
      +     * @param baseURI the URI of the resource where the XML instance was stored
      +     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
      +     * @param secureValidation whether secure validation is enabled or not
      +     * We need this because the Manifest has the individual {@link ResourceResolver}s which have 
      +     * been set by the user
      +     * @throws XMLSecurityException
      +     */
      +    protected Reference(Element element, String baseURI, Manifest manifest, boolean secureValidation)
      +        throws XMLSecurityException {
      +        super(element, baseURI);
      +        this.secureValidation = secureValidation;
      +        this.baseURI = baseURI;
      +        Element el = XMLUtils.getNextElement(element.getFirstChild());
      +        if (Constants._TAG_TRANSFORMS.equals(el.getLocalName()) 
      +            && Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
      +            transforms = new Transforms(el, this.baseURI);
      +            transforms.setSecureValidation(secureValidation);
      +            if (secureValidation && transforms.getLength() > MAXIMUM_TRANSFORM_COUNT) {
      +                Object exArgs[] = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT };
      +                
      +                throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
      +            }
      +            el = XMLUtils.getNextElement(el.getNextSibling());
      +        }
      +        digestMethodElem = el;
      +        digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
      +        this.manifest = manifest;
      +    }
      +
      +    /**
      +     * Returns {@link MessageDigestAlgorithm}
      +     *
      +     *
      +     * @return {@link MessageDigestAlgorithm}
      +     *
      +     * @throws XMLSignatureException
      +     */
      +    public MessageDigestAlgorithm getMessageDigestAlgorithm() throws XMLSignatureException {
      +        if (digestMethodElem == null) {
      +            return null;
      +        }
      +
      +        String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
      +
      +        if (uri == null) {
      +            return null;
      +        }
      +        
      +        if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
      +            Object exArgs[] = { uri };
      +
      +            throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
      +        }
      +
      +        return MessageDigestAlgorithm.getInstance(this.doc, uri);
      +    }
      +
      +    /**
      +     * Sets the URI of this Reference element
      +     *
      +     * @param uri the URI of this Reference element
      +     */
      +    public void setURI(String uri) {
      +        if (uri != null) {
      +            this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
      +        }
      +    }
      +
      +    /**
      +     * Returns the URI of this Reference element
      +     *
      +     * @return URI the URI of this Reference element
      +     */
      +    public String getURI() {
      +        return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
      +    }
      +
      +    /**
      +     * Sets the Id attribute of this Reference element
      +     *
      +     * @param id the Id attribute of this Reference element
      +     */
      +    public void setId(String id) {
      +        if (id != null) {
      +            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
      +            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
      +        }
      +    }
      +
      +    /**
      +     * Returns the Id attribute of this Reference element
      +     *
      +     * @return Id the Id attribute of this Reference element
      +     */
      +    public String getId() {
      +        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
      +    }
      +
      +    /**
      +     * Sets the type atttibute of the Reference indicate whether an 
      +     * ds:Object, ds:SignatureProperty, or ds:Manifest 
      +     * element.
      +     *
      +     * @param type the type attribute of the Reference
      +     */
      +    public void setType(String type) {
      +        if (type != null) {
      +            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
      +        }
      +    }
      +
      +    /**
      +     * Return the type atttibute of the Reference indicate whether an 
      +     * ds:Object, ds:SignatureProperty, or ds:Manifest 
      +     * element
      +     *
      +     * @return the type attribute of the Reference
      +     */
      +    public String getType() {
      +        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
      +    }
      +
      +    /**
      +     * Method isReferenceToObject
      +     *
      +     * This returns true if the Type attribute of the
      +     * Reference element points to a #Object element
      +     *
      +     * @return true if the Reference type indicates that this Reference points to an 
      +     * Object
      +     */
      +    public boolean typeIsReferenceToObject() {
      +        if (Reference.OBJECT_URI.equals(this.getType())) {
      +            return true;
      +        }
      +
      +        return false;
      +    }
      +
      +    /**
      +     * Method isReferenceToManifest
      +     *
      +     * This returns true if the Type attribute of the
      +     * Reference element points to a #Manifest element
      +     *
      +     * @return true if the Reference type indicates that this Reference points to a 
      +     * {@link Manifest}
      +     */
      +    public boolean typeIsReferenceToManifest() {
      +        if (Reference.MANIFEST_URI.equals(this.getType())) {
      +            return true;
      +        }
      +
      +        return false;
      +    }
      +
      +    /**
      +     * Method setDigestValueElement
      +     *
      +     * @param digestValue
      +     */
      +    private void setDigestValueElement(byte[] digestValue) {
      +        Node n = digestValueElement.getFirstChild();
      +        while (n != null) {
      +            digestValueElement.removeChild(n);
      +            n = n.getNextSibling();
      +        }
      +
      +        String base64codedValue = Base64.encode(digestValue);
      +        Text t = this.doc.createTextNode(base64codedValue);
      +
      +        digestValueElement.appendChild(t);
      +    }
      +
      +    /**
      +     * Method generateDigestValue
      +     *
      +     * @throws ReferenceNotInitializedException
      +     * @throws XMLSignatureException
      +     */
      +    public void generateDigestValue()
      +        throws XMLSignatureException, ReferenceNotInitializedException {
      +        this.setDigestValueElement(this.calculateDigest(false));
      +    }
      +
      +    /**
      +     * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
      +     * @return the XMLSignatureInput of the source of this reference
      +     * @throws ReferenceNotInitializedException If the resolver found any
      +     * problem resolving the reference
      +     */
      +    public XMLSignatureInput getContentsBeforeTransformation()
      +        throws ReferenceNotInitializedException {
      +        try {
      +            Attr uriAttr = 
      +                this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
      +
      +            ResourceResolver resolver = 
      +                ResourceResolver.getInstance(
      +                    uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation
      +                );
      +            resolver.addProperties(this.manifest.getResolverProperties());
      +
      +            return resolver.resolve(uriAttr, this.baseURI, secureValidation);
      +        }  catch (ResourceResolverException ex) {
      +            throw new ReferenceNotInitializedException("empty", ex);
      +        }
      +    }
      +
      +    private XMLSignatureInput getContentsAfterTransformation(
      +        XMLSignatureInput input, OutputStream os
      +    ) throws XMLSignatureException {
      +        try {
      +            Transforms transforms = this.getTransforms();
      +            XMLSignatureInput output = null;
       
      -                  break doTransforms;
      -               }
      +            if (transforms != null) {
      +                output = transforms.performTransforms(input, os);
      +                this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
       
      -               output = t.performTransform(output, null);
      +                //this.transformsOutput.setSourceURI(output.getSourceURI());
      +            } else {
      +                output = input;
                   }
       
      +            return output;
      +        } catch (ResourceResolverException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (CanonicalizationException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (InvalidCanonicalizerException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (TransformationException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (XMLSecurityException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        }
      +    }
      +
      +    /**
      +     * Returns the XMLSignatureInput which is the result of the Transforms.
      +     * @return a XMLSignatureInput with all transformations applied.
      +     * @throws XMLSignatureException
      +     */
      +    public XMLSignatureInput getContentsAfterTransformation()
      +        throws XMLSignatureException {
      +        XMLSignatureInput input = this.getContentsBeforeTransformation();
      +        cacheDereferencedElement(input);
      +
      +        return this.getContentsAfterTransformation(input, null);
      +    }
      +
      +    /**
      +     * This method returns the XMLSignatureInput which represents the node set before
      +     * some kind of canonicalization is applied for the first time.
      +     * @return Gets a the node doing everything till the first c14n is needed
      +     *
      +     * @throws XMLSignatureException
      +     */
      +    public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
      +        throws XMLSignatureException {
      +        try {
      +            XMLSignatureInput input = this.getContentsBeforeTransformation();
      +            cacheDereferencedElement(input);
      +            XMLSignatureInput output = input;
      +            Transforms transforms = this.getTransforms();
      +
      +            if (transforms != null) {
      +                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
      +                    Transform t = transforms.item(i);
      +                    String uri = t.getURI();
      +
      +                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS) 
      +                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS) 
      +                        || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS) 
      +                        || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)) {
      +                        break doTransforms;
      +                    }
      +
      +                    output = t.performTransform(output, null);
      +                }
      +
                   output.setSourceURI(input.getSourceURI());
      -         }
      -         return output;
      -      } catch (IOException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (ResourceResolverException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (CanonicalizationException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (InvalidCanonicalizerException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (TransformationException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (XMLSecurityException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * Method getHTMLRepresentation
      -    * @return The HTML of the transformation
      -    * @throws XMLSignatureException
      -    */
      -   public String getHTMLRepresentation() throws XMLSignatureException {
      -
      -      try {
      -         XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
      -         Set inclusiveNamespaces = new HashSet();
      +            }
      +            return output;
      +        } catch (IOException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (ResourceResolverException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (CanonicalizationException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (InvalidCanonicalizerException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (TransformationException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (XMLSecurityException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        }
      +    }
      +
      +    /**
      +     * Method getHTMLRepresentation
      +     * @return The HTML of the transformation
      +     * @throws XMLSignatureException
      +     */
      +    public String getHTMLRepresentation() throws XMLSignatureException {
      +        try {
      +            XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
       
      -         {
                   Transforms transforms = this.getTransforms();
                   Transform c14nTransform = null;
       
                   if (transforms != null) {
      -               doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
      -                  Transform t = transforms.item(i);
      -                  String URI = t.getURI();
      +                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
      +                    Transform t = transforms.item(i);
      +                    String uri = t.getURI();
      +
      +                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
      +                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
      +                        c14nTransform = t;
      +                        break doTransforms;
      +                    }
      +                }
      +            }
      +
      +            Set inclusiveNamespaces = new HashSet();
      +            if (c14nTransform != null
      +                && (c14nTransform.length(
      +                    InclusiveNamespaces.ExclusiveCanonicalizationNamespace, 
      +                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
      +
      +                // there is one InclusiveNamespaces element
      +                InclusiveNamespaces in = 
      +                    new InclusiveNamespaces(
      +                        XMLUtils.selectNode(
      +                            c14nTransform.getElement().getFirstChild(),
      +                            InclusiveNamespaces.ExclusiveCanonicalizationNamespace, 
      +                            InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, 
      +                            0
      +                        ), this.getBaseURI());
      +
      +                inclusiveNamespaces = 
      +                    InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
      +            }
       
      -                  if (URI.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
      -                          || URI.equals(
      -                             Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
      -                     c14nTransform = t;
      +            return nodes.getHTMLRepresentation(inclusiveNamespaces);
      +        } catch (TransformationException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (InvalidTransformException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        } catch (XMLSecurityException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        }
      +    }
      +
      +    /**
      +     * This method only works works after a call to verify.
      +     * @return the transformed output(i.e. what is going to be digested).
      +     */
      +    public XMLSignatureInput getTransformsOutput() {
      +        return this.transformsOutput;
      +    }
      +    
      +    /**
      +     * Get the ReferenceData that corresponds to the cached representation of the dereferenced
      +     * object before transformation.
      +     */
      +    public ReferenceData getReferenceData() {
      +        return referenceData;
      +    }
      +
      +    /**
      +     * This method returns the {@link XMLSignatureInput} which is referenced by the
      +     * URI Attribute.
      +     * @param os where to write the transformation can be null.
      +     * @return the element to digest
      +     *
      +     * @throws XMLSignatureException
      +     * @see Manifest#verifyReferences()
      +     */
      +    protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
      +        throws XMLSignatureException {
      +        try {
      +            XMLSignatureInput input = this.getContentsBeforeTransformation();
      +            cacheDereferencedElement(input);
      +            
      +            XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
      +            this.transformsOutput = output;
      +            return output;
      +        } catch (XMLSecurityException ex) {
      +            throw new ReferenceNotInitializedException("empty", ex);
      +        }
      +    }
      +    
      +    /**
      +     * Store the dereferenced Element(s) so that it/they can be retrieved later.
      +     */
      +    private void cacheDereferencedElement(XMLSignatureInput input) {
      +        if (input.isNodeSet()) {
      +            try {
      +                final Set s = input.getNodeSet();
      +                referenceData = new ReferenceNodeSetData() {
      +                    public Iterator iterator() { 
      +                        return new Iterator() {
      +                            
      +                            Iterator sIterator = s.iterator();
      +                            
      +                            public boolean hasNext() {
      +                                return sIterator.hasNext();
      +                            }
      +
      +                            public Node next() {
      +                                return sIterator.next();
      +                            }
      +
      +                            public void remove() {
      +                                throw new UnsupportedOperationException();
      +                            }
      +                        };
      +                    }
      +                };
      +            } catch (Exception e) {
      +                // log a warning
      +                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
      +            }
      +        } else if (input.isElement()) {
      +            referenceData = new ReferenceSubTreeData
      +                (input.getSubNode(), input.isExcludeComments());
      +        } else if (input.isOctetStream() || input.isByteArray()) {
      +            try {
      +                referenceData = new ReferenceOctetStreamData
      +                    (input.getOctetStream(), input.getSourceURI(),
      +                        input.getMIMEType());
      +            } catch (IOException ioe) {
      +                // log a warning
      +                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
      +            }
      +        }
      +    }
       
      -                     break doTransforms;
      -                  }
      -               }
      +    /**
      +     * Method getTransforms
      +     *
      +     * @return The transforms that applied this reference.
      +     * @throws InvalidTransformException
      +     * @throws TransformationException
      +     * @throws XMLSecurityException
      +     * @throws XMLSignatureException
      +     */
      +    public Transforms getTransforms()
      +        throws XMLSignatureException, InvalidTransformException,
      +        TransformationException, XMLSecurityException {
      +        return transforms;           
      +    }
      +
      +    /**
      +     * Method getReferencedBytes
      +     * 
      +     * @return the bytes that will be used to generated digest.
      +     * @throws ReferenceNotInitializedException
      +     * @throws XMLSignatureException
      +     */
      +    public byte[] getReferencedBytes()
      +        throws ReferenceNotInitializedException, XMLSignatureException {
      +        try {
      +            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null);
      +            return output.getBytes();
      +        } catch (IOException ex) {
      +            throw new ReferenceNotInitializedException("empty", ex);
      +        } catch (CanonicalizationException ex) {
      +            throw new ReferenceNotInitializedException("empty", ex);
      +        } 
      +    }
      +
      +
      +    /**
      +     * Method calculateDigest
      +     *
      +     * @param validating true if validating the reference
      +     * @return reference Calculate the digest of this reference.
      +     * @throws ReferenceNotInitializedException
      +     * @throws XMLSignatureException
      +     */
      +    private byte[] calculateDigest(boolean validating)
      +        throws ReferenceNotInitializedException, XMLSignatureException {
      +        OutputStream os = null;
      +        try {
      +            MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
      +
      +            mda.reset();
      +            DigesterOutputStream diOs = new DigesterOutputStream(mda);
      +            os = new UnsyncBufferedOutputStream(diOs);
      +            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);         
      +            // if signing and c14n11 property == true explicitly add
      +            // C14N11 transform if needed
      +            if (Reference.useC14N11 && !validating && !output.isOutputStreamSet() 
      +                && !output.isOctetStream()) {
      +                if (transforms == null) {
      +                    transforms = new Transforms(this.doc);
      +                    transforms.setSecureValidation(secureValidation);
      +                    this.constructionElement.insertBefore(transforms.getElement(), digestMethodElem);
      +                }
      +                transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
      +                output.updateOutputStream(os, true);
      +            } else {
      +                output.updateOutputStream(os);
                   }
      +            os.flush();
      +            
      +            if (output.getOctetStreamReal() != null) {
      +                output.getOctetStreamReal().close();
      +            }
      +            
      +            //this.getReferencedBytes(diOs);
      +            //mda.update(data);
      +
      +            return diOs.getDigestValue();
      +        } catch (XMLSecurityException ex) {
      +            throw new ReferenceNotInitializedException("empty", ex);
      +        } catch (IOException ex) {
      +            throw new ReferenceNotInitializedException("empty", ex);
      +        } finally {
      +            if (os != null) {
      +                try {
      +                    os.close();
      +                } catch (IOException ex) {
      +                    throw new ReferenceNotInitializedException("empty", ex);
      +                } 
      +            }
      +        }
      +    }
       
      -            if (c14nTransform != null) {
      +    /**
      +     * Returns the digest value.
      +     *
      +     * @return the digest value.
      +     * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
      +     * @throws XMLSecurityException if the Reference does not contain a DigestValue element
      +     */
      +    public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
      +        if (digestValueElement == null) {
      +            // The required element is not in the XML!
      +            Object[] exArgs ={ Constants._TAG_DIGESTVALUE, Constants.SignatureSpecNS };
      +            throw new XMLSecurityException(
      +                "signature.Verification.NoSignatureElement", exArgs
      +            );
      +        }
      +        return Base64.decode(digestValueElement);
      +    }
      +
      +
      +    /**
      +     * Tests reference validation is success or false
      +     *
      +     * @return true if reference validation is success, otherwise false
      +     * @throws ReferenceNotInitializedException
      +     * @throws XMLSecurityException
      +     */
      +    public boolean verify()
      +        throws ReferenceNotInitializedException, XMLSecurityException {
      +        byte[] elemDig = this.getDigestValue();
      +        byte[] calcDig = this.calculateDigest(true);
      +        boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
      +
      +        if (!equal) {
      +            log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
      +            log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
      +            log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
      +        } else {
      +            if (log.isLoggable(java.util.logging.Level.FINE)) {
      +                log.log(java.util.logging.Level.FINE, "Verification successful for URI \"" + this.getURI() + "\"");
      +            }
      +        }
       
      -               if (c14nTransform
      -                       .length(InclusiveNamespaces
      -                          .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
      -                          ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
      +        return equal;
      +    }
       
      -                  // there is one InclusiveNamespaces element
      -                  InclusiveNamespaces in = new InclusiveNamespaces(
      -                        XMLUtils.selectNode(
      -                        c14nTransform.getElement().getFirstChild(),
      -                                                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
      -                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
      -
      -                  inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
      -                     in.getInclusiveNamespaces());
      -               }
      -            }
      -         }
      -
      -         return nodes.getHTMLRepresentation(inclusiveNamespaces);
      -      } catch (TransformationException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (InvalidTransformException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      } catch (XMLSecurityException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * This method only works works after a call to verify.
      -    * @return the transformed output(i.e. what is going to be digested).
      -    */
      -   public XMLSignatureInput getTransformsOutput() {
      -      return this._transformsOutput;
      -   }
      -
      -   /**
      -    * This method returns the {@link XMLSignatureInput} which is referenced by the
      -    * URI Attribute.
      -    * @param os where to write the transformation can be null.
      -    * @return the element to digest
      -    *
      -    * @throws XMLSignatureException
      -    * @see Manifest#verifyReferences()
      -    */
      -   protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
      -           throws XMLSignatureException {
      -
      -      try {
      -         XMLSignatureInput input = this.getContentsBeforeTransformation();
      -         XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
      -
      -         /* at this stage, this._transformsInput and this._transformsOutput
      -          * contain a huge amount of nodes. When we do not cache these nodes
      -          * but only preserve the octets, the memory footprint is dramatically
      -          * reduced.
      -          */
      -         if (!Reference.CacheSignedNodes) {
      -
      -            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
      -
      -            //this._transformsOutput.setSourceURI(output.getSourceURI());
      -         }
      -         return output;
      -      } catch (XMLSecurityException ex) {
      -         throw new ReferenceNotInitializedException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * Method getTransforms
      -    *
      -    * @return The transforms that applied this reference.
      -    * @throws InvalidTransformException
      -    * @throws TransformationException
      -    * @throws XMLSecurityException
      -    * @throws XMLSignatureException
      -    */
      -   public Transforms getTransforms()
      -           throws XMLSignatureException, InvalidTransformException,
      -                  TransformationException, XMLSecurityException {
      -
      -      return transforms;
      -   }
      -
      -   /**
      -    * Method getReferencedBytes
      -    *
      -    * @return the bytes that will be used to generated digest.
      -    * @throws ReferenceNotInitializedException
      -    * @throws XMLSignatureException
      -    */
      -   public byte[] getReferencedBytes()
      -           throws ReferenceNotInitializedException, XMLSignatureException {
      -    try {
      -        XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);
      -
      -        byte[] signedBytes = output.getBytes();
      -
      -        return signedBytes;
      -     } catch (IOException ex) {
      -        throw new ReferenceNotInitializedException("empty", ex);
      -     } catch (CanonicalizationException ex) {
      -        throw new ReferenceNotInitializedException("empty", ex);
      -     }
      -
      -   }
      -
      -
      -   /**
      -    * Method calculateDigest
      -    *
      -    * @param validating true if validating the reference
      -    * @return reference Calculate the digest of this reference.
      -    * @throws ReferenceNotInitializedException
      -    * @throws XMLSignatureException
      -    */
      -   private byte[] calculateDigest(boolean validating)
      -           throws ReferenceNotInitializedException, XMLSignatureException {
      -
      -      try {
      -
      -         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
      -
      -         mda.reset();
      -         DigesterOutputStream diOs=new DigesterOutputStream(mda);
      -         OutputStream os=new UnsyncBufferedOutputStream(diOs);
      -         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);
      -         // if signing and c14n11 property == true explicitly add
      -         // C14N11 transform if needed
      -         if (Reference.useC14N11 && !validating &&
      -             !output.isOutputStreamSet() && !output.isOctetStream()) {
      -             if (transforms == null) {
      -                 transforms = new Transforms(this._doc);
      -                 this._constructionElement.insertBefore
      -                     (transforms.getElement(), digestMethodElem);
      -             }
      -             transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
      -             output.updateOutputStream(os, true);
      -         } else {
      -             output.updateOutputStream(os);
      -         }
      -         os.flush();
      -         //this.getReferencedBytes(diOs);
      -         //mda.update(data);
      -
      -         return diOs.getDigestValue();
      -      } catch (XMLSecurityException ex) {
      -         throw new ReferenceNotInitializedException("empty", ex);
      -      } catch (IOException ex) {
      -         throw new ReferenceNotInitializedException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * Returns the digest value.
      -    *
      -    * @return the digest value.
      -    * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
      -    * @throws XMLSecurityException if the Reference does not contain a DigestValue element
      -    */
      -   public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
      -      if (digestValueElement == null) {
      -                  // The required element is not in the XML!
      -                  Object[] exArgs ={ Constants._TAG_DIGESTVALUE,
      -                                                         Constants.SignatureSpecNS };
      -                  throw new XMLSecurityException(
      -                                        "signature.Verification.NoSignatureElement",
      -                                        exArgs);
      -          }
      -      byte[] elemDig = Base64.decode(digestValueElement);
      -      return elemDig;
      -   }
      -
      -
      -   /**
      -    * Tests reference valdiation is success or false
      -    *
      -    * @return true if reference valdiation is success, otherwise false
      -    * @throws ReferenceNotInitializedException
      -    * @throws XMLSecurityException
      -    */
      -   public boolean verify()
      -           throws ReferenceNotInitializedException, XMLSecurityException {
      -
      -      byte[] elemDig = this.getDigestValue();
      -      byte[] calcDig = this.calculateDigest(true);
      -      boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
      -
      -      if (!equal) {
      -         log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
      -         log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
      -         log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
      -      } else {
      -         log.log(java.util.logging.Level.INFO, "Verification successful for URI \"" + this.getURI() + "\"");
      -      }
      -
      -      return equal;
      -   }
      -
      -   /**
      -    * Method getBaseLocalName
      -    * @inheritDoc
      -    *
      -    */
      -   public String getBaseLocalName() {
      -      return Constants._TAG_REFERENCE;
      -   }
      +    /**
      +     * Method getBaseLocalName
      +     * @inheritDoc
      +     */
      +    public String getBaseLocalName() {
      +        return Constants._TAG_REFERENCE;
      +    }
       }
      --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	2013-06-28 11:34:00.385593944 -0400
      +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java	2013-06-28 11:34:00.209599424 -0400
      @@ -2,28 +2,26 @@
        * reserved comment block
        * DO NOT REMOVE OR ALTER!
        */
      -/*
      - * Copyright  1999-2004 The Apache Software Foundation.
      - *
      - *  Licensed 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
      +/**
      + * 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
        *
      - *  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.
      + * http://www.apache.org/licenses/LICENSE-2.0
        *
      + * Unless required by applicable law or agreed to in writing,
      + * software distributed under the License is distributed on an
      + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      + * KIND, either express or implied. See the License for the
      + * specific language governing permissions and limitations
      + * under the License.
        */
       package com.sun.org.apache.xml.internal.security.signature;
       
      -
      -
      -
      -
       /**
        * Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
        * because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
      @@ -32,58 +30,56 @@
        */
       public class ReferenceNotInitializedException extends XMLSignatureException {
       
      -   /**
      -         *
      -         */
      -        private static final long serialVersionUID = 1L;
      -
      -   /**
      -    * Constructor ReferenceNotInitializedException
      -    *
      -    */
      -   public ReferenceNotInitializedException() {
      -      super();
      -   }
      -
      -   /**
      -    * Constructor ReferenceNotInitializedException
      -    *
      -    * @param _msgID
      -    */
      -   public ReferenceNotInitializedException(String _msgID) {
      -      super(_msgID);
      -   }
      -
      -   /**
      -    * Constructor ReferenceNotInitializedException
      -    *
      -    * @param _msgID
      -    * @param exArgs
      -    */
      -   public ReferenceNotInitializedException(String _msgID, Object exArgs[]) {
      -      super(_msgID, exArgs);
      -   }
      -
      -   /**
      -    * Constructor ReferenceNotInitializedException
      -    *
      -    * @param _msgID
      -    * @param _originalException
      -    */
      -   public ReferenceNotInitializedException(String _msgID,
      -                                           Exception _originalException) {
      -      super(_msgID, _originalException);
      -   }
      -
      -   /**
      -    * Constructor ReferenceNotInitializedException
      -    *
      -    * @param _msgID
      -    * @param exArgs
      -    * @param _originalException
      -    */
      -   public ReferenceNotInitializedException(String _msgID, Object exArgs[],
      -                                           Exception _originalException) {
      -      super(_msgID, exArgs, _originalException);
      -   }
      +    /**
      +     * 
      +     */
      +    private static final long serialVersionUID = 1L;
      +
      +    /**
      +     * Constructor ReferenceNotInitializedException
      +     *
      +     */
      +    public ReferenceNotInitializedException() {
      +        super();
      +    }
      +
      +    /**
      +     * Constructor ReferenceNotInitializedException
      +     *
      +     * @param msgID
      +     */
      +    public ReferenceNotInitializedException(String msgID) {
      +        super(msgID);
      +    }
      +
      +    /**
      +     * Constructor ReferenceNotInitializedException
      +     *
      +     * @param msgID
      +     * @param exArgs
      +     */
      +    public ReferenceNotInitializedException(String msgID, Object exArgs[]) {
      +        super(msgID, exArgs);
      +    }
      +
      +    /**
      +     * Constructor ReferenceNotInitializedException
      +     *
      +     * @param msgID
      +     * @param originalException
      +     */
      +    public ReferenceNotInitializedException(String msgID, Exception originalException) {
      +        super(msgID, originalException);
      +    }
      +
      +    /**
      +     * Constructor ReferenceNotInitializedException
      +     *
      +     * @param msgID
      +     * @param exArgs
      +     * @param originalException
      +     */
      +    public ReferenceNotInitializedException(String msgID, Object exArgs[], Exception originalException) {
      +        super(msgID, exArgs, originalException);
      +    }
       }
      --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	2013-06-28 11:34:00.985575268 -0400
      +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java	2013-06-28 11:34:00.817580496 -0400
      @@ -2,34 +2,34 @@
        * reserved comment block
        * DO NOT REMOVE OR ALTER!
        */
      -/*
      - * Copyright  1999-2004 The Apache Software Foundation.
      - *
      - *  Licensed 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.
      - *
      +/**
      + * Licensed to the Apache Software Foundation (ASF) under one
      + * or more contributor license agreements. See the NOTICE file
      + * distributed with this work for additional information
      + * regarding copyright ownership. The ASF licenses this file
      + * to you under the Apache License, Version 2.0 (the
      + * "License"); you may not use this file except in compliance
      + * with the License. You may obtain a copy of the License at
      + *
      + * http://www.apache.org/licenses/LICENSE-2.0
      + *
      + * Unless required by applicable law or agreed to in writing,
      + * software distributed under the License is distributed on an
      + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      + * KIND, either express or implied. See the License for the
      + * specific language governing permissions and limitations
      + * under the License.
        */
       package com.sun.org.apache.xml.internal.security.signature;
       
       import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
       import com.sun.org.apache.xml.internal.security.utils.Constants;
      -import com.sun.org.apache.xml.internal.security.utils.IdResolver;
       import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
       import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
       import org.w3c.dom.Attr;
       import org.w3c.dom.Document;
       import org.w3c.dom.Element;
       
      -
       /**
        * Handles <ds:SignatureProperties> elements
        * This Element holds {@link SignatureProperty} that contian additional information items
      @@ -37,120 +37,112 @@
        * for example, data-time stamp, serial number of cryptographic hardware.
        *
        * @author Christian Geuer-Pollmann
      - *
        */
       public class SignatureProperties extends SignatureElementProxy {
       
      -   /**
      -    * Constructor SignatureProperties
      -    *
      -    * @param doc
      -    */
      -   public SignatureProperties(Document doc) {
      -
      -      super(doc);
      -
      -      XMLUtils.addReturnToElement(this._constructionElement);
      -   }
      -
      -   /**
      -    * Constructs {@link SignatureProperties} from {@link Element}
      -    * @param element SignatureProperties elementt
      -    * @param BaseURI the URI of the resource where the XML instance was stored
      -    * @throws XMLSecurityException
      -    */
      -   public SignatureProperties(Element element, String BaseURI)
      -           throws XMLSecurityException {
      -      super(element, BaseURI);
      -
      -      Attr attr = element.getAttributeNodeNS(null, "Id");
      -      if (attr != null) {
      -          element.setIdAttributeNode(attr, true);
      -      }
      -
      -      int length = getLength();
      -      for (int i = 0; i < length; i++) {
      -          Element propertyElem =
      -              XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
      -          Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
      -          if (propertyAttr != null) {
      -              propertyElem.setIdAttributeNode(propertyAttr, true);
      -          }
      -      }
      -   }
      -
      -   /**
      -    * Return the nonnegative number of added SignatureProperty elements.
      -    *
      -    * @return the number of SignatureProperty elements
      -    */
      -   public int getLength() {
      -
      -         Element[] propertyElems =
      -            XMLUtils.selectDsNodes(this._constructionElement,
      -                                     Constants._TAG_SIGNATUREPROPERTY
      -                                    );
      -
      -         return propertyElems.length;
      -   }
      -
      -   /**
      -    * Return the ith SignatureProperty.  Valid i
      -    * values are 0 to {link@ getSize}-1.
      -    *
      -    * @param i Index of the requested {@link SignatureProperty}
      -    * @return the ith SignatureProperty
      -    * @throws XMLSignatureException
      -    */
      -   public SignatureProperty item(int i) throws XMLSignatureException {
      -          try {
      -         Element propertyElem =
      -            XMLUtils.selectDsNode(this._constructionElement,
      -                                 Constants._TAG_SIGNATUREPROPERTY,
      -                                 i );
      -
      -         if (propertyElem == null) {
      -            return null;
      -         }
      -         return new SignatureProperty(propertyElem, this._baseURI);
      -      } catch (XMLSecurityException ex) {
      -         throw new XMLSignatureException("empty", ex);
      -      }
      -   }
      -
      -   /**
      -    * Sets the Id attribute
      -    *
      -    * @param Id the Id attribute
      -    */
      -   public void setId(String Id) {
      -
      -      if (Id != null) {
      -          setLocalIdAttribute(Constants._ATT_ID, Id);
      -      }
      -   }
      -
      -   /**
      -    * Returns the Id attribute
      -    *
      -    * @return the Id attribute
      -    */
      -   public String getId() {
      -      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
      -   }
      -
      -   /**
      -    * Method addSignatureProperty
      -    *
      -    * @param sp
      -    */
      -   public void addSignatureProperty(SignatureProperty sp) {
      -      this._constructionElement.appendChild(sp.getElement());
      -      XMLUtils.addReturnToElement(this._constructionElement);
      -   }
      -
      -   /** @inheritDoc */
      -   public String getBaseLocalName() {
      -      return Constants._TAG_SIGNATUREPROPERTIES;
      -   }
      +    /**
      +     * Constructor SignatureProperties
      +     *
      +     * @param doc
      +     */
      +    public SignatureProperties(Document doc) {
      +        super(doc);
      +
      +        XMLUtils.addReturnToElement(this.constructionElement);
      +    }
      +
      +    /**
      +     * Constructs {@link SignatureProperties} from {@link Element}
      +     * @param element SignatureProperties element
      +     * @param BaseURI the URI of the resource where the XML instance was stored
      +     * @throws XMLSecurityException
      +     */
      +    public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
      +        super(element, BaseURI);
      +        
      +        Attr attr = element.getAttributeNodeNS(null, "Id");
      +        if (attr != null) {
      +            element.setIdAttributeNode(attr, true);
      +        }
      +        
      +        int length = getLength();
      +        for (int i = 0; i < length; i++) {
      +            Element propertyElem =
      +                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
      +            Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
      +            if (propertyAttr != null) {
      +                propertyElem.setIdAttributeNode(propertyAttr, true);
      +            }
      +        }
      +    }
      +
      +    /**
      +     * Return the nonnegative number of added SignatureProperty elements.
      +     *
      +     * @return the number of SignatureProperty elements
      +     */
      +    public int getLength() {
      +        Element[] propertyElems =
      +            XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
      +
      +        return propertyElems.length;
      +    }
      +
      +    /**
      +     * Return the ith SignatureProperty. Valid i
      +     * values are 0 to {link@ getSize}-1.
      +     *
      +     * @param i Index of the requested {@link SignatureProperty}
      +     * @return the ith SignatureProperty
      +     * @throws XMLSignatureException
      +     */
      +    public SignatureProperty item(int i) throws XMLSignatureException {
      +        try {
      +            Element propertyElem =
      +                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
      +
      +            if (propertyElem == null) {
      +                return null;
      +            } 
      +            return new SignatureProperty(propertyElem, this.baseURI);               
      +        } catch (XMLSecurityException ex) {
      +            throw new XMLSignatureException("empty", ex);
      +        }
      +    }
      +
      +    /**
      +     * Sets the Id attribute
      +     *
      +     * @param Id the Id attribute
      +     */
      +    public void setId(String Id) {
      +        if (Id != null) {
      +            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
      +            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
      +        }
      +    }
      +
      +    /**
      +     * Returns the Id attribute
      +     *
      +     * @return the Id attribute
      +     */
      +    public String getId() {
      +        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
      +    }
      +
      +    /**
      +     * Method addSignatureProperty
      +     *
      +     * @param sp
      +     */
      +    public void addSignatureProperty(SignatureProperty sp) {
      +        this.constructionElement.appendChild(sp.getElement());
      +        XMLUtils.addReturnToElement(this.constructionElement);
      +    }
      +
      +    /** @inheritDoc */
      +    public String getBaseLocalName() {
      +        return Constants._TAG_SIGNATUREPROPERTIES;
      +    }
       }
      --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	2013-06-28 11:34:01.585556593 -0400
      +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java	2013-06-28 11:34:01.409562072 -0400
      @@ -2,27 +2,28 @@
        * reserved comment block
        * DO NOT REMOVE OR ALTER!
        */
      -/*
      - * Copyright  1999-2004 The Apache Software Foundation.
      - *
      - *  Licensed 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
      +/**
      + * 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
        *
      - *  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.
      + * http://www.apache.org/licenses/LICENSE-2.0
        *
      + * Unless required by applicable law or agreed to in writing,
      + * software distributed under the License is distributed on an
      + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      + * KIND, either express or implied. See the License for the
      + * specific language governing permissions and limitations
      + * under the License.
        */
       package com.sun.org.apache.xml.internal.security.signature;
       
       import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
       import com.sun.org.apache.xml.internal.security.utils.Constants;
      -import com.sun.org.apache.xml.internal.security.utils.IdResolver;
       import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
       import org.w3c.dom.Document;
       import org.w3c.dom.Element;
      @@ -37,96 +38,96 @@
        */
       public class SignatureProperty extends SignatureElementProxy {
       
      -   /**
      -    * Constructs{@link SignatureProperty} using specified Target attribute
      -    *
      -    * @param doc the {@link Document} in which XMLsignature is placed
      -    * @param Target the Target attribute references the Signature element to which the property applies SignatureProperty
      -    */
      -   public SignatureProperty(Document doc, String Target) {
      -      this(doc, Target, null);
      -   }
      -
      -   /**
      -    * Constructs {@link SignatureProperty} using sepcified Target attribute and Id attribute
      -    *
      -    * @param doc the {@link Document} in which XMLsignature is placed
      -    * @param Target the Target attribute references the Signature element to which the property applies
      -    * @param Id the Id will be specified by {@link Reference#getURI} in validation
      -    */
      -   public SignatureProperty(Document doc, String Target, String Id) {
      -
      -      super(doc);
      -
      -      this.setTarget(Target);
      -      this.setId(Id);
      -   }
      -
      -   /**
      -    * Constructs a {@link SignatureProperty} from an {@link Element}
      -    * @param element SignatureProperty element
      -    * @param BaseURI the URI of the resource where the XML instance was stored
      -    * @throws XMLSecurityException
      -    */
      -   public SignatureProperty(Element element, String BaseURI)
      -           throws XMLSecurityException {
      -      super(element, BaseURI);
      -   }
      -
      -   /**
      -    *   Sets the Id attribute
      -    *
      -    *   @param Id the Id attribute
      -    */
      -   public void setId(String Id) {
      -
      -      if (Id != null) {
      -          setLocalIdAttribute(Constants._ATT_ID, Id);
      -      }
      -   }
      -
      -   /**
      -    * Returns the Id attribute
      -    *
      -    * @return the Id attribute
      -    */
      -   public String getId() {
      -      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
      -   }
      -
      -   /**
      -    * Sets the Target attribute
      -    *
      -    * @param Target the Target attribute
      -    */
      -   public void setTarget(String Target) {
      -
      -      if ((Target != null)) {
      -         this._constructionElement.setAttributeNS(null, Constants._ATT_TARGET, Target);
      -      }
      -   }
      -
      -   /**
      -    * Returns the Target attribute
      -    *
      -    * @return the Target attribute
      -    */
      -   public String getTarget() {
      -      return this._constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
      -   }
      -
      -   /**
      -    * Method appendChild
      -    *
      -    * @param node
      -    * @return the node in this element.
      -    */
      -   public Node appendChild(Node node) {
      -      return this._constructionElement.appendChild(node);
      -   }
      -
      -   /** @inheritDoc */
      -   public String getBaseLocalName() {
      -      return Constants._TAG_SIGNATUREPROPERTY;
      -   }
      +    /**
      +     * Constructs{@link SignatureProperty} using specified target attribute
      +     *
      +     * @param doc the {@link Document} in which XMLsignature is placed
      +     * @param target the target attribute references the Signature 
      +     * element to which the property applies SignatureProperty
      +     */
      +    public SignatureProperty(Document doc, String target) {
      +        this(doc, target, null);
      +    }
      +
      +    /**
      +     * Constructs {@link SignatureProperty} using sepcified target attribute and 
      +     * id attribute
      +     *
      +     * @param doc the {@link Document} in which XMLsignature is placed
      +     * @param target the target attribute references the Signature
      +     *  element to which the property applies
      +     * @param id the id will be specified by {@link Reference#getURI} in validation
      +     */
      +    public SignatureProperty(Document doc, String target, String id) {
      +        super(doc);
      +
      +        this.setTarget(target);
      +        this.setId(id);
      +    }
      +
      +    /**
      +     * Constructs a {@link SignatureProperty} from an {@link Element}
      +     * @param element SignatureProperty element
      +     * @param BaseURI the URI of the resource where the XML instance was stored
      +     * @throws XMLSecurityException
      +     */
      +    public SignatureProperty(Element element, String BaseURI) throws XMLSecurityException {
      +        super(element, BaseURI);
      +    }
      +
      +    /**
      +     *   Sets the id attribute
      +     *
      +     *   @param id the id attribute
      +     */
      +    public void setId(String id) {
      +        if (id != null) {
      +            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
      +            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
      +        }
      +    }
      +
      +    /**
      +     * Returns the id attribute
      +     *
      +     * @return the id attribute
      +     */
      +    public String getId() {
      +        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
      +    }
      +
      +    /**
      +     * Sets the target attribute
      +     *
      +     * @param target the target attribute
      +     */
      +    public void setTarget(String target) {
      +        if (target != null) {
      +            this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
      +        }
      +    }
      +
      +    /**
      +     * Returns the target attribute
      +     *
      +     * @return the target attribute
      +     */
      +    public String getTarget() {
      +        return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
      +    }
      +
      +    /**
      +     * Method appendChild
      +     *
      +     * @param node
      +     * @return the node in this element.
      +     */
      +    public Node appendChild(Node node) {
      +        return this.constructionElement.appendChild(node);
      +    }
      +
      +    /** @inheritDoc */
      +    public String getBaseLocalName() {
      +        return Constants._TAG_SIGNATUREPROPERTY;
      +    }
       }
      --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	2013-06-28 11:34:02.197537545 -0400
      +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java	2013-06-28 11:34:02.033542649 -0400
      @@ -2,21 +2,23 @@
        * reserved comment block
        * DO NOT REMOVE OR ALTER!
        */
      -/*
      - * Copyright  1999-2004 The Apache Software Foundation.
      - *
      - *  Licensed 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
      +/**
      + * 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
        *
      - *  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.
      + * http://www.apache.org/licenses/LICENSE-2.0
        *
      + * Unless required by applicable law or agreed to in writing,
      + * software distributed under the License is distributed on an
      + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      + * KIND, either express or implied. See the License for the
      + * specific language governing permissions and limitations
      + * under the License.
        */
       package com.sun.org.apache.xml.internal.security.signature;
       
      @@ -50,42 +52,42 @@
        */
       public class SignedInfo extends Manifest {
       
      -    /** Field _signatureAlgorithm */
      -    private SignatureAlgorithm _signatureAlgorithm = null;
      +    /** Field signatureAlgorithm */
      +    private SignatureAlgorithm signatureAlgorithm = null;
       
      -    /** Field _c14nizedBytes           */
      -    private byte[] _c14nizedBytes = null;
      +    /** Field c14nizedBytes           */
      +    private byte[] c14nizedBytes = null;
       
           private Element c14nMethod;
           private Element signatureMethod;
       
           /**
      -     * Overwrites {@link Manifest#addDocument} because it creates another
      +     * Overwrites {@link Manifest#addDocument} because it creates another 
            * Element.
            *
      -     * @param doc the {@link Document} in which XMLsignature will
      +     * @param doc the {@link Document} in which XMLsignature will 
            *    be placed
            * @throws XMLSecurityException
            */
           public SignedInfo(Document doc) throws XMLSecurityException {
      -        this(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA,
      +        this(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA, 
                    Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
           }
       
           /**
      -     * Constructs {@link SignedInfo} using given Canonicalization algorithm and
      +     * Constructs {@link SignedInfo} using given Canonicalization algorithm and 
            * Signature algorithm.
            *
            * @param doc SignedInfo is placed in this document
      -     * @param signatureMethodURI URI representation of the Digest and
      +     * @param signatureMethodURI URI representation of the Digest and 
            *    Signature algorithm
      -     * @param canonicalizationMethodURI URI representation of the
      +     * @param canonicalizationMethodURI URI representation of the 
            *    Canonicalization method
            * @throws XMLSecurityException
            */
      -    public SignedInfo(Document doc, String signatureMethodURI,
      -        String canonicalizationMethodURI)
      -              throws XMLSecurityException {
      +    public SignedInfo(
      +        Document doc, String signatureMethodURI, String canonicalizationMethodURI
      +    ) throws XMLSecurityException {
               this(doc, signatureMethodURI, 0, canonicalizationMethodURI);
           }
       
      @@ -93,38 +95,36 @@
            * Constructor SignedInfo
            *
            * @param doc SignedInfo is placed in this document
      -     * @param signatureMethodURI URI representation of the Digest and
      +     * @param signatureMethodURI URI representation of the Digest and 
            *    Signature algorithm
            * @param hMACOutputLength
      -     * @param canonicalizationMethodURI URI representation of the
      +     * @param canonicalizationMethodURI URI representation of the 
            *    Canonicalization method
            * @throws XMLSecurityException
            */
      -    public SignedInfo(Document doc, String signatureMethodURI,
      -        int hMACOutputLength, String canonicalizationMethodURI)
      -              throws XMLSecurityException {
      -
      +    public SignedInfo(
      +        Document doc, String signatureMethodURI, 
      +        int hMACOutputLength, String canonicalizationMethodURI
      +    ) throws XMLSecurityException {
               super(doc);
       
      -        c14nMethod = XMLUtils.createElementInSignatureSpace(this._doc,
      -                                Constants._TAG_CANONICALIZATIONMETHOD);
      +        c14nMethod = 
      +            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
       
      -        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM,
      -                                  canonicalizationMethodURI);
      -        this._constructionElement.appendChild(c14nMethod);
      -        XMLUtils.addReturnToElement(this._constructionElement);
      +        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
      +        this.constructionElement.appendChild(c14nMethod);
      +        XMLUtils.addReturnToElement(this.constructionElement);
       
               if (hMACOutputLength > 0) {
      -            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
      -                    signatureMethodURI, hMACOutputLength);
      +            this.signatureAlgorithm = 
      +                new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
               } else {
      -            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
      -                    signatureMethodURI);
      +            this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
               }
       
      -        signatureMethod = this._signatureAlgorithm.getElement();
      -        this._constructionElement.appendChild(signatureMethod);
      -        XMLUtils.addReturnToElement(this._constructionElement);
      +        signatureMethod = this.signatureAlgorithm.getElement();
      +        this.constructionElement.appendChild(signatureMethod);
      +        XMLUtils.addReturnToElement(this.constructionElement);
           }
       
           /**
      @@ -133,22 +133,22 @@
            * @param canonicalizationMethodElem
            * @throws XMLSecurityException
            */
      -    public SignedInfo(Document doc, Element signatureMethodElem,
      -        Element canonicalizationMethodElem) throws XMLSecurityException {
      -
      +    public SignedInfo(
      +        Document doc, Element signatureMethodElem, Element canonicalizationMethodElem
      +    ) throws XMLSecurityException {
               super(doc);
               // Check this?
               this.c14nMethod = canonicalizationMethodElem;
      -        this._constructionElement.appendChild(c14nMethod);
      -        XMLUtils.addReturnToElement(this._constructionElement);
      +        this.constructionElement.appendChild(c14nMethod);
      +        XMLUtils.addReturnToElement(this.constructionElement);
       
      -        this._signatureAlgorithm =
      +        this.signatureAlgorithm = 
                   new SignatureAlgorithm(signatureMethodElem, null);
       
      -        signatureMethod = this._signatureAlgorithm.getElement();
      -        this._constructionElement.appendChild(signatureMethod);
      +        signatureMethod = this.signatureAlgorithm.getElement();
      +        this.constructionElement.appendChild(signatureMethod);
       
      -        XMLUtils.addReturnToElement(this._constructionElement);
      +        XMLUtils.addReturnToElement(this.constructionElement);
           }
       
           /**
      @@ -157,48 +157,76 @@
            * @param element SignedInfo
            * @param baseURI the URI of the resource where the XML instance was stored
            * @throws XMLSecurityException
      -     * @see Question
      -     * @see Answer
      +     * @see 
      +     * Question
      +     * @see 
      +     * Answer
            */
      -    public SignedInfo(Element element, String baseURI)
      -           throws XMLSecurityException {
      -
      +    public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
      +        this(element, baseURI, false);
      +    }
      +    
      +    /**
      +     * Build a {@link SignedInfo} from an {@link Element}
      +     *
      +     * @param element SignedInfo
      +     * @param baseURI the URI of the resource where the XML instance was stored
      +     * @param secureValidation whether secure validation is enabled or not
      +     * @throws XMLSecurityException
      +     * @see 
      +     * Question
      +     * @see 
      +     * Answer
      +     */
      +    public SignedInfo(
      +        Element element, String baseURI, boolean secureValidation
      +    ) throws XMLSecurityException {
               // Parse the Reference children and Id attribute in the Manifest
      -        super(element, baseURI);
      +        super(reparseSignedInfoElem(element), baseURI, secureValidation);
       
      -        /* canonicalize ds:SignedInfo, reparse it into a new document
      +        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
      +        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
      +        this.signatureAlgorithm =
      +            new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation);
      +    }
      +
      +    private static Element reparseSignedInfoElem(Element element)
      +        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.
                */
      -        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
      -        String c14nMethodURI = this.getCanonicalizationMethodURI();
      +        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))) {
      -            // the c14n is not a secure one and can rewrite the URIs or like
      -            // that reparse the SignedInfo to be sure
      +            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(this.getCanonicalizationMethodURI());
      +                    Canonicalizer.getInstance(c14nMethodURI);
       
      -                this._c14nizedBytes =
      -                    c14nizer.canonicalizeSubtree(this._constructionElement);
      +                byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
                       javax.xml.parsers.DocumentBuilderFactory dbf =
                           javax.xml.parsers.DocumentBuilderFactory.newInstance();
                       dbf.setNamespaceAware(true);
      -                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
      -                               Boolean.TRUE);
      -                javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
      +                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
      +                javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();        
                       Document newdoc =
      -                    db.parse(new ByteArrayInputStream(this._c14nizedBytes));
      -                Node imported =
      -                    this._doc.importNode(newdoc.getDocumentElement(), true);
      +                    db.parse(new ByteArrayInputStream(c14nizedBytes));
      +                Node imported = 
      +                    element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
       
      -                this._constructionElement.getParentNode().replaceChild(imported,
      -                    this._constructionElement);
      +                element.getParentNode().replaceChild(imported, element);
       
      -                this._constructionElement = (Element) imported;
      +                return (Element) imported;
                   } catch (ParserConfigurationException ex) {
                       throw new XMLSecurityException("empty", ex);
                   } catch (IOException ex) {
      @@ -207,184 +235,163 @@
                       throw new XMLSecurityException("empty", ex);
                   }
               }
      -        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
      -        this._signatureAlgorithm =
      -            new SignatureAlgorithm(signatureMethod, this.getBaseURI());
      +        return element;
           }
       
      -   /**
      -    * Tests core validation process
      -    *
      -    * @return true if verification was successful
      -    * @throws MissingResourceFailureException
      -    * @throws XMLSecurityException
      -    */
      -   public boolean verify()
      -           throws MissingResourceFailureException, XMLSecurityException {
      -      return super.verifyReferences(false);
      -   }
      -
      -   /**
      -    * Tests core validation process
      -    *
      -    * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, too
      -    * @return true if verification was successful
      -    * @throws MissingResourceFailureException
      -    * @throws XMLSecurityException
      -    */
      -   public boolean verify(boolean followManifests)
      -           throws MissingResourceFailureException, XMLSecurityException {
      -      return super.verifyReferences(followManifests);
      -   }
      -
      -   /**
      -    * Returns getCanonicalizedOctetStream
      -    *
      -    * @return the canonicalization result octedt stream of SignedInfo element
      -    * @throws CanonicalizationException
      -    * @throws InvalidCanonicalizerException
      -    * @throws XMLSecurityException
      -    */
      -   public byte[] getCanonicalizedOctetStream()
      -           throws CanonicalizationException, InvalidCanonicalizerException,
      -                 XMLSecurityException {
      -
      -      if ((this._c14nizedBytes == null)
      -              /*&& (this._state == ElementProxy.MODE_SIGN)*/) {
      -         Canonicalizer c14nizer =
      -            Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
      -
      -         this._c14nizedBytes =
      -            c14nizer.canonicalizeSubtree(this._constructionElement);
      -      }
      -
      -      // make defensive copy
      -      byte[] output = new byte[this._c14nizedBytes.length];
      -
      -      System.arraycopy(this._c14nizedBytes, 0, output, 0, output.length);
      -
      -      return output;
      -   }
      -
      -   /**
      -    *  Output the C14n stream to the give outputstream.
      -    * @param os
      -    * @throws CanonicalizationException
      -    * @throws InvalidCanonicalizerException
      -    * @throws XMLSecurityException
      -    */
      -   public void signInOctectStream(OutputStream os)
      -       throws CanonicalizationException, InvalidCanonicalizerException,
      -           XMLSecurityException {
      -
      -        if ((this._c14nizedBytes == null)) {
      -       Canonicalizer c14nizer =
      -          Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
      -       c14nizer.setWriter(os);
      -       String inclusiveNamespaces = this.getInclusiveNamespaces();
      -
      -       if(inclusiveNamespaces == null)
      -        c14nizer.canonicalizeSubtree(this._constructionElement);
      -       else
      -        c14nizer.canonicalizeSubtree(this._constructionElement, inclusiveNamespaces);
      -    } else {
      -        try {
      -                        os.write(this._c14nizedBytes);
      -                } catch (IOException e) {
      -                        throw new RuntimeException(""+e);
      -                }
      -    }
      -   }
      -
      -   /**
      -    * Returns the Canonicalization method URI
      -    *
      -    * @return the Canonicalization method URI
      -    */
      -   public String getCanonicalizationMethodURI() {
      -
      -
      -     return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
      -   }
      -
      -   /**
      -    * Returns the Signature method URI
      -    *
      -    * @return the Signature method URI
      -    */
      -   public String getSignatureMethodURI() {
      -
      -      Element signatureElement = this.getSignatureMethodElement();
      -
      -      if (signatureElement != null) {
      -         return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
      -      }
      -
      -      return null;
      -   }
      -
      -   /**
      -    * Method getSignatureMethodElement
      -    * @return gets The SignatureMethod Node.
      -    *
      -    */
      -   public Element getSignatureMethodElement() {
      -           return signatureMethod;
      -   }
      -
      -   /**
      -    * Creates a SecretKey for the appropriate Mac algorithm based on a
      -    * byte[] array password.
      -    *
      -    * @param secretKeyBytes
      -    * @return the secret key for the SignedInfo element.
      -    */
      -   public SecretKey createSecretKey(byte[] secretKeyBytes)
      -   {
      -
      -      return new SecretKeySpec(secretKeyBytes,
      -                               this._signatureAlgorithm
      -                                  .getJCEAlgorithmString());
      -   }
      -
      -   protected SignatureAlgorithm getSignatureAlgorithm() {
      -           return _signatureAlgorithm;
      -   }
      -   /**
      -    * Method getBaseLocalName
      -    * @inheritDoc
      -    *
      -    */
      -   public String getBaseLocalName() {
      -      return Constants._TAG_SIGNEDINFO;
      -   }
      -
      -   public String getInclusiveNamespaces() {
      -
      -
      -
      -     String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
      -     if(!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
      -                        c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
      -                return null;
      +    /**
      +     * Tests core validation process
      +     *
      +     * @return true if verification was successful
      +     * @throws MissingResourceFailureException
      +     * @throws XMLSecurityException
      +     */
      +    public boolean verify()
      +        throws MissingResourceFailureException, XMLSecurityException {
      +        return super.verifyReferences(false);
      +    }
      +
      +    /**
      +     * Tests core validation process
      +     *
      +     * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, too
      +     * @return true if verification was successful
      +     * @throws MissingResourceFailureException
      +     * @throws XMLSecurityException
      +     */
      +    public boolean verify(boolean followManifests)
      +        throws MissingResourceFailureException, XMLSecurityException {
      +        return super.verifyReferences(followManifests);
      +    }
      +
      +    /**
      +     * Returns getCanonicalizedOctetStream
      +     *
      +     * @return the canonicalization result octet stream of SignedInfo element
      +     * @throws CanonicalizationException
      +     * @throws InvalidCanonicalizerException
      +     * @throws XMLSecurityException
      +     */
      +    public byte[] getCanonicalizedOctetStream()
      +        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
      +        if (this.c14nizedBytes == null) {
      +            Canonicalizer c14nizer =
      +                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
      +
      +            this.c14nizedBytes =
      +                c14nizer.canonicalizeSubtree(this.constructionElement);
      +        }
      +
      +        // make defensive copy
      +        return this.c14nizedBytes.clone();
      +    }
      +
      +    /**
      +     * Output the C14n stream to the given OutputStream.
      +     * @param os
      +     * @throws CanonicalizationException
      +     * @throws InvalidCanonicalizerException
      +     * @throws XMLSecurityException
      +     */
      +    public void signInOctetStream(OutputStream os)            
      +        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
      +        if (this.c14nizedBytes == null) {
      +            Canonicalizer c14nizer =
      +                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
      +            c14nizer.setWriter(os);
      +            String inclusiveNamespaces = this.getInclusiveNamespaces();
      +
      +            if (inclusiveNamespaces == null) {
      +                c14nizer.canonicalizeSubtree(this.constructionElement);
      +            } else {
      +                c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
                   }
      +        } else {
      +            try {
      +                os.write(this.c14nizedBytes);
      +            } catch (IOException e) {
      +                throw new RuntimeException(e);
      +            }  
      +        }    
      +    }
      +
      +    /**
      +     * Returns the Canonicalization method URI
      +     *
      +     * @return the Canonicalization method URI
      +     */
      +    public String getCanonicalizationMethodURI() {
      +        return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);    
      +    }
      +
      +    /**
      +     * Returns the Signature method URI
      +     *
      +     * @return the Signature method URI
      +     */
      +    public String getSignatureMethodURI() {
      +        Element signatureElement = this.getSignatureMethodElement();
      +
      +        if (signatureElement != null) {
      +            return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
      +        }
      +
      +        return null;
      +    }
      +
      +    /**
      +     * Method getSignatureMethodElement
      +     * @return returns the SignatureMethod Element   
      +     *
      +     */
      +    public Element getSignatureMethodElement() {
      +        return signatureMethod;
      +    }
      +
      +    /**
      +     * Creates a SecretKey for the appropriate Mac algorithm based on a
      +     * byte[] array password.
      +     *
      +     * @param secretKeyBytes
      +     * @return the secret key for the SignedInfo element.
      +     */
      +    public SecretKey createSecretKey(byte[] secretKeyBytes) {
      +        return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
      +    }
      +
      +    protected SignatureAlgorithm getSignatureAlgorithm() {
      +        return signatureAlgorithm;
      +    }
       
      -     Element inclusiveElement = XMLUtils.getNextElement(
      -                 c14nMethod.getFirstChild());
      +    /**
      +     * Method getBaseLocalName
      +     * @inheritDoc
      +     *
      +     */
      +    public String getBaseLocalName() {
      +        return Constants._TAG_SIGNEDINFO;
      +    }
      +
      +    public String getInclusiveNamespaces() {
      +        String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
      +        if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
      +            c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
      +            return null;
      +        }
       
      -     if(inclusiveElement != null)
      -     {
      -         try
      -         {
      -             String inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
      -                         InclusiveNamespaces.ExclusiveCanonicalizationNamespace).getInclusiveNamespaces();
      -             return inclusiveNamespaces;
      -         }
      -         catch (XMLSecurityException e)
      -         {
      -             return null;
      -         }
      -     }
      -     return null;
      +        Element inclusiveElement = XMLUtils.getNextElement(c14nMethod.getFirstChild());
      +
      +        if (inclusiveElement != null) {
      +            try {
      +                String inclusiveNamespaces = 
      +                    new InclusiveNamespaces(
      +                        inclusiveElement,
      +                        InclusiveNamespaces.ExclusiveCanonicalizationNamespace
      +                    ).getInclusiveNamespaces();
      +                return inclusiveNamespaces;
      +            } catch (XMLSecurityException e) {
      +                return null;
      +            }
      +        }
      +        return null;
           }
       }
      --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	2013-06-28 11:34:02.897515755 -0400
      +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java	2013-06-28 11:34:02.725521105 -0400
      @@ -2,26 +2,26 @@
        * reserved comment block
        * DO NOT REMOVE OR ALTER!
        */
      -/*
      - * Copyright  1999-2004 The Apache Software Foundation.
      - *
      - *  Licensed 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
      +/**
      + * 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
        *
      - *  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.
      + * http://www.apache.org/licenses/LICENSE-2.0
        *
      + * Unless required by applicable law or agreed to in writing,
      + * software distributed under the License is distributed on an
      + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      + * KIND, either express or implied. See the License for the
      + * specific language governing permissions and limitations
      + * under the License.
        */
       package com.sun.org.apache.xml.internal.security.signature;
       
      -
      -
       import java.io.IOException;
       import java.io.OutputStream;
       import java.security.Key;
      @@ -42,7 +42,6 @@
       import com.sun.org.apache.xml.internal.security.utils.Base64;
       import com.sun.org.apache.xml.internal.security.utils.Constants;
       import com.sun.org.apache.xml.internal.security.utils.I18n;
      -import com.sun.org.apache.xml.internal.security.utils.IdResolver;
       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;
      @@ -56,7 +55,6 @@
       import org.w3c.dom.NodeList;
       import org.w3c.dom.Text;
       
      -
       /**
        * Handles <ds:Signature> elements.
        * This is the main class that deals with creating and verifying signatures.
      @@ -64,7 +62,7 @@
        * 

      There are 2 types of constructors for this class. The ones that take a * document, baseURI and 1 or more Java Objects. This is mostly used for * signing purposes. - * The other constructor is the one that takes a DOM Element and a BaseURI. + * The other constructor is the one that takes a DOM Element and a baseURI. * This is used mostly with for verifying, when you have a SignatureElement. * * There are a few different types of methods: @@ -76,329 +74,391 @@ * ObjectContainer during signing. *

    • sign and checkSignatureValue methods are used to sign and validate the * signature.
    • - * - * @author $Author: mullan $ */ public final class XMLSignature extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** MAC - Required HMAC-SHA1 */ + public static final String ALGO_ID_MAC_HMAC_SHA1 = + Constants.SignatureSpecNS + "hmac-sha1"; + + /** Signature - Required DSAwithSHA1 (DSS) */ + public static final String ALGO_ID_SIGNATURE_DSA = + Constants.SignatureSpecNS + "dsa-sha1"; + + /** Signature - Recommended RSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_RSA = + Constants.SignatureSpecNS + "rsa-sha1"; + + /** Signature - Recommended RSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = + Constants.SignatureSpecNS + "rsa-sha1"; + + /** Signature - NOT Recommended RSAwithMD5 */ + public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = + Constants.MoreAlgorithmsSpecNS + "rsa-md5"; + + /** Signature - Optional RSAwithRIPEMD160 */ + public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = + Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160"; + + /** Signature - Optional RSAwithSHA256 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha256"; + + /** Signature - Optional RSAwithSHA384 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha384"; + + /** Signature - Optional RSAwithSHA512 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha512"; + + /** HMAC - NOT Recommended HMAC-MD5 */ + public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = + Constants.MoreAlgorithmsSpecNS + "hmac-md5"; + + /** HMAC - Optional HMAC-RIPEMD160 */ + public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = + Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160"; + + /** HMAC - Optional HMAC-SHA256 */ + public static final String ALGO_ID_MAC_HMAC_SHA256 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha256"; + + /** HMAC - Optional HMAC-SHA284 */ + public static final String ALGO_ID_MAC_HMAC_SHA384 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha384"; + + /** HMAC - Optional HMAC-SHA512 */ + public static final String ALGO_ID_MAC_HMAC_SHA512 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha512"; + + /**Signature - Optional ECDSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + + /**Signature - Optional ECDSAwithSHA256 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"; + + /**Signature - Optional ECDSAwithSHA384 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; + + /**Signature - Optional ECDSAwithSHA512 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLSignature.class.getName()); + + /** ds:Signature.ds:SignedInfo element */ + private SignedInfo signedInfo; + + /** ds:Signature.ds:KeyInfo */ + private KeyInfo keyInfo; + + /** + * Checking the digests in References in a Signature are mandatory, but for + * References inside a Manifest it is application specific. This boolean is + * to indicate that the References inside Manifests should be validated. + */ + private boolean followManifestsDuringValidation = false; + + private Element signatureValueElement; - //J- - /** MAC - Required HMAC-SHA1 */ - public static final String ALGO_ID_MAC_HMAC_SHA1 = Constants.SignatureSpecNS + "hmac-sha1"; - - /** Signature - Required DSAwithSHA1 (DSS) */ - public static final String ALGO_ID_SIGNATURE_DSA = Constants.SignatureSpecNS + "dsa-sha1"; - - /** Signature - Recommended RSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_RSA = Constants.SignatureSpecNS + "rsa-sha1"; - /** Signature - Recommended RSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = Constants.SignatureSpecNS + "rsa-sha1"; - /** Signature - NOT Recommended RSAwithMD5 */ - public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = Constants.MoreAlgorithmsSpecNS + "rsa-md5"; - /** Signature - Optional RSAwithRIPEMD160 */ - public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160"; - /** Signature - Optional RSAwithSHA256 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = Constants.MoreAlgorithmsSpecNS + "rsa-sha256"; - /** Signature - Optional RSAwithSHA384 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = Constants.MoreAlgorithmsSpecNS + "rsa-sha384"; - /** Signature - Optional RSAwithSHA512 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = Constants.MoreAlgorithmsSpecNS + "rsa-sha512"; - - /** HMAC - NOT Recommended HMAC-MD5 */ - public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5"; - /** HMAC - Optional HMAC-RIPEMD160 */ - public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160"; - /** HMAC - Optional HMAC-SHA256 */ - public static final String ALGO_ID_MAC_HMAC_SHA256 = Constants.MoreAlgorithmsSpecNS + "hmac-sha256"; - /** HMAC - Optional HMAC-SHA284 */ - public static final String ALGO_ID_MAC_HMAC_SHA384 = Constants.MoreAlgorithmsSpecNS + "hmac-sha384"; - /** HMAC - Optional HMAC-SHA512 */ - public static final String ALGO_ID_MAC_HMAC_SHA512 = Constants.MoreAlgorithmsSpecNS + "hmac-sha512"; - /**Signature - Optional ECDSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; - - - //J+ - - /** ds:Signature.ds:SignedInfo element */ - private SignedInfo _signedInfo = null; - - /** ds:Signature.ds:KeyInfo */ - private KeyInfo _keyInfo = null; - - /** - * Checking the digests in References in a Signature are mandatory, but for - * References inside a Manifest it is application specific. This boolean is - * to indicate that the References inside Manifests should be validated. - */ - private boolean _followManifestsDuringValidation = false; - -private Element signatureValueElement; - - /** - * This creates a new ds:Signature Element and adds an empty - * ds:SignedInfo. - * The 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. - * @throws XMLSecurityException - */ - public XMLSignature(Document doc, String BaseURI, String SignatureMethodURI) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, 0, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); - } - - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI the Signature method to be used. - * @param HMACOutputLength - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, HMACOutputLength, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); - } - - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @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( - Document doc, String BaseURI, String SignatureMethodURI, String CanonicalizationMethodURI) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, 0, CanonicalizationMethodURI); - } - - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI - * @param HMACOutputLength - * @param CanonicalizationMethodURI - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength, String CanonicalizationMethodURI) - throws XMLSecurityException { - - super(doc); - - String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); - if (xmlnsDsPrefix == null) { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); - } else { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS); - } - XMLUtils.addReturnToElement(this._constructionElement); - - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodURI, - HMACOutputLength, - CanonicalizationMethodURI); - - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); - - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } - /** - * Creates a XMLSignature in a Document - * @param doc - * @param BaseURI - * @param SignatureMethodElem - * @param CanonicalizationMethodElem - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, Element SignatureMethodElem, Element CanonicalizationMethodElem) - throws XMLSecurityException { - - super(doc); - - String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); - if (xmlnsDsPrefix == null) { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); - } else { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS); - } - XMLUtils.addReturnToElement(this._constructionElement); - - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodElem, CanonicalizationMethodElem); - - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); - - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * 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 - * @throws XMLSecurityException - * @throws XMLSignatureException if the signature is badly formatted - */ - public XMLSignature(Element element, String BaseURI) - throws XMLSignatureException, XMLSecurityException { - - super(element, BaseURI); - - // check out SignedInfo child - Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());// XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - //Constants._TAG_SIGNEDINFO,0); - - // check to see if it is there - if (signedInfoElem == null) { - 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); - - // check out SignatureValue child - this.signatureValueElement =XMLUtils.getNextElement(signedInfoElem.getNextSibling()); //XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_SIGNATUREVALUE,0); - - // check to see if it exists - if (signatureValueElement == null) { - Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, - Constants._TAG_SIGNATURE }; - - throw new XMLSignatureException("xml.WrongContent", exArgs); - } - Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); - if (signatureValueAttr != null) { - signatureValueElement.setIdAttributeNode(signatureValueAttr, true); - } - - // - Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_KEYINFO,0); - - // If it exists use it, but it's not mandatory - if ((keyInfoElem != null) && (keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) && - keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) ) { - this._keyInfo = new KeyInfo(keyInfoElem, BaseURI); - } - - // - Element objectElem = - XMLUtils.getNextElement(signatureValueElement.getNextSibling()); - while (objectElem != null) { - Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); - if (objectAttr != null) { - objectElem.setIdAttributeNode(objectAttr, true); - } - - NodeList nodes = objectElem.getChildNodes(); - int length = nodes.getLength(); - // Register Ids of the Object child elements - for (int i = 0; i < length; i++) { - Node child = nodes.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element)child; - String tag = childElem.getLocalName(); - if (tag.equals("Manifest")) { - new Manifest(childElem, BaseURI); - } else if (tag.equals("SignatureProperties")) { - new SignatureProperties(childElem, BaseURI); - } - } - } - - objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); - } - } - - /** - * Sets the Id attribute - * - * @param Id Id value to be used by the id attribute on the Signature Element - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Returns the completely parsed SignedInfo object. - * - * @return the completely parsed SignedInfo object. - */ - public SignedInfo getSignedInfo() { - return this._signedInfo; - } - - /** - * Returns the octet value of the SignatureValue element. - * Throws an XMLSignatureException if it has no or wrong content. - * - * @return the value of the SignatureValue element. - * @throws XMLSignatureException If there is no content - */ - public byte[] getSignatureValue() throws XMLSignatureException { - - try { - byte[] signatureValue = Base64.decode(signatureValueElement); - - return signatureValue; - } catch (Base64DecodingException ex) { - throw new XMLSignatureException("empty", ex); - } - } + private static final int MODE_SIGN = 0; + private static final int MODE_VERIFY = 1; + private int state = MODE_SIGN; + + /** + * This creates a new ds:Signature Element and adds an empty + * ds:SignedInfo. + * The 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. + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI) + throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); + } + + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI the Signature method to be used. + * @param hmacOutputLength + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI, + int hmacOutputLength) throws XMLSecurityException { + this( + doc, baseURI, signatureMethodURI, hmacOutputLength, + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS + ); + } + + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @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( + Document doc, + String baseURI, + String signatureMethodURI, + String canonicalizationMethodURI + ) throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI); + } + + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI + * @param hmacOutputLength + * @param canonicalizationMethodURI + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + int hmacOutputLength, + String canonicalizationMethodURI + ) throws XMLSecurityException { + super(doc); + + String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); + if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS + ); + } else { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS + ); + } + XMLUtils.addReturnToElement(this.constructionElement); + + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo( + this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI + ); + + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); + + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Creates a XMLSignature in a Document + * @param doc + * @param baseURI + * @param SignatureMethodElem + * @param CanonicalizationMethodElem + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + Element SignatureMethodElem, + Element CanonicalizationMethodElem + ) throws XMLSecurityException { + super(doc); + + String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); + if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS + ); + } else { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS + ); + } + XMLUtils.addReturnToElement(this.constructionElement); + + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem); + + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); + + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * 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 + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI) + throws XMLSignatureException, XMLSecurityException { + this(element, baseURI, false); + } + + /** + * 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 + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI, boolean secureValidation) + throws XMLSignatureException, XMLSecurityException { + super(element, baseURI); + + // 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 }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } + + // create a SignedInfo object from that element + this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation); + // get signedInfoElem again in case it has changed + signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); + + // check out SignatureValue child + this.signatureValueElement = + XMLUtils.getNextElement(signedInfoElem.getNextSibling()); + + // check to see if it exists + if (signatureValueElement == null) { + Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } + Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); + if (signatureValueAttr != null) { + signatureValueElement.setIdAttributeNode(signatureValueAttr, true); + } + + // + Element keyInfoElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); + + // If it exists use it, but it's not mandatory + if (keyInfoElem != null + && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) + && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) { + this.keyInfo = new KeyInfo(keyInfoElem, baseURI); + this.keyInfo.setSecureValidation(secureValidation); + } + + // + Element objectElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); + while (objectElem != null) { + Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); + if (objectAttr != null) { + objectElem.setIdAttributeNode(objectAttr, true); + } + + NodeList nodes = objectElem.getChildNodes(); + int length = nodes.getLength(); + // Register Ids of the Object child elements + for (int i = 0; i < length; i++) { + Node child = nodes.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + Element childElem = (Element)child; + String tag = childElem.getLocalName(); + if (tag.equals("Manifest")) { + new Manifest(childElem, baseURI); + } else if (tag.equals("SignatureProperties")) { + new SignatureProperties(childElem, baseURI); + } + } + } + + objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); + } + + this.state = MODE_VERIFY; + } + + /** + * Sets the Id attribute + * + * @param id Id value for the id attribute on the Signature Element + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** + * Returns the completely parsed SignedInfo object. + * + * @return the completely parsed SignedInfo object. + */ + public SignedInfo getSignedInfo() { + return this.signedInfo; + } + + /** + * Returns the octet value of the SignatureValue element. + * Throws an XMLSignatureException if it has no or wrong content. + * + * @return the value of the SignatureValue element. + * @throws XMLSignatureException If there is no content + */ + public byte[] getSignatureValue() throws XMLSignatureException { + try { + return Base64.decode(signatureValueElement); + } catch (Base64DecodingException ex) { + throw new XMLSignatureException("empty", ex); + } + } /** * Base64 encodes and sets the bytes as the content of the SignatureValue @@ -409,8 +469,7 @@ private void setSignatureValueElement(byte[] bytes) { while (signatureValueElement.hasChildNodes()) { - signatureValueElement.removeChild - (signatureValueElement.getFirstChild()); + signatureValueElement.removeChild(signatureValueElement.getFirstChild()); } String base64codedValue = Base64.encode(bytes); @@ -419,373 +478,393 @@ base64codedValue = "\n" + base64codedValue + "\n"; } - Text t = this._doc.createTextNode(base64codedValue); + Text t = this.doc.createTextNode(base64codedValue); signatureValueElement.appendChild(t); } - /** - * Returns the KeyInfo child. If we are in signing mode and the KeyInfo - * does not exist yet, it is created on demand and added to the Signature. - *
      - * This allows to add arbitrary content to the KeyInfo during signing. - * - * @return the KeyInfo object - */ - public KeyInfo getKeyInfo() { - - // check to see if we are signing and if we have to create a keyinfo - if ( (this._keyInfo == null)) { - - // create the KeyInfo - this._keyInfo = new KeyInfo(this._doc); - - // get the Element from KeyInfo - Element keyInfoElement = this._keyInfo.getElement(); - Element firstObject=null; - Node sibling= this._constructionElement.getFirstChild(); - firstObject = XMLUtils.selectDsNode(sibling,Constants._TAG_OBJECT,0); + /** + * Returns the KeyInfo child. If we are in signing mode and the KeyInfo + * does not exist yet, it is created on demand and added to the Signature. + *
      + * This allows to add arbitrary content to the KeyInfo during signing. + * + * @return the KeyInfo object + */ + public KeyInfo getKeyInfo() { + // check to see if we are signing and if we have to create a keyinfo + if (this.state == MODE_SIGN && this.keyInfo == null) { + + // create the KeyInfo + this.keyInfo = new KeyInfo(this.doc); + + // get the Element from KeyInfo + Element keyInfoElement = this.keyInfo.getElement(); + Element firstObject = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, 0 + ); if (firstObject != null) { - - // add it before the object - this._constructionElement.insertBefore(keyInfoElement, - firstObject); - XMLUtils.addReturnBeforeChild(this._constructionElement, firstObject); + // add it before the object + this.constructionElement.insertBefore(keyInfoElement, firstObject); + XMLUtils.addReturnBeforeChild(this.constructionElement, firstObject); } else { + // add it as the last element to the signature + this.constructionElement.appendChild(keyInfoElement); + XMLUtils.addReturnToElement(this.constructionElement); + } + } - // add it as the last element to the signature - this._constructionElement.appendChild(keyInfoElement); - XMLUtils.addReturnToElement(this._constructionElement); - } - } - - return this._keyInfo; - } + return this.keyInfo; + } - /** - * Appends an Object (not a java.lang.Object but an Object - * element) to the Signature. Please note that this is only possible - * when signing. - * - * @param object ds:Object to be appended. - * @throws XMLSignatureException When this object is used to verify. - */ - public void appendObject(ObjectContainer object) - throws XMLSignatureException { - - //try { - //if (this._state != MODE_SIGN) { - // throw new XMLSignatureException( - // "signature.operationOnlyBeforeSign"); - //} - - this._constructionElement.appendChild(object.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - //} catch (XMLSecurityException ex) { + /** + * Appends an Object (not a java.lang.Object but an Object + * element) to the Signature. Please note that this is only possible + * when signing. + * + * @param object ds:Object to be appended. + * @throws XMLSignatureException When this object is used to verify. + */ + public void appendObject(ObjectContainer object) throws XMLSignatureException { + //try { + //if (this.state != MODE_SIGN) { + // throw new XMLSignatureException( + // "signature.operationOnlyBeforeSign"); + //} + + this.constructionElement.appendChild(object.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + //} catch (XMLSecurityException ex) { // throw new XMLSignatureException("empty", ex); - //} - } + //} + } + + /** + * Returns the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + * + * @param i + * @return the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + */ + public ObjectContainer getObjectItem(int i) { + Element objElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i + ); + + try { + return new ObjectContainer(objElem, this.baseURI); + } catch (XMLSecurityException ex) { + return null; + } + } + + /** + * Returns the number of all ds:Object elements. + * + * @return the number of all ds:Object elements. + */ + public int getObjectLength() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); + } + + /** + * Digests all References in the SignedInfo, calculates the signature value + * and sets it in the SignatureValue Element. + * + * @param signingKey the {@link java.security.PrivateKey} or + * {@link javax.crypto.SecretKey} that is used to sign. + * @throws XMLSignatureException + */ + public void sign(Key signingKey) throws XMLSignatureException { - /** - * Returns the ith ds:Object child of the signature - * or null if no such ds:Object element exists. - * - * @param i - * @return the ith ds:Object child of the signature or null if no such ds:Object element exists. - */ - public ObjectContainer getObjectItem(int i) { - - Element objElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_OBJECT,i); - - try { - return new ObjectContainer(objElem, this._baseURI); - } catch (XMLSecurityException ex) { - return null; - } - } - - /** - * Returns the number of all ds:Object elements. - * - * @return the number of all ds:Object elements. - */ - public int getObjectLength() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); - } - - /** - * Digests all References in the SignedInfo, calculates the signature value and - * sets it in the SignatureValue Element. - * - * @param signingKey the {@link java.security.PrivateKey} or {@link javax.crypto.SecretKey} that is used to sign. - * @throws XMLSignatureException - */ - public void sign(Key signingKey) throws XMLSignatureException { - - if (signingKey instanceof PublicKey) { - throw new IllegalArgumentException(I18n - .translate("algorithms.operationOnlyVerification")); - } + if (signingKey instanceof PublicKey) { + throw new IllegalArgumentException( + I18n.translate("algorithms.operationOnlyVerification") + ); + } - try { - // if (this._state == MODE_SIGN) { + try { //Create a SignatureAlgorithm object - SignedInfo si = this.getSignedInfo(); + SignedInfo si = this.getSignedInfo(); SignatureAlgorithm sa = si.getSignatureAlgorithm(); - // initialize SignatureAlgorithm for signing - sa.initSign(signingKey); - - // generate digest values for all References in this SignedInfo - si.generateDigestValues(); - OutputStream so=new UnsyncBufferedOutputStream(new SignerOutputStream(sa)); + OutputStream so = null; try { - so.close(); - } catch (IOException e) { - //Imposible + // initialize SignatureAlgorithm for signing + sa.initSign(signingKey); + + // generate digest values for all References in this SignedInfo + si.generateDigestValues(); + so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa)); + // get the canonicalized bytes from SignedInfo + si.signInOctetStream(so); + } catch (XMLSecurityException ex) { + throw ex; + } finally { + if (so != null) { + try { + so.close(); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } } - // get the canonicalized bytes from SignedInfo - si.signInOctectStream(so); - byte jcebytes[] = sa.sign(); + // set them on the SignatureValue element + this.setSignatureValueElement(sa.sign()); + } catch (XMLSignatureException ex) { + throw ex; + } catch (CanonicalizationException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new XMLSignatureException("empty", ex); + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", 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. + * + * @param resolver + */ + public void addResourceResolver(ResourceResolverSpi resolver) { + this.getSignedInfo().addResourceResolver(resolver); + } + + /** + * Extracts the public key from the certificate and verifies if the signature + * is valid by re-digesting all References, comparing those against the + * stored DigestValues and then checking to see if the Signatures match on + * the SignedInfo. + * + * @param cert Certificate that contains the public key part of the keypair + * that was used to sign. + * @return true if the signature is valid, false otherwise + * @throws XMLSignatureException + */ + public boolean checkSignatureValue(X509Certificate cert) + throws XMLSignatureException { + // see if cert is null + if (cert != null) { + // check the values with the public key from the cert + return this.checkSignatureValue(cert.getPublicKey()); + } + + Object exArgs[] = { "Didn't get a certificate" }; + throw new XMLSignatureException("empty", exArgs); + } - // set them on the SignateValue element - this.setSignatureValueElement(jcebytes); - //} - } catch (CanonicalizationException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException("empty", ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", 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. - * - * @param resolver - */ - public void addResourceResolver(ResourceResolverSpi resolver) { - this.getSignedInfo().addResourceResolver(resolver); - } - - /** - * Extracts the public key from the certificate and verifies if the signature - * is valid by re-digesting all References, comparing those against the - * stored DigestValues and then checking to see if the Signatures match on - * the SignedInfo. - * - * @param cert Certificate that contains the public key part of the keypair that was used to sign. - * @return true if the signature is valid, false otherwise - * @throws XMLSignatureException - */ - public boolean checkSignatureValue(X509Certificate cert) - throws XMLSignatureException { - - // see if cert is null - if (cert != null) { - - //check the values with the public key from the cert - return this.checkSignatureValue(cert.getPublicKey()); - } - - Object exArgs[] = { "Didn't get a certificate" }; - throw new XMLSignatureException("empty", exArgs); - - } - - /** - * Verifies if the signature is valid by redigesting all References, - * comparing those against the stored DigestValues and then checking to see - * if the Signatures match on the SignedInfo. - * - * @param pk {@link java.security.PublicKey} part of the keypair or {@link javax.crypto.SecretKey} that was used to sign - * @return true if the signature is valid, false otherwise - * @throws XMLSignatureException - */ - public boolean checkSignatureValue(Key pk) throws XMLSignatureException { - - //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" }; - - throw new XMLSignatureException("empty", exArgs); - } - // all references inside the signedinfo need to be dereferenced and - // digested again to see if the outcome matches the stored value in the - // SignedInfo. - // If _followManifestsDuringValidation is true it will do the same for - // References inside a Manifest. - try { - SignedInfo si=this.getSignedInfo(); - //create a SignatureAlgorithms from the SignatureMethod inside - //SignedInfo. This is used to validate the signature. - SignatureAlgorithm sa =si.getSignatureAlgorithm(); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "SignatureMethodURI = " + sa.getAlgorithmURI()); + /** + * Verifies if the signature is valid by redigesting all References, + * comparing those against the stored DigestValues and then checking to see + * if the Signatures match on the SignedInfo. + * + * @param pk {@link java.security.PublicKey} part of the keypair or + * {@link javax.crypto.SecretKey} that was used to sign + * @return true if the signature is valid, false otherwise + * @throws XMLSignatureException + */ + public boolean checkSignatureValue(Key pk) throws XMLSignatureException { + //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" }; + throw new XMLSignatureException("empty", exArgs); + } + // all references inside the signedinfo need to be dereferenced and + // digested again to see if the outcome matches the stored value in the + // SignedInfo. + // If followManifestsDuringValidation is true it will do the same for + // References inside a Manifest. + try { + SignedInfo si = this.getSignedInfo(); + //create a SignatureAlgorithms from the SignatureMethod inside + //SignedInfo. This is used to validate the signature. + SignatureAlgorithm sa = si.getSignatureAlgorithm(); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI()); log.log(java.util.logging.Level.FINE, "jceSigAlgorithm = " + sa.getJCEAlgorithmString()); log.log(java.util.logging.Level.FINE, "jceSigProvider = " + sa.getJCEProviderName()); log.log(java.util.logging.Level.FINE, "PublicKey = " + pk); - } - sa.initVerify(pk); + } + byte sigBytes[] = null; + try { + sa.initVerify(pk); + + // Get the canonicalized (normalized) SignedInfo + SignerOutputStream so = new SignerOutputStream(sa); + OutputStream bos = new UnsyncBufferedOutputStream(so); - // Get the canonicalized (normalized) SignedInfo - SignerOutputStream so=new SignerOutputStream(sa); - OutputStream bos=new UnsyncBufferedOutputStream(so); - si.signInOctectStream(bos); - try { + si.signInOctetStream(bos); bos.close(); - } catch (IOException e) { - //Imposible - } - - //retrieve the byte[] from the stored signature - byte sigBytes[] = this.getSignatureValue(); - - //Have SignatureAlgorithm sign the input bytes and compare them to the - //bytes that were stored in the signature. - if (!sa.verify(sigBytes)) { - log.log(java.util.logging.Level.WARNING, "Signature verification failed."); - return false; - } - - return si.verify(this._followManifestsDuringValidation); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Add a Reference with full parameters to this Signature - * - * @param referenceURI URI of the resource to be signed. Can be null in which - * case the dereferencing is application specific. Can be "" in which it's - * the parent node (or parent document?). There can only be one "" in each - * signature. - * @param trans Optional list of transformations to be done before digesting - * @param digestURI Mandatory URI of the digesting algorithm to use. - * @param ReferenceId Optional id attribute for this Reference - * @param ReferenceType Optional mimetype for the URI - * @throws XMLSignatureException - */ - public void addDocument( - String referenceURI, Transforms trans, String digestURI, String ReferenceId, String ReferenceType) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - digestURI, ReferenceId, ReferenceType); - } - - /** - * This method is a proxy method for the {@link Manifest#addDocument} method. - * - * @param referenceURI URI according to the XML Signature specification. - * @param trans List of transformations to be applied. - * @param digestURI URI of the digest algorithm to be used. - * @see Manifest#addDocument - * @throws XMLSignatureException - */ - public void addDocument( - String referenceURI, Transforms trans, String digestURI) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - digestURI, null, null); - } - - /** - * Adds a Reference with just the URI and the transforms. This used the - * SHA1 algorithm as a default digest algorithm. - * - * @param referenceURI URI according to the XML Signature specification. - * @param trans List of transformations to be applied. - * @throws XMLSignatureException - */ - public void addDocument(String referenceURI, Transforms trans) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - Constants.ALGO_ID_DIGEST_SHA1, null, null); - } - - /** - * Add a Reference with just this URI. It uses SHA1 by default as the digest - * algorithm - * - * @param referenceURI URI according to the XML Signature specification. - * @throws XMLSignatureException - */ - public void addDocument(String referenceURI) throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, null, - Constants.ALGO_ID_DIGEST_SHA1, null, null); - } - - /** - * Add an X509 Certificate to the KeyInfo. This will include the whole cert - * inside X509Data/X509Certificate tags. - * - * @param cert Certificate to be included. This should be the certificate of the key that was used to sign. - * @throws XMLSecurityException - */ - public void addKeyInfo(X509Certificate cert) throws XMLSecurityException { - - X509Data x509data = new X509Data(this._doc); - - x509data.addCertificate(cert); - this.getKeyInfo().add(x509data); - } - - /** - * Add this public key to the KeyInfo. This will include the complete key in - * the KeyInfo structure. - * - * @param pk - */ - public void addKeyInfo(PublicKey pk) { - this.getKeyInfo().add(pk); - } - - /** - * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want to - * create a MAC, this method helps you to obtain the {@link javax.crypto.SecretKey} - * from octets. - * - * @param secretKeyBytes - * @return the secret key created. - * @see SignedInfo#createSecretKey(byte[]) - */ - public SecretKey createSecretKey(byte[] secretKeyBytes) - { - return this.getSignedInfo().createSecretKey(secretKeyBytes); - } - - /** - * Signal wether Manifest should be automatically validated. - * Checking the digests in References in a Signature are mandatory, but for - * References inside a Manifest it is application specific. This boolean is - * to indicate that the References inside Manifests should be validated. - * - * @param followManifests - * @see Core validation section in the XML Signature Rec. - */ - public void setFollowNestedManifests(boolean followManifests) { - this._followManifestsDuringValidation = followManifests; - } - - /** - * Get the local name of this element - * - * @return Constant._TAG_SIGNATURE - */ - public String getBaseLocalName() { - return Constants._TAG_SIGNATURE; - } + // retrieve the byte[] from the stored signature + sigBytes = this.getSignatureValue(); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // Impossible... + } catch (XMLSecurityException ex) { + throw ex; + } + + // have SignatureAlgorithm sign the input bytes and compare them to + // the bytes that were stored in the signature. + if (!sa.verify(sigBytes)) { + log.log(java.util.logging.Level.WARNING, "Signature verification failed."); + return false; + } + + return si.verify(this.followManifestsDuringValidation); + } catch (XMLSignatureException ex) { + throw ex; + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** + * Add a Reference with full parameters to this Signature + * + * @param referenceURI URI of the resource to be signed. Can be null in + * which case the dereferencing is application specific. Can be "" in which + * it's the parent node (or parent document?). There can only be one "" in + * each signature. + * @param trans Optional list of transformations to be done before digesting + * @param digestURI Mandatory URI of the digesting algorithm to use. + * @param referenceId Optional id attribute for this Reference + * @param referenceType Optional mimetype for the URI + * @throws XMLSignatureException + */ + public void addDocument( + String referenceURI, + Transforms trans, + String digestURI, + String referenceId, + String referenceType + ) throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, trans, digestURI, referenceId, referenceType + ); + } + + /** + * This method is a proxy method for the {@link Manifest#addDocument} method. + * + * @param referenceURI URI according to the XML Signature specification. + * @param trans List of transformations to be applied. + * @param digestURI URI of the digest algorithm to be used. + * @see Manifest#addDocument + * @throws XMLSignatureException + */ + public void addDocument( + String referenceURI, + Transforms trans, + String digestURI + ) throws XMLSignatureException { + this.signedInfo.addDocument(this.baseURI, referenceURI, trans, digestURI, null, null); + } + + /** + * Adds a Reference with just the URI and the transforms. This used the + * SHA1 algorithm as a default digest algorithm. + * + * @param referenceURI URI according to the XML Signature specification. + * @param trans List of transformations to be applied. + * @throws XMLSignatureException + */ + public void addDocument(String referenceURI, Transforms trans) + throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, trans, Constants.ALGO_ID_DIGEST_SHA1, null, null + ); + } + + /** + * Add a Reference with just this URI. It uses SHA1 by default as the digest + * algorithm + * + * @param referenceURI URI according to the XML Signature specification. + * @throws XMLSignatureException + */ + public void addDocument(String referenceURI) throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, null, Constants.ALGO_ID_DIGEST_SHA1, null, null + ); + } + + /** + * Add an X509 Certificate to the KeyInfo. This will include the whole cert + * inside X509Data/X509Certificate tags. + * + * @param cert Certificate to be included. This should be the certificate of + * the key that was used to sign. + * @throws XMLSecurityException + */ + public void addKeyInfo(X509Certificate cert) throws XMLSecurityException { + X509Data x509data = new X509Data(this.doc); + + x509data.addCertificate(cert); + this.getKeyInfo().add(x509data); + } + + /** + * Add this public key to the KeyInfo. This will include the complete key in + * the KeyInfo structure. + * + * @param pk + */ + public void addKeyInfo(PublicKey pk) { + this.getKeyInfo().add(pk); + } + + /** + * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want + * to create a MAC, this method helps you to obtain the + * {@link javax.crypto.SecretKey} from octets. + * + * @param secretKeyBytes + * @return the secret key created. + * @see SignedInfo#createSecretKey(byte[]) + */ + public SecretKey createSecretKey(byte[] secretKeyBytes) { + return this.getSignedInfo().createSecretKey(secretKeyBytes); + } + + /** + * Signal wether Manifest should be automatically validated. + * Checking the digests in References in a Signature are mandatory, but for + * References inside a Manifest it is application specific. This boolean is + * to indicate that the References inside Manifests should be validated. + * + * @param followManifests + * @see + * Core validation section in the XML Signature Rec. + */ + public void setFollowNestedManifests(boolean followManifests) { + this.followManifestsDuringValidation = followManifests; + } + + /** + * Get the local name of this element + * + * @return Constants._TAG_SIGNATURE + */ + public String getBaseLocalName() { + return Constants._TAG_SIGNATURE; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java 2013-06-28 11:34:03.641492596 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java 2013-06-28 11:34:03.465498074 -0400 @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * All XML Signature related exceptions inherit herefrom. * @@ -33,57 +32,56 @@ */ public class XMLSignatureException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor XMLSignatureException - * - */ - public XMLSignatureException() { - super(); - } - - /** - * Constructor XMLSignatureException - * - * @param _msgID - */ - public XMLSignatureException(String _msgID) { - super(_msgID); - } - - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param exArgs - */ - public XMLSignatureException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param _originalException - */ - public XMLSignatureException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSignatureException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor XMLSignatureException + * + */ + public XMLSignatureException() { + super(); + } + + /** + * Constructor XMLSignatureException + * + * @param msgID + */ + public XMLSignatureException(String msgID) { + super(msgID); + } + + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param exArgs + */ + public XMLSignatureException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param originalException + */ + public XMLSignatureException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSignatureException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java 2013-06-28 11:34:04.257473423 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java 2013-06-28 11:34:04.093478529 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; @@ -25,7 +27,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -53,17 +54,13 @@ * @author Christian Geuer-Pollmann * $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set? */ -public class XMLSignatureInput implements Cloneable { - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (XMLSignatureInput.class.getName()); - +public class XMLSignatureInput { /* * The XMLSignature Input can be either: * A byteArray like with/or without InputStream. * Or a nodeSet like defined either: * * as a collection of nodes - * * or as subnode excluding or not commets and excluding or + * * or as subnode excluding or not comments and excluding or * not other nodes. */ @@ -71,78 +68,67 @@ * Some InputStreams do not support the {@link java.io.InputStream#reset} * method, so we read it in completely and work on our Proxy. */ - InputStream _inputOctetStreamProxy = null; + private InputStream inputOctetStreamProxy = null; /** * The original NodeSet for this XMLSignatureInput */ - Set _inputNodeSet = null; + private Set inputNodeSet = null; /** * The original Element */ - Node _subNode=null; + private Node subNode = null; /** * Exclude Node *for enveloped transformations* */ - Node excludeNode=null; + private Node excludeNode = null; /** - * + * */ - boolean excludeComments=false; - - boolean isNodeSet=false; + private boolean excludeComments = false; + + private boolean isNodeSet = false; /** * A cached bytes */ - byte []bytes=null; + private byte[] bytes = null; /** - * Some Transforms may require explicit MIME type, charset (IANA registered "character set"), or other such information concerning the data they are receiving from an earlier Transform or the source data, although no Transform algorithm specified in this document needs such explicit information. Such data characteristics are provided as parameters to the Transform algorithm and should be described in the specification for the algorithm. - */ - private String _MIMEType = null; + * Some Transforms may require explicit MIME type, charset (IANA registered + * "character set"), or other such information concerning the data they are + * receiving from an earlier Transform or the source data, although no + * Transform algorithm specified in this document needs such explicit + * information. Such data characteristics are provided as parameters to the + * Transform algorithm and should be described in the specification for the + * algorithm. + */ + private String mimeType = null; /** - * Field _SourceURI + * Field sourceURI */ - private String _SourceURI = null; + private String sourceURI = null; /** * Node Filter list. */ - List nodeFilters=new ArrayList(); - - boolean needsToBeExpanded=false; - OutputStream outputStream=null; - - /** - * Check if the structured is needed to be circumbented. - * @return true if so. - */ - public boolean isNeedsToBeExpanded() { - return needsToBeExpanded; - } - - /** - * Set if the structured is needed to be circumbented. - * @param needsToBeExpanded true if so. - */ - public void setNeedsToBeExpanded(boolean needsToBeExpanded) { - this.needsToBeExpanded = needsToBeExpanded; - } - + private List nodeFilters = new ArrayList(); + + private boolean needsToBeExpanded = false; + private OutputStream outputStream = null; + + private DocumentBuilderFactory dfactory; + /** * Construct a XMLSignatureInput from an octet array. *

      - * This is a comfort method, which internally converts the byte[] array into + * This is a comfort method, which internally converts the byte[] array into * an InputStream *

      NOTE: no defensive copy

      * @param inputOctets an octet array which including XML document or node */ public XMLSignatureInput(byte[] inputOctets) { - - // NO defensive copy - - //this._inputOctetStreamProxy = new ByteArrayInputStream(inputOctets); - this.bytes=inputOctets; + // NO defensive copy + this.bytes = inputOctets; } /** @@ -152,39 +138,7 @@ * @param inputOctetStream */ public XMLSignatureInput(InputStream inputOctetStream) { - this._inputOctetStreamProxy=inputOctetStream; - - //this(JavaUtils.getBytesFromStream(inputOctetStream)); - } - - /** - * Construct a XMLSignatureInput from a String. - *

      - * This is a comfort method, which internally converts the String into a byte - * [] array using the {@link java.lang.String#getBytes()} method. - * @deprecated - * @param inputStr the input String which including XML document or node - */ - @Deprecated - public XMLSignatureInput(String inputStr) { - this(inputStr.getBytes()); - } - - /** - * Construct a XMLSignatureInput from a String with a given encoding. - *

      - * This is a comfort method, which internally converts the String into a byte - * [] array using the {@link java.lang.String#getBytes()} method. - * - * @deprecated - * @param inputStr the input String with encoding encoding - * @param encoding the encoding of inputStr - * @throws UnsupportedEncodingException - */ - @Deprecated - public XMLSignatureInput(String inputStr, String encoding) - throws UnsupportedEncodingException { - this(inputStr.getBytes(encoding)); + this.inputOctetStreamProxy = inputOctetStream; } /** @@ -193,23 +147,37 @@ * * @param rootNode */ - public XMLSignatureInput(Node rootNode) - { - this._subNode = rootNode; + public XMLSignatureInput(Node rootNode) { + this.subNode = rootNode; } /** * Constructor XMLSignatureInput * * @param inputNodeSet - * @param usedXPathAPI */ public XMLSignatureInput(Set inputNodeSet) { - this._inputNodeSet = inputNodeSet; + this.inputNodeSet = inputNodeSet; + } + + /** + * Check if the structure needs to be expanded. + * @return true if so. + */ + public boolean isNeedsToBeExpanded() { + return needsToBeExpanded; + } + + /** + * Set if the structure needs to be expanded. + * @param needsToBeExpanded true if so. + */ + public void setNeedsToBeExpanded(boolean needsToBeExpanded) { + this.needsToBeExpanded = needsToBeExpanded; } /** - * Returns the node set from input which was specified as the parameter of + * Returns the node set from input which was specified as the parameter of * {@link XMLSignatureInput} constructor * * @return the node set @@ -218,13 +186,21 @@ * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet() throws CanonicalizationException, - ParserConfigurationException, IOException, SAXException { + public Set getNodeSet() throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { return getNodeSet(false); } + + /** + * Get the Input NodeSet. + * @return the Input NodeSet. + */ + public Set getInputNodeSet() { + return inputNodeSet; + } /** - * Returns the node set from input which was specified as the parameter of + * Returns the node set from input which was specified as the parameter of * {@link XMLSignatureInput} constructor * @param circumvent * @@ -234,79 +210,73 @@ * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet(boolean circumvent) - throws ParserConfigurationException, IOException, SAXException, - CanonicalizationException { - if (this._inputNodeSet!=null) { - return this._inputNodeSet; + public Set getNodeSet(boolean circumvent) throws ParserConfigurationException, + IOException, SAXException, CanonicalizationException { + if (inputNodeSet != null) { + return inputNodeSet; } - if ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) ) { - + if (inputOctetStreamProxy == null && subNode != null) { if (circumvent) { - XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(_subNode)); + XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode)); } - this._inputNodeSet = new LinkedHashSet(); - XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments); - - return this._inputNodeSet; - } else if (this.isOctetStream()) { + inputNodeSet = new LinkedHashSet(); + XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments); + return inputNodeSet; + } else if (isOctetStream()) { convertToNodes(); - LinkedHashSet result = new LinkedHashSet(); - XMLUtils.getSet(_subNode, result,null,false); - //this._inputNodeSet=result; + Set result = new LinkedHashSet(); + XMLUtils.getSet(subNode, result, null, false); return result; } - throw new RuntimeException( - "getNodeSet() called but no input data present"); + throw new RuntimeException("getNodeSet() called but no input data present"); } /** - * Returns the Octect stream(byte Stream) from input which was specified as + * Returns the Octet stream(byte Stream) from input which was specified as * the parameter of {@link XMLSignatureInput} constructor * - * @return the Octect stream(byte Stream) from input which was specified as + * @return the Octet stream(byte Stream) from input which was specified as * the parameter of {@link XMLSignatureInput} constructor * @throws IOException */ public InputStream getOctetStream() throws IOException { + if (inputOctetStreamProxy != null) { + return inputOctetStreamProxy; + } + + if (bytes != null) { + inputOctetStreamProxy = new ByteArrayInputStream(bytes); + return inputOctetStreamProxy; + } - return getResetableInputStream(); + return null; } /** - * @return real octect stream + * @return real octet stream */ - public InputStream getOctetStreamReal () { - return this._inputOctetStreamProxy; + public InputStream getOctetStreamReal() { + return inputOctetStreamProxy; } /** - * Returns the byte array from input which was specified as the parameter of + * Returns the byte array from input which was specified as the parameter of * {@link XMLSignatureInput} constructor * - * @return the byte[] from input which was specified as the parameter of + * @return the byte[] from input which was specified as the parameter of * {@link XMLSignatureInput} constructor * * @throws CanonicalizationException * @throws IOException */ public byte[] getBytes() throws IOException, CanonicalizationException { - if (bytes!=null) { - return bytes; + byte[] inputBytes = getBytesFromInputStream(); + if (inputBytes != null) { + return inputBytes; } - InputStream is = getResetableInputStream(); - if (is!=null) { - //resetable can read again bytes. - if (bytes==null) { - is.reset(); - bytes=JavaUtils.getBytesFromStream(is); - } - return bytes; - } - Canonicalizer20010315OmitComments c14nizer = - new Canonicalizer20010315OmitComments(); - bytes=c14nizer.engineCanonicalize(this); + Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments(); + bytes = c14nizer.engineCanonicalize(this); return bytes; } @@ -316,49 +286,48 @@ * @return true if the object has been set up with a Node set */ public boolean isNodeSet() { - return (( (this._inputOctetStreamProxy == null) - && (this._inputNodeSet != null) ) || isNodeSet); + return ((inputOctetStreamProxy == null + && inputNodeSet != null) || isNodeSet); } /** * Determines if the object has been set up with an Element * - * @return true if the object has been set up with a Node set + * @return true if the object has been set up with an Element */ public boolean isElement() { - return ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) - && (this._inputNodeSet==null) && !isNodeSet); + return (inputOctetStreamProxy == null && subNode != null + && inputNodeSet == null && !isNodeSet); } - + /** * Determines if 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 isOctetStream() { - return ( ((this._inputOctetStreamProxy != null) || bytes!=null) - && ((this._inputNodeSet == null) && _subNode ==null)); + return ((inputOctetStreamProxy != null || bytes != null) + && (inputNodeSet == null && subNode == null)); } /** - * Determines if {@link #setOutputStream} has been called with a + * Determines if {@link #setOutputStream} has been called with a * non-null OutputStream. * - * @return true if {@link #setOutputStream} has been called with a + * @return true if {@link #setOutputStream} has been called with a * non-null OutputStream */ public boolean isOutputStreamSet() { return outputStream != null; } - + /** * Determines if the object has been set up with a ByteArray * * @return true is the object has been set up with an octet stream */ public boolean isByteArray() { - return ( (bytes!=null) - && ((this._inputNodeSet == null) && _subNode ==null)); + return (bytes != null && (this.inputNodeSet == null && subNode == null)); } /** @@ -367,25 +336,25 @@ * @return true if the object has been set up correctly */ public boolean isInitialized() { - return (this.isOctetStream() || this.isNodeSet()); + return isOctetStream() || isNodeSet(); } /** - * Returns MIMEType + * Returns mimeType * - * @return MIMEType + * @return mimeType */ public String getMIMEType() { - return this._MIMEType; + return mimeType; } /** - * Sets MIMEType + * Sets mimeType * - * @param MIMEType + * @param mimeType */ - public void setMIMEType(String MIMEType) { - this._MIMEType = MIMEType; + public void setMIMEType(String mimeType) { + this.mimeType = mimeType; } /** @@ -394,39 +363,39 @@ * @return SourceURI */ public String getSourceURI() { - return this._SourceURI; + return sourceURI; } /** * Sets SourceURI * - * @param SourceURI + * @param sourceURI */ - public void setSourceURI(String SourceURI) { - this._SourceURI = SourceURI; + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; } - + /** * Method toString * @inheritDoc */ public String toString() { - if (this.isNodeSet()) { - return "XMLSignatureInput/NodeSet/" + this._inputNodeSet.size() - + " nodes/" + this.getSourceURI(); - } - if (this.isElement()) { - return "XMLSignatureInput/Element/" + this._subNode - + " exclude "+ this.excludeNode + " comments:" + - this.excludeComments +"/" + this.getSourceURI(); + if (isNodeSet()) { + return "XMLSignatureInput/NodeSet/" + inputNodeSet.size() + + " nodes/" + getSourceURI(); + } + if (isElement()) { + return "XMLSignatureInput/Element/" + subNode + + " exclude "+ excludeNode + " comments:" + + excludeComments +"/" + getSourceURI(); } try { - return "XMLSignatureInput/OctetStream/" + this.getBytes().length - + " octets/" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream/" + getBytes().length + + " octets/" + getSourceURI(); } catch (IOException iex) { - return "XMLSignatureInput/OctetStream//" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream//" + getSourceURI(); } catch (CanonicalizationException cex) { - return "XMLSignatureInput/OctetStream//" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream//" + getSourceURI(); } } @@ -437,9 +406,7 @@ * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation() throws XMLSignatureException { - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger(this); - return db.getHTMLRepresentation(); } @@ -451,11 +418,9 @@ * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation(Set inclusiveNamespaces) - throws XMLSignatureException { - - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger( this, - inclusiveNamespaces); - + throws XMLSignatureException { + XMLSignatureInputDebugger db = + new XMLSignatureInputDebugger(this, inclusiveNamespaces); return db.getHTMLRepresentation(); } @@ -466,7 +431,7 @@ public Node getExcludeNode() { return excludeNode; } - + /** * Sets the exclude node of this XMLSignatureInput * @param excludeNode The excludeNode to set. @@ -480,7 +445,7 @@ * @return The excludeNode set. */ public Node getSubNode() { - return _subNode; + return subNode; } /** @@ -503,40 +468,36 @@ * @throws CanonicalizationException */ public void updateOutputStream(OutputStream diOs) - throws CanonicalizationException, IOException { + throws CanonicalizationException, IOException { updateOutputStream(diOs, false); } - - public void updateOutputStream(OutputStream diOs, boolean c14n11) - throws CanonicalizationException, IOException { - if (diOs==outputStream) { + + public void updateOutputStream(OutputStream diOs, boolean c14n11) + throws CanonicalizationException, IOException { + if (diOs == outputStream) { return; } - if (bytes!=null) { + if (bytes != null) { diOs.write(bytes); - return; - } else if (_inputOctetStreamProxy==null) { + } else if (inputOctetStreamProxy == null) { CanonicalizerBase c14nizer = null; if (c14n11) { - c14nizer = new Canonicalizer11_OmitComments(); + c14nizer = new Canonicalizer11_OmitComments(); } else { - c14nizer = new Canonicalizer20010315OmitComments(); + c14nizer = new Canonicalizer20010315OmitComments(); } c14nizer.setWriter(diOs); - c14nizer.engineCanonicalize(this); - return; + c14nizer.engineCanonicalize(this); } else { - InputStream is = getResetableInputStream(); - if (bytes!=null) { - //already read write it, can be rea. - diOs.write(bytes,0,bytes.length); - return; - } - is.reset(); - int num; - byte[] bytesT = new byte[1024]; - while ((num=is.read(bytesT))>0) { - diOs.write(bytesT,0,num); + byte[] buffer = new byte[4 * 1024]; + int bytesread = 0; + try { + while ((bytesread = inputOctetStreamProxy.read(buffer)) != -1) { + diOs.write(buffer, 0, bytesread); + } + } catch (IOException ex) { + inputOctetStreamProxy.close(); + throw ex; } } } @@ -545,40 +506,35 @@ * @param os */ public void setOutputStream(OutputStream os) { - outputStream=os; + outputStream = os; } - protected InputStream getResetableInputStream() throws IOException{ - if ((_inputOctetStreamProxy instanceof ByteArrayInputStream) ) { - if (!_inputOctetStreamProxy.markSupported()) { - throw new RuntimeException("Accepted as Markable but not truly been"+_inputOctetStreamProxy); - } - return _inputOctetStreamProxy; - } - if (bytes!=null) { - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; + private byte[] getBytesFromInputStream() throws IOException { + if (bytes != null) { + return bytes; } - if (_inputOctetStreamProxy ==null) + if (inputOctetStreamProxy == null) { return null; - if (_inputOctetStreamProxy.markSupported()) { - log.log(java.util.logging.Level.INFO, "Mark Suported but not used as reset"); } - bytes=JavaUtils.getBytesFromStream(_inputOctetStreamProxy); - _inputOctetStreamProxy.close(); - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; + try { + bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy); + } finally { + inputOctetStreamProxy.close(); + } + return bytes; } - + /** * @param filter */ - public void addNodeFilter(NodeFilter filter) { + public void addNodeFilter(NodeFilter filter) { if (isOctetStream()) { try { convertToNodes(); } catch (Exception e) { - throw new XMLSecurityRuntimeException("signature.XMLSignatureInput.nodesetReference",e); + throw new XMLSecurityRuntimeException( + "signature.XMLSignatureInput.nodesetReference", e + ); } } nodeFilters.add(filter); @@ -588,7 +544,6 @@ * @return the node filters */ public List getNodeFilters() { - // TODO Auto-generated method stub return nodeFilters; } @@ -596,39 +551,42 @@ * @param b */ public void setNodeSet(boolean b) { - isNodeSet=b; + isNodeSet = b; } - - void convertToNodes() throws CanonicalizationException, + + void convertToNodes() throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setValidating(false); - dfactory.setNamespaceAware(true); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); + if (dfactory == null) { + dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + dfactory.setValidating(false); + dfactory.setNamespaceAware(true); + } DocumentBuilder db = dfactory.newDocumentBuilder(); - // select all nodes, also the comments. + // select all nodes, also the comments. try { - db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils - .IgnoreAllErrorHandler()); + db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler()); Document doc = db.parse(this.getOctetStream()); - - this._subNode=doc.getDocumentElement(); + this.subNode = doc; } catch (SAXException ex) { - // if a not-wellformed nodeset exists, put a container around it... ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write("".getBytes()); + baos.write("".getBytes("UTF-8")); baos.write(this.getBytes()); - baos.write("".getBytes()); + baos.write("".getBytes("UTF-8")); byte result[] = baos.toByteArray(); Document document = db.parse(new ByteArrayInputStream(result)); - this._subNode=document.getDocumentElement().getFirstChild().getFirstChild(); + this.subNode = document.getDocumentElement().getFirstChild().getFirstChild(); + } finally { + if (this.inputOctetStreamProxy != null) { + this.inputOctetStreamProxy.close(); + } + this.inputOctetStreamProxy = null; + this.bytes = null; } - this._inputOctetStreamProxy=null; - this.bytes=null; } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java 2013-06-28 11:34:04.949451882 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java 2013-06-28 11:34:04.793456737 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; @@ -38,681 +40,591 @@ /** * Class XMLSignatureInputDebugger - * - * @author $Author: mullan $ - * @version $Revision: 1.3 $ */ public class XMLSignatureInputDebugger { + /** Field _xmlSignatureInput */ + private Set xpathNodeSet; + private Set inclusiveNamespaces; - /** Field _xmlSignatureInput */ - private Set _xpathNodeSet; - - private Set _inclusiveNamespaces; - - /** Field _doc */ - private Document _doc = null; - - /** Field _writer */ - private Writer _writer = null; - - // J- - // public static final String HTMLPrefix = "

      ";
      -        /** The HTML Prefix* */
      -        static final String HTMLPrefix = "\n"
      -                        + "\n"
      -                        + "\n"
      -                        + "Caninical XML node set\n"
      -                        + " \n"
      -                        + "\n"
      -                        + "\n"
      -                        + "

      Explanation of the output

      \n" - + "

      The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.

      \n" - + "
        \n" - + "
      • A node which is in the node set is labeled using the INCLUDED style.
      • \n" - + "
      • A node which is NOT in the node set is labeled EXCLUDED style.
      • \n" - + "
      • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
      • \n" - + "
      • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
      • \n" - + "
      \n" + "

      Output

      \n" + "
      \n";
      -
      -        /** HTML Suffix * */
      -        static final String HTMLSuffix = "
      "; - - static final String HTMLExcludePrefix = ""; - - static final String HTMLExcludeSuffix = ""; - - static final String HTMLIncludePrefix = ""; - - static final String HTMLIncludeSuffix = ""; - - static final String HTMLIncludedInclusiveNamespacePrefix = ""; - - static final String HTMLIncludedInclusiveNamespaceSuffix = ""; - - static final String HTMLExcludedInclusiveNamespacePrefix = ""; - - static final String HTMLExcludedInclusiveNamespaceSuffix = ""; - - private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - - private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - - private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - - static final AttrCompare ATTR_COMPARE = new AttrCompare(); - - // J+ - private XMLSignatureInputDebugger() { - // do nothing - } - - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput) { + /** Field doc */ + private Document doc = null; - if (!xmlSignatureInput.isNodeSet()) { - this._xpathNodeSet = null; - } else { - this._xpathNodeSet = xmlSignatureInput._inputNodeSet; - } + /** Field writer */ + private Writer writer = null; + + /** The HTML Prefix* */ + static final String HTMLPrefix = + "\n" + + "\n" + + "\n" + + "Caninical XML node set\n" + + " \n" + + "\n" + + "\n" + + "

      Explanation of the output

      \n" + + "

      The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.

      \n" + + "
        \n" + + "
      • A node which is in the node set is labeled using the INCLUDED style.
      • \n" + + "
      • A node which is NOT in the node set is labeled EXCLUDED style.
      • \n" + + "
      • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
      • \n" + + "
      • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
      • \n" + + "
      \n" + "

      Output

      \n" + "
      \n";
      +
      +    /** HTML Suffix * */
      +    static final String HTMLSuffix = "
      "; + + static final String HTMLExcludePrefix = ""; + + static final String HTMLIncludePrefix = ""; + + static final String HTMLIncludeOrExcludeSuffix = ""; + + static final String HTMLIncludedInclusiveNamespacePrefix = ""; + + static final String HTMLExcludedInclusiveNamespacePrefix = ""; + + private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; + + private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; + + private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; + + static final AttrCompare ATTR_COMPARE = new AttrCompare(); + + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signature to pretty print + */ + public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) { + if (!xmlSignatureInput.isNodeSet()) { + this.xpathNodeSet = null; + } else { + this.xpathNodeSet = xmlSignatureInput.getInputNodeSet(); } + } - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - * @param inclusiveNamespace - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput, Set inclusiveNamespace) { - - this(xmlSignatureInput); - - this._inclusiveNamespaces = inclusiveNamespace; - } - - /** - * Method getHTMLRepresentation - * - * @return The HTML Representation. - * @throws XMLSignatureException - */ - public String getHTMLRepresentation() throws XMLSignatureException { - - if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) { - return HTMLPrefix + "no node set, sorry" - + HTMLSuffix; - } - - { - - // get only a single node as anchor to fetch the owner document - Node n = this._xpathNodeSet.iterator().next(); - - this._doc = XMLUtils.getOwnerDocument(n); - } - - try { - this._writer = new StringWriter(); - - this.canonicalizeXPathNodeSet(this._doc); - this._writer.close(); - - return this._writer.toString(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } finally { - this._xpathNodeSet = null; - this._doc = null; - this._writer = null; - } + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signatur to pretty print + * @param inclusiveNamespace + */ + public XMLSignatureInputDebugger( + XMLSignatureInput xmlSignatureInput, + Set inclusiveNamespace + ) { + this(xmlSignatureInput); + this.inclusiveNamespaces = inclusiveNamespace; + } + + /** + * Method getHTMLRepresentation + * + * @return The HTML Representation. + * @throws XMLSignatureException + */ + public String getHTMLRepresentation() throws XMLSignatureException { + if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) { + return HTMLPrefix + "no node set, sorry" + HTMLSuffix; } - /** - * Method canonicalizeXPathNodeSet - * - * @param currentNode - * @throws XMLSignatureException - * @throws IOException - */ - private void canonicalizeXPathNodeSet(Node currentNode) - throws XMLSignatureException, IOException { + // get only a single node as anchor to fetch the owner document + Node n = this.xpathNodeSet.iterator().next(); - int currentNodeType = currentNode.getNodeType(); - switch (currentNodeType) { + this.doc = XMLUtils.getOwnerDocument(n); - case Node.DOCUMENT_TYPE_NODE: - default: - break; + try { + this.writer = new StringWriter(); - case Node.ENTITY_NODE: - case Node.NOTATION_NODE: - case Node.DOCUMENT_FRAGMENT_NODE: - case Node.ATTRIBUTE_NODE: - throw new XMLSignatureException("empty"); - case Node.DOCUMENT_NODE: - this._writer.write(HTMLPrefix); - - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - this._writer.write(HTMLSuffix); - break; - - case Node.COMMENT_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - int position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputCommentToWriter((Comment) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputPItoWriter((ProcessingInstruction) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.TEXT_NODE: - case Node.CDATA_SECTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - outputTextToWriter(currentNode.getNodeValue()); - - for (Node nextSibling = currentNode.getNextSibling(); (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) || (nextSibling - .getNodeType() == Node.CDATA_SECTION_NODE)); nextSibling = nextSibling - .getNextSibling()) { - - /* - * The XPath data model allows to select only the first of a - * sequence of mixed text and CDATA nodes. But we must output - * them all, so we must search: - * - * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 - */ - this.outputTextToWriter(nextSibling.getNodeValue()); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.ELEMENT_NODE: - Element currentElement = (Element) currentNode; - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("<"); - this._writer.write(currentElement.getTagName()); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // we output all Attrs which are available - NamedNodeMap attrs = currentElement.getAttributes(); - int attrsLength = attrs.getLength(); - Attr attrs2[] = new Attr[attrsLength]; - - for (int i = 0; i < attrsLength; i++) { - attrs2[i] = (Attr)attrs.item(i); - } - - Arrays.sort(attrs2, ATTR_COMPARE); - Object attrs3[] = attrs2; - - for (int i = 0; i < attrsLength; i++) { - Attr a = (Attr) attrs3[i]; - boolean included = this._xpathNodeSet.contains(a); - boolean inclusive = this._inclusiveNamespaces.contains(a - .getName()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespacePrefix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludePrefix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespacePrefix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludePrefix); - } - } - - this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespaceSuffix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludeSuffix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespaceSuffix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludeSuffix); - } - } - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // traversal - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("</"); - this._writer.write(currentElement.getTagName()); - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - } + this.canonicalizeXPathNodeSet(this.doc); + this.writer.close(); + + return this.writer.toString(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } finally { + this.xpathNodeSet = null; + this.doc = null; + this.writer = null; } + } - /** - * Checks whether a Comment or ProcessingInstruction is before or after the - * document element. This is needed for prepending or appending "\n"s. - * - * @param currentNode - * comment or pi to check - * @return NODE_BEFORE_DOCUMENT_ELEMENT, - * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or - * NODE_AFTER_DOCUMENT_ELEMENT - * @see #NODE_BEFORE_DOCUMENT_ELEMENT - * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT - * @see #NODE_AFTER_DOCUMENT_ELEMENT - */ - private int getPositionRelativeToDocumentElement(Node currentNode) { - - if (currentNode == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + /** + * Method canonicalizeXPathNodeSet + * + * @param currentNode + * @throws XMLSignatureException + * @throws IOException + */ + private void canonicalizeXPathNodeSet(Node currentNode) + throws XMLSignatureException, IOException { + + int currentNodeType = currentNode.getNodeType(); + switch (currentNodeType) { + + + case Node.ENTITY_NODE: + case Node.NOTATION_NODE: + case Node.DOCUMENT_FRAGMENT_NODE: + case Node.ATTRIBUTE_NODE: + throw new XMLSignatureException("empty"); + case Node.DOCUMENT_NODE: + this.writer.write(HTMLPrefix); + + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + this.writer.write(HTMLSuffix); + break; + + case Node.COMMENT_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + int position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputCommentToWriter((Comment) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.PROCESSING_INSTRUCTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputPItoWriter((ProcessingInstruction) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + outputTextToWriter(currentNode.getNodeValue()); + + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) + && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + /* + * The XPath data model allows to select only the first of a + * sequence of mixed text and CDATA nodes. But we must output + * them all, so we must search: + * + * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 + */ + this.outputTextToWriter(nextSibling.getNodeValue()); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.ELEMENT_NODE: + Element currentElement = (Element) currentNode; + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("<"); + this.writer.write(currentElement.getTagName()); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // we output all Attrs which are available + NamedNodeMap attrs = currentElement.getAttributes(); + int attrsLength = attrs.getLength(); + Attr attrs2[] = new Attr[attrsLength]; + + for (int i = 0; i < attrsLength; i++) { + attrs2[i] = (Attr)attrs.item(i); + } + + Arrays.sort(attrs2, ATTR_COMPARE); + Object attrs3[] = attrs2; + + for (int i = 0; i < attrsLength; i++) { + Attr a = (Attr) attrs3[i]; + boolean included = this.xpathNodeSet.contains(a); + boolean inclusive = this.inclusiveNamespaces.contains(a.getName()); + + if (included) { + if (inclusive) { + // included and inclusive + this.writer.write(HTMLIncludedInclusiveNamespacePrefix); + } else { + // included and not inclusive + this.writer.write(HTMLIncludePrefix); + } + } else { + if (inclusive) { + // excluded and inclusive + this.writer.write(HTMLExcludedInclusiveNamespacePrefix); + } else { + // excluded and not inclusive + this.writer.write(HTMLExcludePrefix); + } } - Document doc = currentNode.getOwnerDocument(); + this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); + this.writer.write(HTMLIncludeOrExcludeSuffix); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // traversal + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; + currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("</"); + this.writer.write(currentElement.getTagName()); + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.DOCUMENT_TYPE_NODE: + default: + break; + } + } - if (currentNode.getParentNode() != doc) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } + /** + * Checks whether a Comment or ProcessingInstruction is before or after the + * document element. This is needed for prepending or appending "\n"s. + * + * @param currentNode + * comment or pi to check + * @return NODE_BEFORE_DOCUMENT_ELEMENT, + * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or + * NODE_AFTER_DOCUMENT_ELEMENT + * @see #NODE_BEFORE_DOCUMENT_ELEMENT + * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT + * @see #NODE_AFTER_DOCUMENT_ELEMENT + */ + private int getPositionRelativeToDocumentElement(Node currentNode) { + if (currentNode == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } - Element documentElement = doc.getDocumentElement(); + Document doc = currentNode.getOwnerDocument(); - if (documentElement == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } + if (currentNode.getParentNode() != doc) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } - if (documentElement == currentNode) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } + Element documentElement = doc.getDocumentElement(); - for (Node x = currentNode; x != null; x = x.getNextSibling()) { - if (x == documentElement) { - return NODE_BEFORE_DOCUMENT_ELEMENT; - } - } + if (documentElement == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } - return NODE_AFTER_DOCUMENT_ELEMENT; + if (documentElement == currentNode) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Normalizes an {@link Attr}ibute value - * - * The string value of the node is modified by replacing - *
        - *
      • all ampersands (&) with &amp;
      • - *
      • all open angle brackets (<) with &lt;
      • - *
      • all quotation mark characters with &quot;
      • - *
      • and the whitespace characters #x9, #xA, and #xD, - * with character references. The character references are written in - * uppercase hexadecimal with no leading zeroes (for example, #xD - * is represented by the character reference &#xD;)
      • - *
      - * - * @param name - * @param value - * @throws IOException - */ - private void outputAttrToWriter(String name, String value) - throws IOException { - - this._writer.write(" "); - this._writer.write(name); - this._writer.write("=\""); - - int length = value.length(); - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '"': - this._writer.write("&quot;"); - break; - - case 0x09: // '\t' - this._writer.write("&#x9;"); - break; - - case 0x0A: // '\n' - this._writer.write("&#xA;"); - break; - - case 0x0D: // '\r' - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } - } + for (Node x = currentNode; x != null; x = x.getNextSibling()) { + if (x == documentElement) { + return NODE_BEFORE_DOCUMENT_ELEMENT; + } + } - this._writer.write("\""); + return NODE_AFTER_DOCUMENT_ELEMENT; + } + + /** + * Normalizes an {@link Attr}ibute value + * + * The string value of the node is modified by replacing + *
        + *
      • all ampersands (&) with &amp;
      • + *
      • all open angle brackets (<) with &lt;
      • + *
      • all quotation mark characters with &quot;
      • + *
      • and the whitespace characters #x9, #xA, and #xD, + * with character references. The character references are written in + * uppercase hexadecimal with no leading zeroes (for example, #xD + * is represented by the character reference &#xD;)
      • + *
      + * + * @param name + * @param value + * @throws IOException + */ + private void outputAttrToWriter(String name, String value) throws IOException { + this.writer.write(" "); + this.writer.write(name); + this.writer.write("=\""); + + int length = value.length(); + + for (int i = 0; i < length; i++) { + char c = value.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '"': + this.writer.write("&quot;"); + break; + + case 0x09: // '\t' + this.writer.write("&#x9;"); + break; + + case 0x0A: // '\n' + this.writer.write("&#xA;"); + break; + + case 0x0D: // '\r' + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } } - /** - * Normalizes a {@link org.w3c.dom.Comment} value - * - * @param currentPI - * @throws IOException - */ - private void outputPItoWriter(ProcessingInstruction currentPI) - throws IOException { + this.writer.write("\""); + } - if (currentPI == null) { - return; - } + /** + * Normalizes a {@link org.w3c.dom.Comment} value + * + * @param currentPI + * @throws IOException + */ + private void outputPItoWriter(ProcessingInstruction currentPI) throws IOException { + + if (currentPI == null) { + return; + } - this._writer.write("<?"); + this.writer.write("<?"); - String target = currentPI.getTarget(); - int length = target.length(); + String target = currentPI.getTarget(); + int length = target.length(); - for (int i = 0; i < length; i++) { - char c = target.charAt(i); + for (int i = 0; i < length; i++) { + char c = target.charAt(i); - switch (c) { + switch (c) { - case 0x0D: - this._writer.write("&#xD;"); - break; + case 0x0D: + this.writer.write("&#xD;"); + break; - case ' ': - this._writer.write("·"); - break; + case ' ': + this.writer.write("·"); + break; - case '\n': - this._writer.write("¶\n"); - break; + case '\n': + this.writer.write("¶\n"); + break; - default: - this._writer.write(c); - break; - } - } + default: + this.writer.write(c); + break; + } + } - String data = currentPI.getData(); + String data = currentPI.getData(); - length = data.length(); + length = data.length(); - if (length > 0) { - this._writer.write(" "); + if (length > 0) { + this.writer.write(" "); - for (int i = 0; i < length; i++) { - char c = data.charAt(i); + for (int i = 0; i < length; i++) { + char c = data.charAt(i); - switch (c) { + switch (c) { - case 0x0D: - this._writer.write("&#xD;"); - break; + case 0x0D: + this.writer.write("&#xD;"); + break; - default: - this._writer.write(c); - break; - } - } + default: + this.writer.write(c); + break; } - - this._writer.write("?>"); + } } - /** - * Method outputCommentToWriter - * - * @param currentComment - * @throws IOException - */ - private void outputCommentToWriter(Comment currentComment) - throws IOException { + this.writer.write("?>"); + } - if (currentComment == null) { - return; - } + /** + * Method outputCommentToWriter + * + * @param currentComment + * @throws IOException + */ + private void outputCommentToWriter(Comment currentComment) throws IOException { - this._writer.write("<!--"); + if (currentComment == null) { + return; + } - String data = currentComment.getData(); - int length = data.length(); + this.writer.write("<!--"); - for (int i = 0; i < length; i++) { - char c = data.charAt(i); + String data = currentComment.getData(); + int length = data.length(); - switch (c) { + for (int i = 0; i < length; i++) { + char c = data.charAt(i); - case 0x0D: - this._writer.write("&#xD;"); - break; + switch (c) { - case ' ': - this._writer.write("·"); - break; + case 0x0D: + this.writer.write("&#xD;"); + break; - case '\n': - this._writer.write("¶\n"); - break; + case ' ': + this.writer.write("·"); + break; - default: - this._writer.write(c); - break; - } - } + case '\n': + this.writer.write("¶\n"); + break; - this._writer.write("-->"); + default: + this.writer.write(c); + break; + } } - /** - * Method outputTextToWriter - * - * @param text - * @throws IOException - */ - private void outputTextToWriter(String text) throws IOException { + this.writer.write("-->"); + } - if (text == null) { - return; - } + /** + * Method outputTextToWriter + * + * @param text + * @throws IOException + */ + private void outputTextToWriter(String text) throws IOException { + if (text == null) { + return; + } - int length = text.length(); + int length = text.length(); - for (int i = 0; i < length; i++) { - char c = text.charAt(i); + for (int i = 0; i < length; i++) { + char c = text.charAt(i); - switch (c) { + switch (c) { - case '&': - this._writer.write("&amp;"); - break; + case '&': + this.writer.write("&amp;"); + break; - case '<': - this._writer.write("&lt;"); - break; + case '<': + this.writer.write("&lt;"); + break; - case '>': - this._writer.write("&gt;"); - break; + case '>': + this.writer.write("&gt;"); + break; - case 0xD: - this._writer.write("&#xD;"); - break; + case 0xD: + this.writer.write("&#xD;"); + break; - case ' ': - this._writer.write("·"); - break; + case ' ': + this.writer.write("·"); + break; - case '\n': - this._writer.write("¶\n"); - break; + case '\n': + this.writer.write("¶\n"); + break; - default: - this._writer.write(c); - break; - } - } + default: + this.writer.write(c); + break; + } } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java 2013-06-28 11:34:05.685428973 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java 2013-06-28 11:34:05.517434202 -0400 @@ -2,86 +2,84 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class InvalidTransformException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor InvalidTransformException - * - */ - public InvalidTransformException() { - super(); - } - - /** - * Constructor InvalidTransformException - * - * @param _msgId - */ - public InvalidTransformException(String _msgId) { - super(_msgId); - } - - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - */ - public InvalidTransformException(String _msgId, Object exArgs[]) { - super(_msgId, exArgs); - } - - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param _originalException - */ - public InvalidTransformException(String _msgId, Exception _originalException) { - super(_msgId, _originalException); - } - - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - * @param _originalException - */ - public InvalidTransformException(String _msgId, Object exArgs[], - Exception _originalException) { - super(_msgId, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor InvalidTransformException + * + */ + public InvalidTransformException() { + super(); + } + + /** + * Constructor InvalidTransformException + * + * @param msgId + */ + public InvalidTransformException(String msgId) { + super(msgId); + } + + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + */ + public InvalidTransformException(String msgId, Object exArgs[]) { + super(msgId, exArgs); + } + + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param originalException + */ + public InvalidTransformException(String msgId, Exception originalException) { + super(msgId, originalException); + } + + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + * @param originalException + */ + public InvalidTransformException(String msgId, Object exArgs[], Exception originalException) { + super(msgId, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java 2013-06-28 11:34:06.397406811 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java 2013-06-28 11:34:06.213412538 -0400 @@ -69,48 +69,48 @@ public final class Transform extends SignatureElementProxy { /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(Transform.class.getName()); /** All available Transform classes are registered here */ - private static Map> transformSpiHash = + private static Map> transformSpiHash = new ConcurrentHashMap>(); - + private final TransformSpi transformSpi; - + /** - * Generates a Transform object that implements the specified + * Generates a Transform object that implements the specified * Transform algorithm URI. * * @param doc the proxy {@link Document} - * @param algorithmURI Transform algorithm URI representation, - * such as specified in + * @param algorithmURI Transform algorithm URI representation, + * such as specified in * Transform algorithm * @throws InvalidTransformException */ public Transform(Document doc, String algorithmURI) throws InvalidTransformException { this(doc, algorithmURI, (NodeList)null); } - + /** - * Generates a Transform object that implements the specified + * Generates a Transform object that implements the specified * Transform algorithm URI. * - * @param algorithmURI Transform algorithm URI representation, - * such as specified in + * @param algorithmURI Transform algorithm URI representation, + * such as specified in * Transform algorithm * @param contextChild the child element of Transform element * @param doc the proxy {@link Document} * @throws InvalidTransformException */ - public Transform(Document doc, String algorithmURI, Element contextChild) + public Transform(Document doc, String algorithmURI, Element contextChild) throws InvalidTransformException { super(doc); HelperNodeList contextNodes = null; - + if (contextChild != null) { contextNodes = new HelperNodeList(); - + XMLUtils.addReturnToElement(doc, contextNodes); contextNodes.appendChild(contextChild); XMLUtils.addReturnToElement(doc, contextNodes); @@ -122,7 +122,7 @@ /** * Constructs {@link Transform} * - * @param doc the {@link Document} in which Transform will be + * @param doc the {@link Document} in which Transform will be * placed * @param algorithmURI URI representation of Transform algorithm * @param contextNodes the child node list of Transform element @@ -152,7 +152,7 @@ Object exArgs[] = { Constants._ATT_ALGORITHM, Constants._TAG_TRANSFORM }; throw new TransformationException("xml.WrongContent", exArgs); } - + Class transformSpiClass = transformSpiHash.get(algorithmURI); if (transformSpiClass == null) { Object exArgs[] = { algorithmURI }; @@ -172,19 +172,19 @@ ); } } - + /** * Registers implementing class of the Transform algorithm with algorithmURI * * @param algorithmURI algorithmURI URI representation of Transform algorithm - * @param implementingClass implementingClass the implementing + * @param implementingClass implementingClass the implementing * class of {@link TransformSpi} - * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI + * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI * is already registered */ @SuppressWarnings("unchecked") public static void register(String algorithmURI, String implementingClass) - throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, + throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, InvalidTransformException { // are we already registered? Class transformSpi = transformSpiHash.get(algorithmURI); @@ -192,19 +192,19 @@ Object exArgs[] = { algorithmURI, transformSpi }; throw new AlgorithmAlreadyRegisteredException("algorithm.alreadyRegistered", exArgs); } - Class transformSpiClass = + Class transformSpiClass = (Class) ClassLoaderUtils.loadClass(implementingClass, Transform.class); transformSpiHash.put(algorithmURI, transformSpiClass); } - + /** * Registers implementing class of the Transform algorithm with algorithmURI * * @param algorithmURI algorithmURI URI representation of Transform algorithm - * @param implementingClass implementingClass the implementing + * @param implementingClass implementingClass the implementing * class of {@link TransformSpi} - * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI + * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI * is already registered */ public static void register(String algorithmURI, Class implementingClass) @@ -256,22 +256,22 @@ Transforms.TRANSFORM_XPATH2FILTER, TransformXPath2Filter.class ); } - + /** * Returns the URI representation of Transformation algorithm * * @return the URI representation of Transformation algorithm */ public String getURI() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); } /** * Transforms the input, and generates {@link XMLSignatureInput} as output. * - * @param input input {@link XMLSignatureInput} which can supplied Octet + * @param input input {@link XMLSignatureInput} which can supplied Octet * Stream and NodeSet as Input of Transformation - * @return the {@link XMLSignatureInput} class as the result of + * @return the {@link XMLSignatureInput} class as the result of * transformation * @throws CanonicalizationException * @throws IOException @@ -283,14 +283,14 @@ InvalidCanonicalizerException, TransformationException { return performTransform(input, null); } - + /** * Transforms the input, and generates {@link XMLSignatureInput} as output. * - * @param input input {@link XMLSignatureInput} which can supplied Octect + * @param input input {@link XMLSignatureInput} which can supplied Octect * Stream and NodeSet as Input of Transformation * @param os where to output the result of the last transformation - * @return the {@link XMLSignatureInput} class as the result of + * @return the {@link XMLSignatureInput} class as the result of * transformation * @throws CanonicalizationException * @throws IOException @@ -322,14 +322,14 @@ public String getBaseLocalName() { return Constants._TAG_TRANSFORM; } - + /** * Initialize the transform object. */ private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes) throws InvalidTransformException { - this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); Class transformSpiClass = transformSpiHash.get(algorithmURI); if (transformSpiClass == null) { @@ -360,7 +360,7 @@ // give it to the current document if (contextNodes != null) { for (int i = 0; i < contextNodes.getLength(); i++) { - this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); + this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); } } return newTransformSpi; --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java 2013-06-28 11:34:06.989388384 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java 2013-06-28 11:34:06.821393613 -0400 @@ -2,29 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms; -/** - * - * @author $Author: mullan $ - */ - public interface TransformParam { -} +} \ No newline at end of file --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java 2013-06-28 11:34:07.681366844 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java 2013-06-28 11:34:07.521371824 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms; @@ -31,34 +33,19 @@ /** * Base class which all Transform algorithms extend. The common methods that - * have to be overridden are the + * have to be overridden are the * {@link #enginePerformTransform(XMLSignatureInput, Transform)} method. * * @author Christian Geuer-Pollmann */ public abstract class TransformSpi { - /** - * For API compatibility not thread safe. - * @deprecated - */ - @Deprecated - protected Transform _transformObject = null; - /** - * Set the transform object. - * Depeprecated For API compatibility. - * @param transform the Transform - * @deprecated - */ - @Deprecated - protected void setTransform(Transform transform) { - this._transformObject = transform; - } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * * @param input {@link XMLSignatureInput} as the input of transformation * @param os where to output this transformation. - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -68,22 +55,21 @@ * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, OutputStream os, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - return enginePerformTransform(input, _transformObject); + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + throw new UnsupportedOperationException(); } + /** * The mega method which MUST be implemented by the Transformation Algorithm. - * In order to be compatible with preexisting Transform implementations, + * In order to be compatible with preexisting Transform implementations, * by default this implementation invokes the deprecated, thread-unsafe - * methods. Subclasses should override this with a thread-safe + * methods. Subclasses should override this with a thread-safe * implementation. - * + * * @param input {@link XMLSignatureInput} as the input of transformation - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -93,26 +79,14 @@ * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - //Default implementation overide with a much better - try { - TransformSpi tmp = (TransformSpi) getClass().newInstance(); - tmp.setTransform(_transformObject); - return tmp.enginePerformTransform(input); - } catch (InstantiationException e) { - throw new TransformationException("",e); - } catch (IllegalAccessException e) { - throw new TransformationException("",e); - } + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null, transformObject); } /** * The mega method which MUST be implemented by the Transformation Algorithm. - * @deprecated * @param input {@link XMLSignatureInput} as the input of transformation * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException @@ -122,15 +96,13 @@ * @throws SAXException * @throws TransformationException */ - @Deprecated protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - throw new UnsupportedOperationException(); + XMLSignatureInput input + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null); } + /** * Returns the URI representation of Transformation algorithm * --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java 2013-06-28 11:34:08.297347670 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java 2013-06-28 11:34:08.125353024 -0400 @@ -2,86 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class TransformationException extends XMLSecurityException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor TransformationException - * - */ - public TransformationException() { - super(); - } - - /** - * Constructor TransformationException - * - * @param _msgID - */ - public TransformationException(String _msgID) { - super(_msgID); - } - - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - */ - public TransformationException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - - /** - * Constructor TransformationException - * - * @param _msgID - * @param _originalException - */ - public TransformationException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public TransformationException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor TransformationException + * + */ + public TransformationException() { + super(); + } + + /** + * Constructor TransformationException + * + * @param msgID + */ + public TransformationException(String msgID) { + super(msgID); + } + + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + */ + public TransformationException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * Constructor TransformationException + * + * @param msgID + * @param originalException + */ + public TransformationException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public TransformationException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java 2013-06-28 11:34:08.889329243 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java 2013-06-28 11:34:08.721334472 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms; @@ -38,11 +40,11 @@ import org.w3c.dom.NodeList; /** - * Holder of the {@link com.sun.org.apache.xml.internal.security.transforms.Transform} steps to + * Holder of the {@link com.sun.org.apache.xml.internal.security.transforms.Transform} steps to * be performed on the data. - * The input to the first Transform is the result of dereferencing the + * The input to the first Transform is the result of dereferencing the * URI attribute of the Reference element. - * The output from the last Transform is the input for the + * The output from the last Transform is the input for the * DigestMethod algorithm * * @author Christian Geuer-Pollmann @@ -51,69 +53,77 @@ */ public class Transforms extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(Transforms.class.getName()); /** Canonicalization - Required Canonical XML (omits comments) */ - public static final String TRANSFORM_C14N_OMIT_COMMENTS + public static final String TRANSFORM_C14N_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML with Comments */ - public static final String TRANSFORM_C14N_WITH_COMMENTS + public static final String TRANSFORM_C14N_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + /** Canonicalization - Required Canonical XML 1.1 (omits comments) */ - public static final String TRANSFORM_C14N11_OMIT_COMMENTS + public static final String TRANSFORM_C14N11_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML 1.1 with Comments */ - public static final String TRANSFORM_C14N11_WITH_COMMENTS + public static final String TRANSFORM_C14N11_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS; + /** Canonicalization - Required Exclusive Canonicalization (omits comments) */ - public static final String TRANSFORM_C14N_EXCL_OMIT_COMMENTS + public static final String TRANSFORM_C14N_EXCL_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + /** Canonicalization - Recommended Exclusive Canonicalization with Comments */ - public static final String TRANSFORM_C14N_EXCL_WITH_COMMENTS + public static final String TRANSFORM_C14N_EXCL_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + /** Transform - Optional XSLT */ - public static final String TRANSFORM_XSLT + public static final String TRANSFORM_XSLT = "http://www.w3.org/TR/1999/REC-xslt-19991116"; + /** Transform - Required base64 decoding */ - public static final String TRANSFORM_BASE64_DECODE + public static final String TRANSFORM_BASE64_DECODE = Constants.SignatureSpecNS + "base64"; + /** Transform - Recommended XPath */ - public static final String TRANSFORM_XPATH + public static final String TRANSFORM_XPATH = "http://www.w3.org/TR/1999/REC-xpath-19991116"; + /** Transform - Required Enveloped Signature */ - public static final String TRANSFORM_ENVELOPED_SIGNATURE + public static final String TRANSFORM_ENVELOPED_SIGNATURE = Constants.SignatureSpecNS + "enveloped-signature"; + /** Transform - XPointer */ - public static final String TRANSFORM_XPOINTER + public static final String TRANSFORM_XPOINTER = "http://www.w3.org/TR/2001/WD-xptr-20010108"; - /** Transform - XPath Filter v2.0 */ - public static final String TRANSFORM_XPATH2FILTER04 - = "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Transform - XPath Filter */ - public static final String TRANSFORM_XPATH2FILTER + public static final String TRANSFORM_XPATH2FILTER = "http://www.w3.org/2002/06/xmldsig-filter2"; - /** Transform - XPath Filter CHGP private */ - public static final String TRANSFORM_XPATHFILTERCHGP - = "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Transforms.class.getName()); - Element []transforms; + private Element[] transforms; protected Transforms() { }; + + private boolean secureValidation; /** * Constructs {@link Transforms}. * - * @param doc the {@link Document} in which XMLSignature will + * @param doc the {@link Document} in which XMLSignature will * be placed */ public Transforms(Document doc) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** - * Constructs {@link Transforms} from {@link Element} which is + * Constructs {@link Transforms} from {@link Element} which is * Transforms Element * * @param element is Transforms element @@ -125,40 +135,42 @@ * @throws XMLSignatureException */ public Transforms(Element element, String BaseURI) - throws DOMException, XMLSignatureException, - InvalidTransformException, TransformationException, - XMLSecurityException { - + throws DOMException, XMLSignatureException, InvalidTransformException, + TransformationException, XMLSecurityException { super(element, BaseURI); int numberOfTransformElems = this.getLength(); if (numberOfTransformElems == 0) { - // At least one Transform element must be present. Bad. - Object exArgs[] = { Constants._TAG_TRANSFORM, - Constants._TAG_TRANSFORMS }; + Object exArgs[] = { Constants._TAG_TRANSFORM, Constants._TAG_TRANSFORMS }; throw new TransformationException("xml.WrongContent", exArgs); } } + + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } /** - * Adds the Transform with the specified Transform + * Adds the Transform with the specified Transform * algorithm URI * - * @param transformURI the URI form of transform that indicates which + * @param transformURI the URI form of transform that indicates which * transformation is applied to data * @throws TransformationException */ - public void addTransform(String transformURI) - throws TransformationException { - + public void addTransform(String transformURI) throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI); + Transform transform = new Transform(this.doc, transformURI); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -167,23 +179,22 @@ } /** - * Adds the Transform with the specified Transform + * Adds the Transform with the specified Transform * algorithm URI * - * @param transformURI the URI form of transform that indicates which + * @param transformURI the URI form of transform that indicates which * transformation is applied to data * @param contextElement * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, Element childElement) */ public void addTransform(String transformURI, Element contextElement) - throws TransformationException { - + throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI, contextElement); + Transform transform = new Transform(this.doc, transformURI, contextElement); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -192,20 +203,19 @@ } /** - * Adds the Transform with the specified Transform + * Adds the Transform with the specified Transform * algorithm URI. * - * @param transformURI the URI form of transform that indicates which + * @param transformURI the URI form of transform that indicates which * transformation is applied to data * @param contextNodes * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, NodeList contextNodes) */ public void addTransform(String transformURI, NodeList contextNodes) - throws TransformationException { + throws TransformationException { try { - Transform transform = new Transform(this._doc, transformURI, contextNodes); + Transform transform = new Transform(this.doc, transformURI, contextNodes); this.addTransform(transform); } catch (InvalidTransformException ex) { throw new TransformationException("empty", ex); @@ -218,17 +228,18 @@ * @param transform {@link Transform} object */ private void addTransform(Transform transform) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")"); + } Element transformElement = transform.getElement(); - this._constructionElement.appendChild(transformElement); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(transformElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** - * Applies all included Transforms to xmlSignatureInput and + * Applies all included Transforms to xmlSignatureInput and * returns the result of these transformations. * * @param xmlSignatureInput the input for the Transforms @@ -236,12 +247,13 @@ * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput) throws TransformationException { + XMLSignatureInput xmlSignatureInput + ) throws TransformationException { return performTransforms(xmlSignatureInput, null); } - + /** - * Applies all included Transforms to xmlSignatureInput and + * Applies all included Transforms to xmlSignatureInput and * returns the result of these transformations. * * @param xmlSignatureInput the input for the Transforms @@ -250,21 +262,22 @@ * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput, OutputStream os) - throws TransformationException { - + XMLSignatureInput xmlSignatureInput, OutputStream os + ) throws TransformationException { try { - int last=this.getLength()-1; + int last = this.getLength() - 1; for (int i = 0; i < last; i++) { Transform t = this.item(i); + String uri = t.getURI(); if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + t.getURI() - + " transform"); + log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform"); } + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput); } - if (last>=0) { + if (last >= 0) { Transform t = this.item(last); + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput, os); } @@ -277,19 +290,29 @@ throw new TransformationException("empty", ex); } } + + private void checkSecureValidation(Transform transform) throws TransformationException { + String uri = transform.getURI(); + if (secureValidation && Transforms.TRANSFORM_XSLT.equals(uri)) { + Object exArgs[] = { uri }; + + throw new TransformationException( + "signature.Transform.ForbiddenTransform", exArgs + ); + } + } /** * Return the nonnegative number of transformations. * * @return the number of transformations */ - public int getLength() - { + public int getLength() { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } - return transforms.length; + return transforms.length; } /** @@ -301,13 +324,12 @@ * @throws TransformationException */ public Transform item(int i) throws TransformationException { - try { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } - return new Transform(transforms[i], this._baseURI); + return new Transform(transforms[i], this.baseURI); } catch (XMLSecurityException ex) { throw new TransformationException("empty", ex); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java 2013-06-28 11:34:09.597307206 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java 2013-06-28 11:34:09.425312559 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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.transforms.implementations; - - import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.dtm.DTM; @@ -36,7 +36,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Node; - /** * The 'here()' function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node @@ -56,107 +55,98 @@ */ public class FuncHere extends Function { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * The here function returns a node-set containing the attribute or - * processing instruction node or the parent element of the text node - * that directly bears the XPath expression. This expression results - * in an error if the containing XPath expression does not appear in the - * same XML document against which the XPath expression is being evaluated. - * - * @param xctxt - * @return the xobject - * @throws javax.xml.transform.TransformerException - */ - public XObject execute(XPathContext xctxt) - throws javax.xml.transform.TransformerException { - - Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); - - if (xpathOwnerNode == null) { - return null; - } - - int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); - - int currentNode = xctxt.getCurrentNode(); - DTM dtm = xctxt.getDTM(currentNode); - int docContext = dtm.getDocument(); - - if (DTM.NULL == docContext) { - error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); - } - - { - - // check whether currentNode and the node containing the XPath expression - // are in the same document - Document currentDoc = - XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); - Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); - - if (currentDoc != xpathOwnerDoc) { - throw new TransformerException(I18n - .translate("xpath.funcHere.documentsDiffer")); - } - } - - XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); - NodeSetDTM nodeSet = nodes.mutableNodeset(); - - { - int hereNode = DTM.NULL; - - switch (dtm.getNodeType(xpathOwnerNodeDTM)) { - - case Node.ATTRIBUTE_NODE : { - // returns a node-set containing the attribute - hereNode = xpathOwnerNodeDTM; - - nodeSet.addNode(hereNode); - - break; - } - case Node.PROCESSING_INSTRUCTION_NODE : { - // returns a node-set containing the processing instruction node - hereNode = xpathOwnerNodeDTM; - - nodeSet.addNode(hereNode); - - break; - } - case Node.TEXT_NODE : { - // returns a node-set containing the parent element of the - // text node that directly bears the XPath expression - hereNode = dtm.getParent(xpathOwnerNodeDTM); - - nodeSet.addNode(hereNode); - - break; - } - default : - break; - } - } - - /** $todo$ Do I have to do this detach() call? */ - nodeSet.detach(); - - return nodes; - } - - /** - * No arguments to process, so this does nothing. - * @param vars - * @param globalsSize - */ - @SuppressWarnings("rawtypes") - public void fixupVariables(java.util.Vector vars, int globalsSize) { - - // do nothing - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * The here function returns a node-set containing the attribute or + * processing instruction node or the parent element of the text node + * that directly bears the XPath expression. This expression results + * in an error if the containing XPath expression does not appear in the + * same XML document against which the XPath expression is being evaluated. + * + * @param xctxt + * @return the xobject + * @throws javax.xml.transform.TransformerException + */ + @Override + public XObject execute(XPathContext xctxt) + throws javax.xml.transform.TransformerException { + + Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); + + if (xpathOwnerNode == null) { + return null; + } + + int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); + + int currentNode = xctxt.getCurrentNode(); + DTM dtm = xctxt.getDTM(currentNode); + int docContext = dtm.getDocument(); + + if (DTM.NULL == docContext) { + error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); + } + + { + // check whether currentNode and the node containing the XPath expression + // are in the same document + Document currentDoc = + XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); + Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); + + if (currentDoc != xpathOwnerDoc) { + throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); + } + } + + XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); + NodeSetDTM nodeSet = nodes.mutableNodeset(); + + { + int hereNode = DTM.NULL; + + switch (dtm.getNodeType(xpathOwnerNodeDTM)) { + + case Node.ATTRIBUTE_NODE : + case Node.PROCESSING_INSTRUCTION_NODE : { + // returns a node-set containing the attribute / processing instruction node + hereNode = xpathOwnerNodeDTM; + + nodeSet.addNode(hereNode); + + break; + } + case Node.TEXT_NODE : { + // returns a node-set containing the parent element of the + // text node that directly bears the XPath expression + hereNode = dtm.getParent(xpathOwnerNodeDTM); + + nodeSet.addNode(hereNode); + + break; + } + default : + break; + } + } + + /** $todo$ Do I have to do this detach() call? */ + nodeSet.detach(); + + return nodes; + } + + /** + * No arguments to process, so this does nothing. + * @param vars + * @param globalsSize + */ + @SuppressWarnings("rawtypes") + public void fixupVariables(java.util.Vector vars, int globalsSize) { + // do nothing + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java 2013-06-28 11:34:10.189288779 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java 2013-06-28 11:34:10.025293884 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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.transforms.implementations; - - import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStream; @@ -72,115 +72,106 @@ */ public class TransformBase64Decode extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_BASE64_DECODE; - - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return TransformBase64Decode.implementedTransformURI; - } - - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @inheritDoc - * @throws CanonicalizationException - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, - OutputStream os, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - try { - if (input.isElement()) { - Node el=input.getSubNode(); - if (input.getSubNode().getNodeType()==Node.TEXT_NODE) { - el=el.getParentNode(); - } - StringBuffer sb=new StringBuffer(); - traverseElement((Element)el,sb); - if (os==null) { + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_BASE64_DECODE; + + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return TransformBase64Decode.implementedTransformURI; + } + + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @inheritDoc + * @throws CanonicalizationException + * @throws IOException + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + return enginePerformTransform(input, null, transformObject); + } + + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + try { + if (input.isElement()) { + Node el = input.getSubNode(); + if (input.getSubNode().getNodeType() == Node.TEXT_NODE) { + el = el.getParentNode(); + } + StringBuilder sb = new StringBuilder(); + traverseElement((Element)el, sb); + if (os == null) { + byte[] decodedBytes = Base64.decode(sb.toString()); + return new XMLSignatureInput(decodedBytes); + } + Base64.decode(sb.toString(), os); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + if (input.isOctetStream() || input.isNodeSet()) { + if (os == null) { + byte[] base64Bytes = input.getBytes(); + byte[] decodedBytes = Base64.decode(base64Bytes); + return new XMLSignatureInput(decodedBytes); + } + if (input.isByteArray() || input.isNodeSet()) { + Base64.decode(input.getBytes(), os); + } else { + Base64.decode(new BufferedInputStream(input.getOctetStreamReal()), os); + } + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + try { + //Exceptional case there is current not text case testing this(Before it was a + //a common case). + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document doc = + dbf.newDocumentBuilder().parse(input.getOctetStream()); + + Element rootNode = doc.getDocumentElement(); + StringBuilder sb = new StringBuilder(); + traverseElement(rootNode, sb); byte[] decodedBytes = Base64.decode(sb.toString()); return new XMLSignatureInput(decodedBytes); - } - Base64.decode(sb.toString(),os); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - } - if (input.isOctetStream() || input.isNodeSet()) { - - - if (os==null) { - byte[] base64Bytes = input.getBytes(); - byte[] decodedBytes = Base64.decode(base64Bytes); - return new XMLSignatureInput(decodedBytes); - } - if (input.isByteArray() || input.isNodeSet()) { - Base64.decode(input.getBytes(),os); - } else { - Base64.decode(new BufferedInputStream(input.getOctetStreamReal()) - ,os); - } - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - - } - - try { - // Exceptional case there is current not text case testing this - // (before it was a a common case). - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - Document doc = - dbf.newDocumentBuilder().parse(input.getOctetStream()); - - Element rootNode = doc.getDocumentElement(); - StringBuffer sb = new StringBuffer(); - traverseElement(rootNode,sb); - byte[] decodedBytes = Base64.decode(sb.toString()); - - return new XMLSignatureInput(decodedBytes); - } catch (ParserConfigurationException e) { - throw new TransformationException("c14n.Canonicalizer.Exception",e); - } catch (SAXException e) { - throw new TransformationException("SAX exception", e); - } + } catch (ParserConfigurationException e) { + throw new TransformationException("c14n.Canonicalizer.Exception",e); + } catch (SAXException e) { + throw new TransformationException("SAX exception", e); + } } catch (Base64DecodingException e) { throw new TransformationException("Base64Decoding", e); } - } + } - void traverseElement(org.w3c.dom.Element node,StringBuffer sb) { - Node sibling=node.getFirstChild(); - while (sibling!=null) { - switch (sibling.getNodeType()) { - case Node.ELEMENT_NODE: - traverseElement((Element)sibling,sb); - break; - case Node.TEXT_NODE: - sb.append(((Text)sibling).getData()); + void traverseElement(org.w3c.dom.Element node, StringBuilder sb) { + Node sibling = node.getFirstChild(); + while (sibling != null) { + switch (sibling.getNodeType()) { + case Node.ELEMENT_NODE: + traverseElement((Element)sibling, sb); + break; + case Node.TEXT_NODE: + sb.append(((Text)sibling).getData()); } - sibling=sibling.getNextSibling(); + sibling = sibling.getNextSibling(); } - } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java 2013-06-28 11:34:10.873267488 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java 2013-06-28 11:34:10.689273216 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; @@ -37,39 +39,30 @@ */ public class TransformC14N extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_OMIT_COMMENTS; - - - /** - * @inheritDoc - */ - protected String engineGetURI() { - return TransformC14N.implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + + /** + * @inheritDoc + */ + protected String engineGetURI() { + return TransformC14N.implementedTransformURI; + } + + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { output.setOutputStream(os); - } - return output; - } + } + return output; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java 2013-06-28 11:34:11.441249808 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java 2013-06-28 11:34:11.277254913 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; @@ -41,25 +43,19 @@ return Transforms.TRANSFORM_C14N11_OMIT_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments(); if (os != null) { c14n.setWriter(os); } - byte[] result = null; - result = c14n.engineCanonicalize(input); + byte[] result = null; + result = c14n.engineCanonicalize(input); XMLSignatureInput output = new XMLSignatureInput(result); if (os != null) { output.setOutputStream(os); } - return output; + return output; } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java 2013-06-28 11:34:12.089229638 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java 2013-06-28 11:34:11.921234867 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; @@ -41,27 +43,21 @@ return Transforms.TRANSFORM_C14N11_WITH_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { - + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { + Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments(); if (os != null) { c14n.setWriter(os); } - + byte[] result = null; - result = c14n.engineCanonicalize(input); - XMLSignatureInput output = new XMLSignatureInput(result); + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); if (os != null) { output.setOutputStream(os); } - return output; + return output; } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java 2013-06-28 11:34:12.761208721 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java 2013-06-28 11:34:12.589214075 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; @@ -36,71 +38,59 @@ /** * Class TransformC14NExclusive * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public class TransformC14NExclusive extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; - - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * Method enginePerformTransform - * - * @param input - * @return the transformed of the input - * @throws CanonicalizationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; - - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); - - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); - } - - Canonicalizer20010315ExclOmitComments c14n = - new Canonicalizer20010315ExclOmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; + + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } + + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; + + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); + + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI()).getInclusiveNamespaces(); + } + + Canonicalizer20010315ExclOmitComments c14n = + new Canonicalizer20010315ExclOmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); + + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java 2013-06-28 11:34:13.441187555 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java 2013-06-28 11:34:13.273192785 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; @@ -41,59 +43,54 @@ */ public class TransformC14NExclusiveWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; - - /** - * Method engineGetURI - *@inheritDoc - * - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; - - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); - - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); - } - - Canonicalizer20010315ExclWithComments c14n = - new Canonicalizer20010315ExclWithComments(); - if (os!=null) { - c14n.setWriter( os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - XMLSignatureInput output=new XMLSignatureInput(result); - - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; + + /** + * Method engineGetURI + *@inheritDoc + * + */ + protected String engineGetURI() { + return implementedTransformURI; + } + + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; + + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); + + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI() + ).getInclusiveNamespaces(); + } + + Canonicalizer20010315ExclWithComments c14n = + new Canonicalizer20010315ExclWithComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); + XMLSignatureInput output = new XMLSignatureInput(result); + + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java 2013-06-28 11:34:14.133166015 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java 2013-06-28 11:34:13.961171369 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; @@ -37,37 +39,31 @@ */ public class TransformC14NWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_WITH_COMMENTS; - - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_WITH_COMMENTS; + + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } + + /** @inheritDoc */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments(); - if (os!=null) { - c14n.setWriter( os); + if (os != null) { + c14n.setWriter(os); } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java 2013-06-28 11:34:14.805145099 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java 2013-06-28 11:34:14.621150826 -0400 @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; +import java.io.OutputStream; + 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.transforms.Transform; @@ -39,99 +43,99 @@ */ public class TransformEnvelopedSignature extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_ENVELOPED_SIGNATURE; - - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - - - - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - - Node signatureElement = _transformObject.getElement(); - - - signatureElement = searchSignatureElement(signatureElement); - input.setExcludeNode(signatureElement); - input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); - return input; - - // - - - } - - /** - * @param signatureElement - * @return the node that is the signature - * @throws TransformationException - */ - private static Node searchSignatureElement(Node signatureElement) throws TransformationException { - boolean found=false; - - while (true) { - if ((signatureElement == null) - || (signatureElement.getNodeType() == Node.DOCUMENT_NODE)) { - break; - } - Element el=(Element)signatureElement; - if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) - && - el.getLocalName().equals(Constants._TAG_SIGNATURE)) { - found = true; - break; - } + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_ENVELOPED_SIGNATURE; + + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - signatureElement = signatureElement.getParentNode(); - } + /** + * @inheritDoc + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + + Node signatureElement = transformObject.getElement(); + + signatureElement = searchSignatureElement(signatureElement); + input.setExcludeNode(signatureElement); + input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + return input; + } - if (!found) { - throw new TransformationException( - "envelopedSignatureTransformNotInSignatureElement"); + /** + * @param signatureElement + * @return the node that is the signature + * @throws TransformationException + */ + private static Node searchSignatureElement(Node signatureElement) + throws TransformationException { + boolean found = false; + + while (true) { + if (signatureElement == null + || signatureElement.getNodeType() == Node.DOCUMENT_NODE) { + break; } - return signatureElement; + Element el = (Element) signatureElement; + if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) + && el.getLocalName().equals(Constants._TAG_SIGNATURE)) { + found = true; + break; + } + + signatureElement = signatureElement.getParentNode(); + } + + if (!found) { + throw new TransformationException( + "transform.envelopedSignatureTransformNotInSignatureElement"); + } + return signatureElement; } + static class EnvelopedNodeFilter implements NodeFilter { + Node exclude; + EnvelopedNodeFilter(Node n) { - exclude=n; + exclude = n; } - public int isNodeIncludeDO(Node n, int level) { - if ((n==exclude)) - return -1; - return 1; - } + + public int isNodeIncludeDO(Node n, int level) { + if (n == exclude) { + return -1; + } + return 1; + } + /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node n) { - if ((n==exclude) || XMLUtils.isDescendantOrSelf(exclude,n)) - return -1; - return 1; + if (n == exclude || XMLUtils.isDescendantOrSelf(exclude, n)) { + return -1; + } + return 1; //return !XMLUtils.isDescendantOrSelf(exclude,n); } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java 2013-06-28 11:34:15.413126174 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java 2013-06-28 11:34:15.233131776 -0400 @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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.transforms.implementations; +import java.io.OutputStream; + import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; @@ -29,12 +33,10 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; 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.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.objects.XObject; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -51,118 +53,112 @@ */ public class TransformXPath extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH; - - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - - try { - - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); - - - - Element xpathElement =XMLUtils.selectDsNode( - _transformObject.getElement().getFirstChild(), - Constants._TAG_XPATH,0); - - if (xpathElement == null) { - Object exArgs[] = { "ds:XPath", "Transform" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - Node xpathnode = xpathElement.getChildNodes().item(0); - String str=CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - input.setNeedsToBeExpanded(needsCircunvent(str)); - if (xpathnode == null) { - throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, - "Text must be in ds:Xpath"); - } - - - input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str)); - input.setNodeSet(true); - return input; - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } - } - - /** - * @param str - * @return true if needs to be circunvent for bug. - */ - private boolean needsCircunvent(String str) { - //return true; - //return false; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = Transforms.TRANSFORM_XPATH; + + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } + + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + Element xpathElement = + XMLUtils.selectDsNode( + transformObject.getElement().getFirstChild(), Constants._TAG_XPATH, 0); + + if (xpathElement == null) { + Object exArgs[] = { "ds:XPath", "Transform" }; + + throw new TransformationException("xml.WrongContent", exArgs); + } + Node xpathnode = xpathElement.getChildNodes().item(0); + String str = XMLUtils.getStrFromNode(xpathnode); + input.setNeedsToBeExpanded(needsCircumvent(str)); + if (xpathnode == null) { + throw new DOMException( + DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath" + ); + } + + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance)); + input.setNodeSet(true); + return input; + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } + } + + /** + * @param str + * @return true if needs to be circumvent for bug. + */ + private boolean needsCircumvent(String str) { return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1); } static class XPathNodeFilter implements NodeFilter { - PrefixResolverDefault prefixResolver; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); - Node xpathnode; + + XPathAPI xPathAPI; + Node xpathnode; + Element xpathElement; String str; - XPathNodeFilter(Element xpathElement, - Node xpathnode, String str) { - this.xpathnode=xpathnode; - this.str=str; - prefixResolver =new PrefixResolverDefault(xpathElement); + + XPathNodeFilter(Element xpathElement, Node xpathnode, String str, XPathAPI xPathAPI) { + this.xpathnode = xpathnode; + this.str = str; + this.xpathElement = xpathElement; + this.xPathAPI = xPathAPI; } /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ - public int isNodeInclude(Node currentNode) { - XObject includeInResult; + public int isNodeInclude(Node currentNode) { try { - includeInResult = xPathFuncHereAPI.eval(currentNode, - xpathnode, str,prefixResolver); - if (includeInResult.bool()) - return 1; + boolean include = xPathAPI.evaluate(currentNode, xpathnode, str, xpathElement); + if (include) { + return 1; + } return 0; } catch (TransformerException e) { Object[] eArgs = {currentNode}; - throw new XMLSecurityRuntimeException - ("signature.Transform.node", eArgs, e); + throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e); } catch (Exception e) { - Object[] eArgs = {currentNode, new Short(currentNode.getNodeType())}; - throw new XMLSecurityRuntimeException - ("signature.Transform.nodeAndType",eArgs, e); + Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())}; + throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e); } } + public int isNodeIncludeDO(Node n, int level) { - return isNodeInclude(n); + return isNodeInclude(n); } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java 2013-06-28 11:34:15.993108120 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java 2013-06-28 11:34:15.829113225 -0400 @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; - - import java.io.IOException; +import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -42,9 +42,9 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.transforms.params.XPath2FilterContainer; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -55,254 +55,241 @@ /** * Implements the XML Signature XPath Filter v2.0 * - * @author $Author: mullan $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ public class TransformXPath2Filter extends TransformSpi { - /** {@link java.util.logging} logging facility */ -// static java.util.logging.Logger log = -// java.util.logging.Logger.getLogger( -// TransformXPath2Filter.class.getName()); - - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH2FILTER; - //J- - // contains the type of the filter - - // contains the node set - - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - - - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); - try { - List unionNodes=new ArrayList(); - List substractNodes=new ArrayList(); - List intersectNodes=new ArrayList(); - - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); - - - Element []xpathElements =XMLUtils.selectNodes( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2); - int noOfSteps = xpathElements.length; - - - if (noOfSteps == 0) { - Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - - Document inputDoc = null; - if (input.getSubNode() != null) { - inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); - } - - for (int i = 0; i < noOfSteps; i++) { - Element xpathElement =XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2,i); - XPath2FilterContainer xpathContainer = - XPath2FilterContainer.newInstance(xpathElement, - input.getSourceURI()); - - - NodeList subtreeRoots = xPathFuncHereAPI.selectNodeList(inputDoc, - xpathContainer.getXPathFilterTextNode(), - CachedXPathFuncHereAPI.getStrFromNode(xpathContainer.getXPathFilterTextNode()), - xpathContainer.getElement()); - if (xpathContainer.isIntersect()) { - intersectNodes.add(subtreeRoots); - } else if (xpathContainer.isSubtract()) { - substractNodes.add(subtreeRoots); - } else if (xpathContainer.isUnion()) { - unionNodes.add(subtreeRoots); - } - } - - - input.addNodeFilter(new XPath2NodeFilter(unionNodes, substractNodes, - intersectNodes)); - input.setNodeSet(true); - return input; - } catch (TransformerException ex) { - throw new TransformationException("empty", ex); - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } catch (CanonicalizationException ex) { - throw new TransformationException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new TransformationException("empty", ex); - } catch (XMLSecurityException ex) { - throw new TransformationException("empty", ex); - } catch (SAXException ex) { - throw new TransformationException("empty", ex); - } catch (IOException ex) { - throw new TransformationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new TransformationException("empty", ex); - } - } + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPATH2FILTER; + + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } + + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + List unionNodes = new ArrayList(); + List subtractNodes = new ArrayList(); + List intersectNodes = new ArrayList(); + + Element[] xpathElements = + XMLUtils.selectNodes( + transformObject.getElement().getFirstChild(), + XPath2FilterContainer.XPathFilter2NS, + XPath2FilterContainer._TAG_XPATH2 + ); + if (xpathElements.length == 0) { + Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; + + throw new TransformationException("xml.WrongContent", exArgs); + } + + Document inputDoc = null; + if (input.getSubNode() != null) { + inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + + for (int i = 0; i < xpathElements.length; i++) { + Element xpathElement = xpathElements[i]; + + XPath2FilterContainer xpathContainer = + XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI()); + + String str = + XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode()); + + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + + NodeList subtreeRoots = + xpathAPIInstance.selectNodeList( + inputDoc, + xpathContainer.getXPathFilterTextNode(), + str, + xpathContainer.getElement()); + if (xpathContainer.isIntersect()) { + intersectNodes.add(subtreeRoots); + } else if (xpathContainer.isSubtract()) { + subtractNodes.add(subtreeRoots); + } else if (xpathContainer.isUnion()) { + unionNodes.add(subtreeRoots); + } + } + + input.addNodeFilter( + new XPath2NodeFilter(unionNodes, subtractNodes, intersectNodes) + ); + input.setNodeSet(true); + return input; + } catch (TransformerException ex) { + throw new TransformationException("empty", ex); + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } catch (CanonicalizationException ex) { + throw new TransformationException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new TransformationException("empty", ex); + } catch (XMLSecurityException ex) { + throw new TransformationException("empty", ex); + } catch (SAXException ex) { + throw new TransformationException("empty", ex); + } catch (IOException ex) { + throw new TransformationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new TransformationException("empty", ex); + } + } } class XPath2NodeFilter implements NodeFilter { - boolean hasUnionFilter; - boolean hasSubstractFilter; - boolean hasIntersectFilter; - XPath2NodeFilter(List unionNodes, List substractNodes, - List intersectNodes) { - hasUnionFilter=!unionNodes.isEmpty(); - this.unionNodes=convertNodeListToSet(unionNodes); - hasSubstractFilter=!substractNodes.isEmpty(); - this.substractNodes=convertNodeListToSet(substractNodes); - hasIntersectFilter=!intersectNodes.isEmpty(); - this.intersectNodes=convertNodeListToSet(intersectNodes); - } - Set unionNodes; - Set substractNodes; - Set intersectNodes; - - - /** - * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) - */ - public int isNodeInclude(Node currentNode) { - int result=1; - - if (hasSubstractFilter && rooted(currentNode, substractNodes)) { - result = -1; - } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { - result = 0; - } - - //TODO OPTIMIZE - if (result==1) - return 1; - if (hasUnionFilter) { - if (rooted(currentNode, unionNodes)) { - return 1; - } - result=0; - } - return result; - - } - int inSubstract=-1; - int inIntersect=-1; - int inUnion=-1; - public int isNodeIncludeDO(Node n, int level) { - int result=1; - if (hasSubstractFilter) { - if ((inSubstract==-1) || (level<=inSubstract)) { - if (inList(n, substractNodes)) { - inSubstract=level; - } else { - inSubstract=-1; - } - } - if (inSubstract!=-1){ - result=-1; - } - } - if (result!=-1){ - if (hasIntersectFilter) { - if ((inIntersect==-1) || (level<=inIntersect)) { - if (!inList(n, intersectNodes)) { - inIntersect=-1; - result=0; - } else { - inIntersect=level; - } - } - } - } - - if (level<=inUnion) - inUnion=-1; - if (result==1) - return 1; - if (hasUnionFilter) { - if ((inUnion==-1) && inList(n, unionNodes)) { - inUnion=level; - } - if (inUnion!=-1) - return 1; - result=0; - } - - return result; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean rooted(Node currentNode, Set nodeList ) { - if (nodeList.isEmpty()) { - return false; - } - if (nodeList.contains(currentNode)) { - return true; - } - - for(Node rootNode : nodeList) { - if (XMLUtils.isDescendantOrSelf(rootNode,currentNode)) { - return true; - } - } - return false; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean inList(Node currentNode, Set nodeList ) { - return nodeList.contains(currentNode); - } + + boolean hasUnionFilter; + boolean hasSubtractFilter; + boolean hasIntersectFilter; + Set unionNodes; + Set subtractNodes; + Set intersectNodes; + int inSubtract = -1; + int inIntersect = -1; + int inUnion = -1; + + XPath2NodeFilter(List unionNodes, List subtractNodes, + List intersectNodes) { + hasUnionFilter = !unionNodes.isEmpty(); + this.unionNodes = convertNodeListToSet(unionNodes); + hasSubtractFilter = !subtractNodes.isEmpty(); + this.subtractNodes = convertNodeListToSet(subtractNodes); + hasIntersectFilter = !intersectNodes.isEmpty(); + this.intersectNodes = convertNodeListToSet(intersectNodes); + } + + /** + * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) + */ + public int isNodeInclude(Node currentNode) { + int result = 1; + + if (hasSubtractFilter && rooted(currentNode, subtractNodes)) { + result = -1; + } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { + result = 0; + } + + //TODO OPTIMIZE + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if (rooted(currentNode, unionNodes)) { + return 1; + } + result = 0; + } + return result; + } + + public int isNodeIncludeDO(Node n, int level) { + int result = 1; + if (hasSubtractFilter) { + if ((inSubtract == -1) || (level <= inSubtract)) { + if (inList(n, subtractNodes)) { + inSubtract = level; + } else { + inSubtract = -1; + } + } + if (inSubtract != -1){ + result = -1; + } + } + if (result != -1 && hasIntersectFilter + && ((inIntersect == -1) || (level <= inIntersect))) { + if (!inList(n, intersectNodes)) { + inIntersect = -1; + result = 0; + } else { + inIntersect = level; + } + } + + if (level <= inUnion) { + inUnion = -1; + } + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if ((inUnion == -1) && inList(n, unionNodes)) { + inUnion = level; + } + if (inUnion != -1) { + return 1; + } + result=0; + } - private static Set convertNodeListToSet(List l){ - Set result=new HashSet(); + return result; + } + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean rooted(Node currentNode, Set nodeList) { + if (nodeList.isEmpty()) { + return false; + } + if (nodeList.contains(currentNode)) { + return true; + } + for (Node rootNode : nodeList) { + if (XMLUtils.isDescendantOrSelf(rootNode, currentNode)) { + return true; + } + } + return false; + } + + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean inList(Node currentNode, Set nodeList) { + return nodeList.contains(currentNode); + } + + private static Set convertNodeListToSet(List l) { + Set result = new HashSet(); for (NodeList rootNodes : l) { - int length = rootNodes.getLength(); - for (int i = 0; i < length; i++) { - Node rootNode = rootNodes.item(i); - result.add(rootNode); - } + int length = rootNodes.getLength(); + + for (int i = 0; i < length; i++) { + Node rootNode = rootNodes.item(i); + result.add(rootNode); + } } return result; } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java 2013-06-28 11:34:16.625088448 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java 2013-06-28 11:34:16.445094051 -0400 @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.implementations; - - +import java.io.OutputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -29,8 +30,6 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; - - /** * Class TransformXPointer * @@ -38,30 +37,29 @@ */ public class TransformXPointer extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPOINTER; - - - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @throws TransformationException - * - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - - Object exArgs[] = { implementedTransformURI }; - - throw new TransformationException( - "signature.Transform.NotYetImplemented", exArgs); - } + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPOINTER; + + + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } + + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + + Object exArgs[] = { implementedTransformURI }; + + throw new TransformationException("signature.Transform.NotYetImplemented", exArgs); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java 2013-06-28 11:34:17.265068528 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java 2013-06-28 11:34:17.097073756 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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.transforms.implementations; @@ -24,7 +26,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.lang.reflect.Method; import javax.xml.XMLConstants; import javax.xml.transform.Source; @@ -55,132 +56,112 @@ */ public class TransformXSLT extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XSLT; - //J- - static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; - static final String defaultXSLTSpecNSprefix = "xslt"; - static final String XSLTSTYLESHEET = "stylesheet"; - - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - TransformXSLT.class.getName()); - - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * Method enginePerformTransform - * - * @param input the input for this transform - * @return the result of this Transform - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject) - throws IOException, - TransformationException { - try { - Element transformElement = _transformObject.getElement(); - - Element _xsltElement = - XMLUtils.selectNode(transformElement.getFirstChild(), - XSLTSpecNS,"stylesheet", 0); - - if (_xsltElement == null) { - Object exArgs[] = { "xslt:stylesheet", "Transform" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - - TransformerFactory tFactory = TransformerFactory.newInstance(); - - // Process XSLT stylesheets in a secure manner - tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - /* - * This transform requires an octet stream as input. If the actual - * input is an XPath node-set, then the signature application should - * attempt to convert it to octets (apply Canonical XML]) as described - * in the Reference Processing Model (section 4.3.3.2). - */ - Source xmlSource = - new StreamSource(new ByteArrayInputStream(input.getBytes())); - Source stylesheet; - - /* - * This complicated transformation of the stylesheet itself is necessary - * because of the need to get the pure style sheet. If we simply say - * Source stylesheet = new DOMSource(this._xsltElement); - * whereby this._xsltElement is not the rootElement of the Document, - * this causes problems; - * so we convert the stylesheet to byte[] and use this as input stream - */ - { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Transformer transformer = tFactory.newTransformer(); - DOMSource source = new DOMSource(_xsltElement); - StreamResult result = new StreamResult(os); - - transformer.transform(source, result); - - stylesheet = - new StreamSource(new ByteArrayInputStream(os.toByteArray())); - } - - Transformer transformer = tFactory.newTransformer(stylesheet); - - // Force Xalan to use \n as line separator on all OSes. This - // avoids OS specific signature validation failures due to line - // separator differences in the transformed output. Unfortunately, - // this is not a standard JAXP property so will not work with non-Xalan - // implementations. - try { - transformer.setOutputProperty - ("{http://xml.apache.org/xalan}line-separator", "\n"); - } catch (Exception e) { - log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " - + e.getMessage()); - } - - if (baos==null) { - ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); - StreamResult outputTarget = new StreamResult(baos1); - transformer.transform(xmlSource, outputTarget); - return new XMLSignatureInput(baos1.toByteArray()); - } - StreamResult outputTarget = new StreamResult(baos); - - transformer.transform(xmlSource, outputTarget); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(baos); - return output; - } catch (XMLSecurityException ex) { - Object exArgs[] = { ex.getMessage() }; - - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerConfigurationException ex) { - Object exArgs[] = { ex.getMessage() }; - - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerException ex) { - Object exArgs[] = { ex.getMessage() }; - - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } - } + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XSLT; + + static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; + static final String defaultXSLTSpecNSprefix = "xslt"; + static final String XSLTSTYLESHEET = "stylesheet"; + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(TransformXSLT.class.getName()); + + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } + + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream baos, Transform transformObject + ) throws IOException, TransformationException { + try { + Element transformElement = transformObject.getElement(); + + Element xsltElement = + XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0); + + if (xsltElement == null) { + Object exArgs[] = { "xslt:stylesheet", "Transform" }; + + throw new TransformationException("xml.WrongContent", exArgs); + } + + TransformerFactory tFactory = TransformerFactory.newInstance(); + // Process XSLT stylesheets in a secure manner + tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + + /* + * This transform requires an octet stream as input. If the actual + * input is an XPath node-set, then the signature application should + * attempt to convert it to octets (apply Canonical XML]) as described + * in the Reference Processing Model (section 4.3.3.2). + */ + Source xmlSource = + new StreamSource(new ByteArrayInputStream(input.getBytes())); + Source stylesheet; + + /* + * This complicated transformation of the stylesheet itself is necessary + * because of the need to get the pure style sheet. If we simply say + * Source stylesheet = new DOMSource(this.xsltElement); + * whereby this.xsltElement is not the rootElement of the Document, + * this causes problems; + * so we convert the stylesheet to byte[] and use this as input stream + */ + { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Transformer transformer = tFactory.newTransformer(); + DOMSource source = new DOMSource(xsltElement); + StreamResult result = new StreamResult(os); + + transformer.transform(source, result); + + stylesheet = + new StreamSource(new ByteArrayInputStream(os.toByteArray())); + } + + Transformer transformer = tFactory.newTransformer(stylesheet); + + // Force Xalan to use \n as line separator on all OSes. This + // avoids OS specific signature validation failures due to line + // separator differences in the transformed output. Unfortunately, + // this is not a standard JAXP property so will not work with non-Xalan + // implementations. + try { + transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n"); + } catch (Exception e) { + log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " + e.getMessage()); + } + + if (baos == null) { + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + StreamResult outputTarget = new StreamResult(baos1); + transformer.transform(xmlSource, outputTarget); + return new XMLSignatureInput(baos1.toByteArray()); + } + StreamResult outputTarget = new StreamResult(baos); + + transformer.transform(xmlSource, outputTarget); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(baos); + return output; + } catch (XMLSecurityException ex) { + Object exArgs[] = { ex.getMessage() }; + + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerConfigurationException ex) { + Object exArgs[] = { ex.getMessage() }; + + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerException ex) { + Object exArgs[] = { ex.getMessage() }; + + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java 2013-06-28 11:34:17.929047859 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java 2013-06-28 11:34:17.765052964 -0400 @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.params; - - -import java.util.Iterator; import java.util.Set; import java.util.SortedSet; -import java.util.StringTokenizer; import java.util.TreeSet; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -34,7 +32,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This Object serves as Content for the ds:Transforms for exclusive * Canonicalization. @@ -44,136 +41,130 @@ * * @author Christian Geuer-Pollmann */ -public class InclusiveNamespaces extends ElementProxy - implements TransformParam { +public class InclusiveNamespaces extends ElementProxy implements TransformParam { - /** Field _TAG_EC_INCLUSIVENAMESPACES */ - public static final String _TAG_EC_INCLUSIVENAMESPACES = - "InclusiveNamespaces"; - - /** Field _ATT_EC_PREFIXLIST */ - public static final String _ATT_EC_PREFIXLIST = "PrefixList"; - - /** Field ExclusiveCanonicalizationNamespace */ - public static final String ExclusiveCanonicalizationNamespace = - "http://www.w3.org/2001/10/xml-exc-c14n#"; - - /** - * Constructor XPathContainer - * - * @param doc - * @param prefixList - */ - public InclusiveNamespaces(Document doc, String prefixList) { - this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); - } - - /** - * Constructor InclusiveNamespaces - * - * @param doc - * @param prefixes - */ - public InclusiveNamespaces(Document doc, Set prefixes) { - - super(doc); - - StringBuffer sb = new StringBuffer(); - SortedSet prefixList = new TreeSet(prefixes); - - - - for (String prefix : prefixList) { - if (prefix.equals("xmlns")) { - sb.append("#default "); - } else { - sb.append(prefix + " "); - } - } - - this._constructionElement - .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST, - sb.toString().trim()); - } - - /** - * Method getInclusiveNamespaces - * - * @return The Inclusive Namespace string - */ - public String getInclusiveNamespaces() { - return this._constructionElement - .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); - } - - /** - * Constructor InclusiveNamespaces - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public InclusiveNamespaces(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Decodes the inclusiveNamespaces String and returns all - * selected namespace prefixes as a Set. The #default - * namespace token is represented as an empty namespace prefix - * ("xmlns"). - *
      - * The String inclusiveNamespaces=" xenc ds #default" - * is returned as a Set containing the following Strings: - *
        - *
      • xmlns
      • - *
      • xenc
      • - *
      • ds
      • - *
      - * - * @param inclusiveNamespaces - * @return A set to string - */ - public static SortedSet prefixStr2Set(String inclusiveNamespaces) { - - SortedSet prefixes = new TreeSet(); - - if ((inclusiveNamespaces == null) - || (inclusiveNamespaces.length() == 0)) { - return prefixes; - } - - StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n"); - - while (st.hasMoreTokens()) { - String prefix = st.nextToken(); - - if (prefix.equals("#default")) { - prefixes.add("xmlns" ); - } else { - prefixes.add( prefix); - } - } - - return prefixes; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public String getBaseNamespace() { - return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; - } + /** Field _TAG_EC_INCLUSIVENAMESPACES */ + public static final String _TAG_EC_INCLUSIVENAMESPACES = + "InclusiveNamespaces"; + + /** Field _ATT_EC_PREFIXLIST */ + public static final String _ATT_EC_PREFIXLIST = "PrefixList"; + + /** Field ExclusiveCanonicalizationNamespace */ + public static final String ExclusiveCanonicalizationNamespace = + "http://www.w3.org/2001/10/xml-exc-c14n#"; + + /** + * Constructor XPathContainer + * + * @param doc + * @param prefixList + */ + public InclusiveNamespaces(Document doc, String prefixList) { + this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); + } + + /** + * Constructor InclusiveNamespaces + * + * @param doc + * @param prefixes + */ + public InclusiveNamespaces(Document doc, Set prefixes) { + super(doc); + + SortedSet prefixList = null; + if (prefixes instanceof SortedSet) { + prefixList = (SortedSet)prefixes; + } else { + prefixList = new TreeSet(prefixes); + } + + StringBuilder sb = new StringBuilder(); + for (String prefix : prefixList) { + if (prefix.equals("xmlns")) { + sb.append("#default "); + } else { + sb.append(prefix + " "); + } + } + + this.constructionElement.setAttributeNS( + null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim()); + } + + /** + * Constructor InclusiveNamespaces + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public InclusiveNamespaces(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Method getInclusiveNamespaces + * + * @return The Inclusive Namespace string + */ + public String getInclusiveNamespaces() { + return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); + } + + /** + * Decodes the inclusiveNamespaces String and returns all + * selected namespace prefixes as a Set. The #default + * namespace token is represented as an empty namespace prefix + * ("xmlns"). + *
      + * The String inclusiveNamespaces=" xenc ds #default" + * is returned as a Set containing the following Strings: + *
        + *
      • xmlns
      • + *
      • xenc
      • + *
      • ds
      • + *
      + * + * @param inclusiveNamespaces + * @return A set to string + */ + public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + SortedSet prefixes = new TreeSet(); + + if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) { + return prefixes; + } + + String[] tokens = inclusiveNamespaces.split("\\s"); + for (String prefix : tokens) { + if (prefix.equals("#default")) { + prefixes.add("xmlns"); + } else { + prefixes.add(prefix); + } + } + + return prefixes; + } + + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public String getBaseNamespace() { + return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; + } + + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java 2013-06-28 11:34:18.561028188 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java 2013-06-28 11:34:18.393033416 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -32,284 +32,261 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; - - /** Field INTERSECT */ - public static final String INTERSECT = - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; - - /** Field SUBTRACT */ - public static final String SUBTRACT = - XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; - - /** Field UNION */ - public static final String UNION = - XPath2FilterContainer._ATT_FILTER_VALUE_UNION; - - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; - - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/06/xmldsig-filter2"; - - /** - * Constructor XPath2FilterContainer - * - */ - private XPath2FilterContainer() { - - // no instantiation - } - - /** - * Constructor XPath2FilterContainer - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer(Document doc, String xpath2filter, - String filterType) { - - super(doc); - - this._constructionElement - .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - } - - /** - * Constructor XPath2FilterContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer(Element element, String BaseURI) - throws XMLSecurityException { - - super(element, BaseURI); - - String filterStr = this._constructionElement.getAttributeNS(null, - XPath2FilterContainer._ATT_FILTER); - - if (!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; - - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } - - /** - * Creates a new XPath2FilterContainer with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceIntersect(Document doc, - String xpath2filter) { - - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT); - } - - /** - * Creates a new XPath2FilterContainer with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceSubtract(Document doc, - String xpath2filter) { - - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Creates a new XPath2FilterContainer with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the filter - */ - public static XPath2FilterContainer newInstanceUnion(Document doc, - String xpath2filter) { - - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION); - } - - /** - * Method newInstances - * - * @param doc - * @param params - * @return the nodelist with the data - */ - public static NodeList newInstances(Document doc, String[][] params) { - - HelperNodeList nl = new HelperNodeList(); - - XMLUtils.addReturnToElement(doc, nl); - - for (int i = 0; i < params.length; i++) { - String type = params[i][0]; - String xpath = params[i][1]; - - if (!(type.equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION))) { - throw new IllegalArgumentException("The type(" + i + ")=\"" + type - + "\" is illegal"); - } - - XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); - - nl.appendChild(c.getElement()); - XMLUtils.addReturnToElement(doc, nl); - } - - return nl; - } - - /** - * Creates a XPath2FilterContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the filter - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer(element, BaseURI); - } - - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); - } - - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** - * Method getBaseLocalName - * - * @return the XPATH2 tag - */ - public final String getBaseLocalName() { - return XPath2FilterContainer._TAG_XPATH2; - } - - /** - * Method getBaseNamespace - * - * @return XPATH2 tag namespace - */ - public final String getBaseNamespace() { - return XPath2FilterContainer.XPathFilter2NS; - } + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; + + /** Field INTERSECT */ + public static final String INTERSECT = + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; + + /** Field SUBTRACT */ + public static final String SUBTRACT = + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; + + /** Field UNION */ + public static final String UNION = + XPath2FilterContainer._ATT_FILTER_VALUE_UNION; + + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; + + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/06/xmldsig-filter2"; + + /** + * Constructor XPath2FilterContainer + * + */ + private XPath2FilterContainer() { + // no instantiation + } + + /** + * Constructor XPath2FilterContainer + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) { + super(doc); + + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer._ATT_FILTER, filterType); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } + + /** + * Constructor XPath2FilterContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException { + + super(element, BaseURI); + + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER); + + if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; + + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } + + /** + * Creates a new XPath2FilterContainer with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } + + /** + * Creates a new XPath2FilterContainer with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceSubtract(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } + + /** + * Creates a new XPath2FilterContainer with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the filter + */ + public static XPath2FilterContainer newInstanceUnion(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } + + /** + * Method newInstances + * + * @param doc + * @param params + * @return the nodelist with the data + */ + public static NodeList newInstances(Document doc, String[][] params) { + HelperNodeList nl = new HelperNodeList(); + + XMLUtils.addReturnToElement(doc, nl); + + for (int i = 0; i < params.length; i++) { + String type = params[i][0]; + String xpath = params[i][1]; + + if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))) { + throw new IllegalArgumentException("The type(" + i + ")=\"" + type + + "\" is illegal"); + } + + XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); + + nl.appendChild(c.getElement()); + XMLUtils.addReturnToElement(doc, nl); + } + + return nl; + } + + /** + * Creates a XPath2FilterContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the filter + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer(element, BaseURI); + } + + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } + + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } + + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } + + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } + + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { + + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); + + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } + + return null; + } + + /** + * Method getBaseLocalName + * + * @return the XPATH2 tag + */ + public final String getBaseLocalName() { + return XPath2FilterContainer._TAG_XPATH2; + } + + /** + * Method getBaseNamespace + * + * @return XPATH2 tag namespace + */ + public final String getBaseNamespace() { + return XPath2FilterContainer.XPathFilter2NS; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java 2013-06-28 11:34:19.193008516 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java 2013-06-28 11:34:19.025013744 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -31,237 +31,222 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer04 extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer04 extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; - - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; - - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/04/xmldsig-filter2"; - - /** - * Constructor XPath2FilterContainer04 - * - */ - private XPath2FilterContainer04() { - - // no instantiation - } - - /** - * Constructor XPath2FilterContainer04 - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer04(Document doc, String xpath2filter, - String filterType) { - - super(doc); - - this._constructionElement.setAttributeNS(null, XPath2FilterContainer04._ATT_FILTER, - filterType); - - if ((xpath2filter.length() > 2) - && (!Character.isWhitespace(xpath2filter.charAt(0)))) { - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - XMLUtils.addReturnToElement(this._constructionElement); - } else { - this._constructionElement - .appendChild(doc.createTextNode(xpath2filter)); - } - } - - /** - * Constructor XPath2FilterContainer04 - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer04(Element element, String BaseURI) - throws XMLSecurityException { - - super(element, BaseURI); - - String filterStr = - this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); - - if (!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, - XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; - - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } - - /** - * Creates a new XPath2FilterContainer04 with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceIntersect(Document doc, - String xpath2filter) { - - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT); - } - - /** - * Creates a new XPath2FilterContainer04 with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceSubtract(Document doc, - String xpath2filter) { - - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Creates a new XPath2FilterContainer04 with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceUnion(Document doc, - String xpath2filter) { - - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_UNION); - } - - /** - * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the instance - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer04 newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer04(element, BaseURI); - } - - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); - } - - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** @inheritDoc */ - public final String getBaseLocalName() { - return XPath2FilterContainer04._TAG_XPATH2; - } - - /** @inheritDoc */ - public final String getBaseNamespace() { - return XPath2FilterContainer04.XPathFilter2NS; - } + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; + + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; + + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/04/xmldsig-filter2"; + + /** + * Constructor XPath2FilterContainer04 + * + */ + private XPath2FilterContainer04() { + + // no instantiation + } + + /** + * Constructor XPath2FilterContainer04 + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) { + super(doc); + + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER, filterType); + + if ((xpath2filter.length() > 2) + && (!Character.isWhitespace(xpath2filter.charAt(0)))) { + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + XMLUtils.addReturnToElement(this.constructionElement); + } else { + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } + } + + /** + * Constructor XPath2FilterContainer04 + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer04(Element element, String BaseURI) + throws XMLSecurityException { + + super(element, BaseURI); + + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); + + if (!filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, + XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; + + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } + + /** + * Creates a new XPath2FilterContainer04 with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } + + /** + * Creates a new XPath2FilterContainer04 with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceSubtract( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } + + /** + * Creates a new XPath2FilterContainer04 with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceUnion( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } + + /** + * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the instance + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer04 newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer04(element, BaseURI); + } + + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } + + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } + + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } + + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } + + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); + + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } + + return null; + } + + /** @inheritDoc */ + public final String getBaseLocalName() { + return XPath2FilterContainer04._TAG_XPATH2; + } + + /** @inheritDoc */ + public final String getBaseNamespace() { + return XPath2FilterContainer04.XPathFilter2NS; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java 2013-06-28 11:34:19.888986851 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java 2013-06-28 11:34:19.716992205 -0400 @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.params; - import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; @@ -29,7 +30,6 @@ import org.w3c.dom.NodeList; import org.w3c.dom.Text; - /** * This Object serves both as namespace prefix resolver and as container for * the ds:XPath Element. It implements the {@link org.w3c.dom.Element} interface @@ -39,45 +39,44 @@ */ public class XPathContainer extends SignatureElementProxy implements TransformParam { - /** - * Constructor XPathContainer - * - * @param doc - */ - public XPathContainer(Document doc) { - super(doc); - } - - /** - * Sets the TEXT value of the ds:XPath Element. - * - * @param xpath - */ - public void setXPath(String xpath) { - - if (this._constructionElement.getChildNodes() != null) { - NodeList nl = this._constructionElement.getChildNodes(); - - for (int i = 0; i < nl.getLength(); i++) { - this._constructionElement.removeChild(nl.item(i)); - } - } - - Text xpathText = this._doc.createTextNode(xpath); - this._constructionElement.appendChild(xpathText); - } - - /** - * Returns the TEXT value of the ds:XPath Element. - * - * @return the TEXT value of the ds:XPath Element. - */ - public String getXPath() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_XPATH; - } + /** + * Constructor XPathContainer + * + * @param doc + */ + public XPathContainer(Document doc) { + super(doc); + } + + /** + * Sets the TEXT value of the ds:XPath Element. + * + * @param xpath + */ + public void setXPath(String xpath) { + if (this.constructionElement.getChildNodes() != null) { + NodeList nl = this.constructionElement.getChildNodes(); + + for (int i = 0; i < nl.getLength(); i++) { + this.constructionElement.removeChild(nl.item(i)); + } + } + + Text xpathText = this.doc.createTextNode(xpath); + this.constructionElement.appendChild(xpathText); + } + + /** + * Returns the TEXT value of the ds:XPath Element. + * + * @return the TEXT value of the ds:XPath Element. + */ + public String getXPath() { + return this.getTextFromTextChild(); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_XPATH; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java 2013-06-28 11:34:20.504967677 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java 2013-06-28 11:34:20.328973155 -0400 @@ -2,320 +2,315 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.transforms.params; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; -import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; 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; - /** * Implements the parameters for a custom Transform which has a better performance - * thatn the xfilter2. + * than the xfilter2. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XPathFilterCHGPContainer extends ElementProxy - implements TransformParam { +public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; + public static final String TRANSFORM_XPATHFILTERCHGP = + "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _TAG_EXCLUDE = "Exclude"; - - /** Field _TAG_XPATHCHGP */ - public static final String _TAG_XPATHCHGP = "XPathAlternative"; - - /** Field _ATT_INCLUDESLASH */ - public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; - - /** Field IncludeSlash */ - public static final boolean IncludeSlash = true; - - /** Field ExcludeSlash */ - public static final boolean ExcludeSlash = false; - - /** - * Constructor XPathFilterCHGPContainer - * - */ - private XPathFilterCHGPContainer() { - - // no instantiation - } - - /** - * Constructor XPathFilterCHGPContainer - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - */ - private XPathFilterCHGPContainer(Document doc, boolean includeSlashPolicy, - String includeButSearch, - String excludeButSearch, String exclude) { - - super(doc); - - if (includeSlashPolicy) { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"); - } else { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"); - } - - if ((includeButSearch != null) - && (includeButSearch.trim().length() > 0)) { - Element includeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_INCLUDE_BUT_SEARCH); - - includeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(includeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(includeButSearchElem); - } - - if ((excludeButSearch != null) - && (excludeButSearch.trim().length() > 0)) { - Element excludeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_EXCLUDE_BUT_SEARCH); - - excludeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(excludeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeButSearchElem); - } - - if ((exclude != null) && (exclude.trim().length() > 0)) { - Element excludeElem = ElementProxy.createElementForFamily(doc, - this.getBaseNamespace(), - XPathFilterCHGPContainer._TAG_EXCLUDE); - - excludeElem - .appendChild(this._doc.createTextNode(indentXPathText(exclude))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeElem); - } - - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method indentXPathText - * - * @param xp - * @return the string with enters - */ - static String indentXPathText(String xp) { - - if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { - return "\n" + xp + "\n"; - } - return xp; - - } - - /** - * Constructor XPathFilterCHGPContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPathFilterCHGPContainer(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** - * Creates a new XPathFilterCHGPContainer; needed for generation. - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - * @return the created object - */ - public static XPathFilterCHGPContainer getInstance(Document doc, - boolean includeSlashPolicy, String includeButSearch, - String excludeButSearch, String exclude) { - - return new XPathFilterCHGPContainer(doc, includeSlashPolicy, - includeButSearch, excludeButSearch, - exclude); - } - - /** - * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * - * @throws XMLSecurityException - * @return the created object. - */ - public static XPathFilterCHGPContainer getInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPathFilterCHGPContainer(element, BaseURI); - } - - /** - * Method getXStr - * - * @param type - * @return The Xstr - */ - private String getXStr(String type) { - - if (this.length(this.getBaseNamespace(), type) != 1) { - return ""; - } - - Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); - - return XMLUtils.getFullTextChildrenFromElement(xElem); - } - - /** - * Method getIncludeButSearch - * - * @return the string - */ - public String getIncludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } - - /** - * Method getExcludeButSearch - * - * @return the string - */ - public String getExcludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } - - /** - * Method getExclude - * - * @return the string - */ - public String getExclude() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); - } - - /** - * Method getIncludeSlashPolicy - * - * @return the string - */ - public boolean getIncludeSlashPolicy() { - - return this._constructionElement - .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH) - .equals("true"); - } - - /** - * Returns the first Text node which contains information from the XPath - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @param type - * @return the first Text node which contains information from the XPath 2 Filter String - */ - private Node getHereContextNode(String type) { - - if (this.length(this.getBaseNamespace(), type) != 1) { - return null; - } - - return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); - } - - /** - * Method getHereContextNodeIncludeButSearch - * - * @return the string - */ - public Node getHereContextNodeIncludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExcludeButSearch - * - * @return the string - */ - public Node getHereContextNodeExcludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExclude - * - * @return the string - */ - public Node getHereContextNodeExclude() { - return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public final String getBaseLocalName() { - return XPathFilterCHGPContainer._TAG_XPATHCHGP; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public final String getBaseNamespace() { - return Transforms.TRANSFORM_XPATHFILTERCHGP; - } + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; + + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _TAG_EXCLUDE = "Exclude"; + + /** Field _TAG_XPATHCHGP */ + public static final String _TAG_XPATHCHGP = "XPathAlternative"; + + /** Field _ATT_INCLUDESLASH */ + public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; + + /** Field IncludeSlash */ + public static final boolean IncludeSlash = true; + + /** Field ExcludeSlash */ + public static final boolean ExcludeSlash = false; + + /** + * Constructor XPathFilterCHGPContainer + * + */ + private XPathFilterCHGPContainer() { + // no instantiation + } + + /** + * Constructor XPathFilterCHGPContainer + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + */ + private XPathFilterCHGPContainer( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + super(doc); + + if (includeSlashPolicy) { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true" + ); + } else { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false" + ); + } + + if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) { + Element includeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH + ); + + includeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(includeButSearch)) + ); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(includeButSearchElem); + } + + if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) { + Element excludeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH + ); + + excludeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(excludeButSearch))); + + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeButSearchElem); + } + + if ((exclude != null) && (exclude.trim().length() > 0)) { + Element excludeElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE); + + excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude))); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeElem); + } + + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method indentXPathText + * + * @param xp + * @return the string with enters + */ + static String indentXPathText(String xp) { + if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { + return "\n" + xp + "\n"; + } + return xp; + } + + /** + * Constructor XPathFilterCHGPContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPathFilterCHGPContainer(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Creates a new XPathFilterCHGPContainer; needed for generation. + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + * @return the created object + */ + public static XPathFilterCHGPContainer getInstance( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + return new XPathFilterCHGPContainer( + doc, includeSlashPolicy, includeButSearch, excludeButSearch, exclude); + } + + /** + * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * + * @throws XMLSecurityException + * @return the created object. + */ + public static XPathFilterCHGPContainer getInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPathFilterCHGPContainer(element, BaseURI); + } + + /** + * Method getXStr + * + * @param type + * @return The Xstr + */ + private String getXStr(String type) { + if (this.length(this.getBaseNamespace(), type) != 1) { + return ""; + } + + Element xElem = + XMLUtils.selectNode( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); + + return XMLUtils.getFullTextChildrenFromElement(xElem); + } + + /** + * Method getIncludeButSearch + * + * @return the string + */ + public String getIncludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } + + /** + * Method getExcludeButSearch + * + * @return the string + */ + public String getExcludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } + + /** + * Method getExclude + * + * @return the string + */ + public String getExclude() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); + } + + /** + * Method getIncludeSlashPolicy + * + * @return the string + */ + public boolean getIncludeSlashPolicy() { + return this.constructionElement.getAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true"); + } + + /** + * Returns the first Text node which contains information from the XPath + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @param type + * @return the first Text node which contains information from the XPath 2 Filter String + */ + private Node getHereContextNode(String type) { + + if (this.length(this.getBaseNamespace(), type) != 1) { + return null; + } + + return XMLUtils.selectNodeText( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); + } + + /** + * Method getHereContextNodeIncludeButSearch + * + * @return the string + */ + public Node getHereContextNodeIncludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } + + /** + * Method getHereContextNodeExcludeButSearch + * + * @return the string + */ + public Node getHereContextNodeExcludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } + + /** + * Method getHereContextNodeExclude + * + * @return the string + */ + public Node getHereContextNodeExclude() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); + } + + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public final String getBaseLocalName() { + return XPathFilterCHGPContainer._TAG_XPATHCHGP; + } + + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public final String getBaseNamespace() { + return TRANSFORM_XPATHFILTERCHGP; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java 2013-06-28 11:34:21.152947508 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java 2013-06-28 11:34:20.976952986 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; @@ -32,762 +34,765 @@ import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Implementation of MIME's Base64 encoding and decoding conversions. - * Optimized code. (raw version taken from oreilly.jonathan.util, - * and currently com.sun.org.apache.xerces.internal.ds.util.Base64) + * Optimized code. (raw version taken from oreilly.jonathan.util, + * and currently org.apache.xerces.ds.util.Base64) * * @author Raul Benito(Of the xerces copy, and little adaptations). * @author Anli Shundi * @author Christian Geuer-Pollmann - * @see RFC 2045 + * @see RFC 2045 * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */ public class Base64 { + /** Field BASE64DEFAULTLENGTH */ + public static final int BASE64DEFAULTLENGTH = 76; + + private static final int BASELENGTH = 255; + private static final int LOOKUPLENGTH = 64; + private static final int TWENTYFOURBITGROUP = 24; + private static final int EIGHTBIT = 8; + private static final int SIXTEENBIT = 16; + private static final int FOURBYTE = 4; + private static final int SIGN = -128; + private static final char PAD = '='; + private static final byte [] base64Alphabet = new byte[BASELENGTH]; + private static final char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; i++) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i>= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); + } + + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } + + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; + + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char)('A' + i); + } + + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char)('a' + j); + } - /** Field BASE64DEFAULTLENGTH */ - public static final int BASE64DEFAULTLENGTH = 76; + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char)('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + } - private Base64() { - // we don't allow instantiation - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - static final byte[] getBytes(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string + private Base64() { + // we don't allow instantiation + } + + /** + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + static final byte[] getBytes(BigInteger big, int bitlen) { - if ((big.bitLength() % 8) == 0) { // correct values + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values startSrc = 1; // skip sign bit bigLen--; // valid length of the string - } + } - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - return resizedBytes; + return resizedBytes; + } - } - - /** - * Encode in Base64 the given {@link BigInteger}. - * - * @param big - * @return String with Base64 encoding - */ - public static final String encode(BigInteger big) { - return encode(getBytes(big, big.bitLength())); - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - public static final byte[] encode(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string + /** + * Encode in Base64 the given {@link BigInteger}. + * + * @param big + * @return String with Base64 encoding + */ + public static final String encode(BigInteger big) { + return encode(getBytes(big, big.bitLength())); + } + + /** + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + public static final byte[] encode(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } - if ((big.bitLength() % 8) == 0) { // correct values + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values startSrc = 1; // skip sign bit bigLen--; // valid length of the string - } + } - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - return resizedBytes; + return resizedBytes; + } - } - - /** - * Method decodeBigIntegerFromElement - * - * @param element - * @return the biginter obtained from the node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(element)); - } - - /** - * Method decodeBigIntegerFromText - * - * @param text - * @return the biginter obtained from the text node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(text.getData())); - } - - /** - * This method takes an (empty) Element and a BigInteger and adds the - * base64 encoded BigInteger to the Element. - * - * @param element - * @param biginteger - */ - public static final void fillElementWithBigInteger(Element element, - BigInteger biginteger) { - - String encodedInt = encode(biginteger); - - if (encodedInt.length() > 76) { - encodedInt = "\n" + encodedInt + "\n"; - } - - Document doc = element.getOwnerDocument(); - Text text = doc.createTextNode(encodedInt); - - element.appendChild(text); - } - - /** - * Method decode - * - * Takes the Text children of the Element and interprets - * them as input for the Base64.decode() function. - * - * @param element - * @return the byte obtained of the decoding the element - * $todo$ not tested yet - * @throws Base64DecodingException - */ - public static final byte[] decode(Element element) throws Base64DecodingException { - - Node sibling = element.getFirstChild(); - StringBuffer sb = new StringBuffer(); - - while (sibling!=null) { - if (sibling.getNodeType() == Node.TEXT_NODE) { - Text t = (Text) sibling; - - sb.append(t.getData()); - } - sibling=sibling.getNextSibling(); - } - - return decode(sb.toString()); - } - - /** - * Method encodeToElement - * - * @param doc - * @param localName - * @param bytes - * @return an Element with the base64 encoded in the text. - * - */ - public static final Element encodeToElement(Document doc, String localName, - byte[] bytes) { - - Element el = XMLUtils.createElementInSignatureSpace(doc, localName); - Text text = doc.createTextNode(encode(bytes)); - - el.appendChild(text); - - return el; - } - - /** - * Method decode - * - * - * @param base64 - * @return the UTF bytes of the base64 - * @throws Base64DecodingException - * - */ - public final static byte[] decode(byte[] base64) throws Base64DecodingException { - return decodeInternal(base64, -1); - } - - - - /** - * Encode a byte array and fold lines at the standard 76th character unless - * ignore line breaks property is set. - * - * @param binaryData byte[] to be base64 encoded - * @return the String with encoded data - */ - public static final String encode(byte[] binaryData) { - return XMLUtils.ignoreLineBreaks() - ? encode(binaryData, Integer.MAX_VALUE) - : encode(binaryData, BASE64DEFAULTLENGTH); - } - - /** - * Base64 decode the lines from the reader and return an InputStream - * with the bytes. - * - * - * @param reader - * @return InputStream with the decoded bytes - * @exception IOException passes what the reader throws - * @throws IOException - * @throws Base64DecodingException - */ - public final static byte[] decode(BufferedReader reader) - throws IOException, Base64DecodingException { - - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - String line; - - while (null != (line = reader.readLine())) { - byte[] bytes = decode(line); - - baos.write(bytes); - } - - return baos.toByteArray(); - } - - static private final int BASELENGTH = 255; - static private final int LOOKUPLENGTH = 64; - static private final int TWENTYFOURBITGROUP = 24; - static private final int EIGHTBIT = 8; - static private final int SIXTEENBIT = 16; - static private final int FOURBYTE = 4; - static private final int SIGN = -128; - static private final char PAD = '='; - static final private byte [] base64Alphabet = new byte[BASELENGTH]; - static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; - - static { - - for (int i = 0; i= 'A'; i--) { - base64Alphabet[i] = (byte) (i-'A'); - } - for (int i = 'z'; i>= 'a'; i--) { - base64Alphabet[i] = (byte) ( i-'a' + 26); - } - - for (int i = '9'; i >= '0'; i--) { - base64Alphabet[i] = (byte) (i-'0' + 52); - } - - base64Alphabet['+'] = 62; - base64Alphabet['/'] = 63; - - for (int i = 0; i<=25; i++) - lookUpBase64Alphabet[i] = (char)('A'+i); - - for (int i = 26, j = 0; i<=51; i++, j++) - lookUpBase64Alphabet[i] = (char)('a'+ j); - - for (int i = 52, j = 0; i<=61; i++, j++) - lookUpBase64Alphabet[i] = (char)('0' + j); - lookUpBase64Alphabet[62] = '+'; - lookUpBase64Alphabet[63] = '/'; - - } - - protected static final boolean isWhiteSpace(byte octect) { - return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); - } - - protected static final boolean isPad(byte octect) { - return (octect == PAD); - } - - - /** - * Encodes hex octects into Base64 - * - * @param binaryData Array containing binaryData - * @return Encoded Base64 array - */ - /** - * Encode a byte array in Base64 format and return an optionally - * wrapped line. - * - * @param binaryData byte[] data to be encoded - * @param length int length of wrapped lines; No wrapping if less than 4. - * @return a String with encoded data - */ - public static final String encode(byte[] binaryData,int length) { + /** + * Method decodeBigIntegerFromElement + * + * @param element + * @return the biginteger obtained from the node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromElement(Element element) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(element)); + } - if (length<4) { - length=Integer.MAX_VALUE; - } + /** + * Method decodeBigIntegerFromText + * + * @param text + * @return the biginter obtained from the text node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromText(Text text) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(text.getData())); + } - if (binaryData == null) - return null; + /** + * This method takes an (empty) Element and a BigInteger and adds the + * base64 encoded BigInteger to the Element. + * + * @param element + * @param biginteger + */ + public static final void fillElementWithBigInteger(Element element, BigInteger biginteger) { - int lengthDataBits = binaryData.length*EIGHTBIT; - if (lengthDataBits == 0) { - return ""; - } + String encodedInt = encode(biginteger); - int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; - int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; - int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets; - int quartesPerLine = length/4; - int numberLines = (numberQuartet-1)/quartesPerLine; - char encodedData[] = null; + if (!XMLUtils.ignoreLineBreaks() && encodedInt.length() > BASE64DEFAULTLENGTH) { + encodedInt = "\n" + encodedInt + "\n"; + } - encodedData = new char[numberQuartet*4+numberLines]; + Document doc = element.getOwnerDocument(); + Text text = doc.createTextNode(encodedInt); - byte k=0, l=0, b1=0,b2=0,b3=0; + element.appendChild(text); + } - int encodedIndex = 0; - int dataIndex = 0; - int i = 0; + /** + * Method decode + * + * Takes the Text children of the Element and interprets + * them as input for the Base64.decode() function. + * + * @param element + * @return the byte obtained of the decoding the element + * $todo$ not tested yet + * @throws Base64DecodingException + */ + public static final byte[] decode(Element element) throws Base64DecodingException { + Node sibling = element.getFirstChild(); + StringBuffer sb = new StringBuffer(); - for (int line = 0; line < numberLines; line++) { - for (int quartet = 0; quartet < 19; quartet++) { - b1 = binaryData[dataIndex++]; - b2 = binaryData[dataIndex++]; - b3 = binaryData[dataIndex++]; + while (sibling != null) { + if (sibling.getNodeType() == Node.TEXT_NODE) { + Text t = (Text) sibling; + sb.append(t.getData()); + } + sibling = sibling.getNextSibling(); + } - l = (byte)(b2 & 0x0f); - k = (byte)(b1 & 0x03); + return decode(sb.toString()); + } - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); + /** + * Method encodeToElement + * + * @param doc + * @param localName + * @param bytes + * @return an Element with the base64 encoded in the text. + * + */ + public static final Element encodeToElement(Document doc, String localName, byte[] bytes) { + Element el = XMLUtils.createElementInSignatureSpace(doc, localName); + Text text = doc.createTextNode(encode(bytes)); - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); + el.appendChild(text); + return el; + } - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; + /** + * Method decode + * + * @param base64 + * @return the UTF bytes of the base64 + * @throws Base64DecodingException + * + */ + public static final byte[] decode(byte[] base64) throws Base64DecodingException { + return decodeInternal(base64, -1); + } - i++; - } - encodedData[encodedIndex++] = 0xa; - } + /** + * Encode a byte array and fold lines at the standard 76th character unless + * ignore line breaks property is set. + * + * @param binaryData byte[] to be base64 encoded + * @return the String with encoded data + */ + public static final String encode(byte[] binaryData) { + return XMLUtils.ignoreLineBreaks() + ? encode(binaryData, Integer.MAX_VALUE) + : encode(binaryData, BASE64DEFAULTLENGTH); + } - for (; i>2):(byte)((b1)>>2^0xc0); + protected static final boolean isWhiteSpace(byte octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); + protected static final boolean isPad(byte octect) { + return (octect == PAD); + } + /** + * Encodes hex octets into Base64 + * + * @param binaryData Array containing binaryData + * @return Encoded Base64 array + */ + /** + * Encode a byte array in Base64 format and return an optionally + * wrapped line. + * + * @param binaryData byte[] data to be encoded + * @param length int length of wrapped lines; No wrapping if less than 4. + * @return a String with encoded data + */ + public static final String encode(byte[] binaryData,int length) { + if (length < 4) { + length = Integer.MAX_VALUE; + } - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - } + if (binaryData == null) { + return null; + } - // form integral number of 6-bit groups - if (fewerThan24bits == EIGHTBIT) { - b1 = binaryData[dataIndex]; - k = (byte) ( b1 &0x03 ); - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ]; - encodedData[encodedIndex++] = PAD; - encodedData[encodedIndex++] = PAD; - } else if (fewerThan24bits == SIXTEENBIT) { - b1 = binaryData[dataIndex]; - b2 = binaryData[dataIndex +1 ]; - l = ( byte ) ( b2 &0x0f ); - k = ( byte ) ( b1 &0x03 ); + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + int quartesPerLine = length / 4; + int numberLines = (numberQuartet - 1) / quartesPerLine; + char encodedData[] = null; + + encodedData = new char[numberQuartet * 4 + numberLines]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + int encodedIndex = 0; + int dataIndex = 0; + int i = 0; + + for (int line = 0; line < numberLines; line++) { + for (int quartet = 0; quartet < 19; quartet++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + + i++; + } + encodedData[encodedIndex++] = 0xa; + } + + for (; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; - encodedData[encodedIndex++] = PAD; - } + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 &0x03); + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2):(byte)((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex +1 ]; + l = ( byte ) (b2 & 0x0f); + k = ( byte ) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } - //encodedData[encodedIndex] = 0xa; + //encodedData[encodedIndex] = 0xa; - return new String(encodedData); - } + return new String(encodedData); + } /** - * Decodes Base64 data into octects + * Decodes Base64 data into octets * * @param encoded String containing base64 encoded data * @return byte array containing the decoded data * @throws Base64DecodingException if there is a problem decoding the data */ - public final static byte[] decode(String encoded) throws Base64DecodingException { - - if (encoded == null) - return null; - byte []bytes=new byte[encoded.length()]; - int len=getBytesInternal(encoded, bytes); - return decodeInternal(bytes, len); + public static final byte[] decode(String encoded) throws Base64DecodingException { + if (encoded == null) { + return null; } + byte[] bytes = new byte[encoded.length()]; + int len = getBytesInternal(encoded, bytes); + return decodeInternal(bytes, len); + } - protected static final int getBytesInternal(String s,byte[] result) { - int length=s.length(); + protected static final int getBytesInternal(String s, byte[] result) { + int length = s.length(); - int newSize=0; + int newSize = 0; for (int i = 0; i < length; i++) { - byte dataS=(byte)s.charAt(i); - if (!isWhiteSpace(dataS)) + byte dataS = (byte)s.charAt(i); + if (!isWhiteSpace(dataS)) { result[newSize++] = dataS; + } } return newSize; - } - protected final static byte[] decodeInternal(byte[] base64Data, int len) throws Base64DecodingException { - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four - } - - int numberQuadruple = (len/FOURBYTE ); - - if (numberQuadruple == 0) - return new byte[0]; - - byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; - - - int i = 0; - int encodedIndex = 0; - int dataIndex = 0; - - //decodedData = new byte[ (numberQuadruple)*3]; - dataIndex=(numberQuadruple-1)*4; - encodedIndex=(numberQuadruple-1)*3; - //first last bits. - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - if ((b1==-1) || (b2==-1)) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null + + protected static final byte[] decodeInternal(byte[] base64Data, int len) + throws Base64DecodingException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); } + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - byte d3,d4; - b3 = base64Alphabet[d3=base64Data[dataIndex++]]; - b4 = base64Alphabet[d4=base64Data[dataIndex++]]; - if ((b3==-1 ) || (b4==-1) ) { - //Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 1 ]; - decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 2 ]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); - decodedData[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); + int numberQuadruple = (len / FOURBYTE); + + if (numberQuadruple == 0) { + return new byte[0]; + } + + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; + + //decodedData = new byte[ (numberQuadruple)*3]; + dataIndex = (numberQuadruple - 1) * 4; + encodedIndex = (numberQuadruple - 1) * 3; + //first last bits. + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1==-1) || (b2==-1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } + + + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1) || (b4 == -1) ) { + //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 1]; + decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4) ; + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 2]; + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + decodedData[encodedIndex] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); } } else { //No PAD e.g 3cQl decodedData = new byte[encodedIndex+3]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - } - encodedIndex=0; - dataIndex=0; - //the begin - for (i=numberQuadruple-1; i>0; i--) { - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; - - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - } - return decodedData; - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data String containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(String base64Data, - OutputStream os) throws Base64DecodingException, IOException { - byte[] bytes=new byte[base64Data.length()]; - int len=getBytesInternal(base64Data, bytes); - decode(bytes,os,len); - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data Byte array containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(byte[] base64Data, - OutputStream os) throws Base64DecodingException, IOException { - decode(base64Data,os,-1); - } - protected final static void decode(byte[] base64Data, - OutputStream os,int len) throws Base64DecodingException, IOException { + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4); + } + encodedIndex = 0; + dataIndex = 0; + //the begin + for (i = numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; + + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 ); + } + return decodedData; + } - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four + /** + * Decodes Base64 data into outputstream + * + * @param base64Data String containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(String base64Data, OutputStream os) + throws Base64DecodingException, IOException { + byte[] bytes = new byte[base64Data.length()]; + int len = getBytesInternal(base64Data, bytes); + decode(bytes,os,len); } - int numberQuadruple = (len/FOURBYTE ); + /** + * Decodes Base64 data into outputstream + * + * @param base64Data Byte array containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(byte[] base64Data, OutputStream os) + throws Base64DecodingException, IOException { + decode(base64Data,os,-1); + } - if (numberQuadruple == 0) - return; + protected static final void decode(byte[] base64Data, OutputStream os, int len) + throws Base64DecodingException, IOException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } + + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } + + int numberQuadruple = (len / FOURBYTE); + + if (numberQuadruple == 0) { + return; + } - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - int i = 0; + int i = 0; + int dataIndex = 0; - int dataIndex = 0; + //the begin + for (i=numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - //the begin - for (i=numberQuadruple-1; i>0; i--) { + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf))); + os.write( (byte)(b3 << 6 | b4)); + } b1 = base64Alphabet[base64Data[dataIndex++]]; b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - - - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); - } - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - - // first last bits. - if ((b1==-1) || - (b2==-1) ){ - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - byte d3,d4; - b3= base64Alphabet[d3 = base64Data[dataIndex++]]; - b4= base64Alphabet[d4 = base64Data[dataIndex++]]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } - return ; - } - - /** - * Decodes Base64 data into outputstream - * - * @param is containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(InputStream is, - OutputStream os) throws Base64DecodingException, IOException { - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; - - int index=0; - byte []data=new byte[4]; - int read; - //the begin - while ((read=is.read())>0) { - byte readed=(byte)read; - if (isWhiteSpace(readed)) { - continue; + + // first last bits. + if ((b1 == -1) || (b2 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - if (isPad(readed)) { - data[index++]=readed; - if (index==3) - data[index++]=(byte)is.read(); - break; + + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1 ) || (b4 == -1) ) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3 ) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write( (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); } + } + /** + * Decodes Base64 data into outputstream + * + * @param is containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(InputStream is, OutputStream os) + throws Base64DecodingException, IOException { + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + + int index=0; + byte[] data = new byte[4]; + int read; + //the begin + while ((read = is.read()) > 0) { + byte readed = (byte)read; + if (isWhiteSpace(readed)) { + continue; + } + if (isPad(readed)) { + data[index++] = readed; + if (index == 3) { + data[index++] = (byte)is.read(); + } + break; + } - if ((data[index++]=readed)==-1) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } + if ((data[index++] = readed) == -1) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - if (index!=4) { + if (index != 4) { continue; + } + index = 0; + b1 = base64Alphabet[data[0]]; + b2 = base64Alphabet[data[1]]; + b3 = base64Alphabet[data[2]]; + b4 = base64Alphabet[data[3]]; + + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + + byte d1 = data[0], d2 = data[1], d3 = data[2], d4 = data[3]; + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); } - index=0; - b1 = base64Alphabet[data[0]]; - b2 = base64Alphabet[data[1]]; - b3 = base64Alphabet[data[2]]; - b4 = base64Alphabet[data[3]]; - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); } + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data the byte array of base64 data (with WS) + * @return the new length + */ + protected static final int removeWhiteSpace(byte[] data) { + if (data == null) { + return 0; + } - byte d1=data[0],d2=data[1],d3=data[2], d4=data[3]; - b1 = base64Alphabet[d1]; - b2 = base64Alphabet[d2]; - b3 = base64Alphabet[ d3 ]; - b4 = base64Alphabet[ d4 ]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - b3 = base64Alphabet[ d3 ]; - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } - - return ; - } - /** - * remove WhiteSpace from MIME containing encoded Base64 data. - * - * @param data the byte array of base64 data (with WS) - * @return the new length - */ - protected static final int removeWhiteSpace(byte[] data) { - if (data == null) - return 0; - - // count characters that's not whitespace - int newSize = 0; - int len = data.length; - for (int i = 0; i < len; i++) { - byte dataS=data[i]; - if (!isWhiteSpace(dataS)) - data[newSize++] = dataS; - } - return newSize; - } + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + byte dataS = data[i]; + if (!isWhiteSpace(dataS)) { + data[newSize++] = dataS; + } + } + return newSize; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java 2013-06-28 11:34:21.816926839 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java 2013-06-28 11:34:21.632932567 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Provides all constants and some translation functions for i18n. * @@ -29,202 +29,245 @@ * XML * Signature specification. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class Constants { - /** Field configurationFile */ - public static final String configurationFile = "data/websig.conf"; + /** Field configurationFile */ + public static final String configurationFile = "data/websig.conf"; + + /** Field configurationFileNew */ + public static final String configurationFileNew = ".xmlsecurityconfig"; - /** Field configurationFileNew */ - public static final String configurationFileNew = ".xmlsecurityconfig"; + /** Field exceptionMessagesResourceBundleDir */ + public static final String exceptionMessagesResourceBundleDir = + "com/sun/org/apache/xml/internal/security/resource"; + + /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ + public static final String exceptionMessagesResourceBundleBase = + exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; + + /** + * The URL of the + * XML Signature specification + */ + public static final String SIGNATURESPECIFICATION_URL = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; + + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#"; + + /** The URL for more algorithms **/ + public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; + + /** The URI for XML spec*/ + public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; + + /** The URI for XMLNS spec*/ + public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; + + /** Tag of Attr Algorithm**/ + public static final String _ATT_ALGORITHM = "Algorithm"; + + /** Tag of Attr URI**/ + public static final String _ATT_URI = "URI"; + + /** Tag of Attr Type**/ + public static final String _ATT_TYPE = "Type"; + + /** Tag of Attr Id**/ + public static final String _ATT_ID = "Id"; + + /** Tag of Attr MimeType**/ + public static final String _ATT_MIMETYPE = "MimeType"; + + /** Tag of Attr Encoding**/ + public static final String _ATT_ENCODING = "Encoding"; + + /** Tag of Attr Target**/ + public static final String _ATT_TARGET = "Target"; + + // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) + // KeyValue (DSAKeyValue|RSAKeyValue) + // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) + // RSAKeyValue (Modulus, Exponent) + // RetrievalMethod (Transforms?) + // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) + // X509IssuerSerial (X509IssuerName, X509SerialNumber) + // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) + // SPKIData (SPKISexp) + + /** Tag of Element CanonicalizationMethod **/ + public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; + + /** Tag of Element DigestMethod **/ + public static final String _TAG_DIGESTMETHOD = "DigestMethod"; + + /** Tag of Element DigestValue **/ + public static final String _TAG_DIGESTVALUE = "DigestValue"; + + /** Tag of Element Manifest **/ + public static final String _TAG_MANIFEST = "Manifest"; + + /** Tag of Element Methods **/ + public static final String _TAG_METHODS = "Methods"; + + /** Tag of Element Object **/ + public static final String _TAG_OBJECT = "Object"; + + /** Tag of Element Reference **/ + public static final String _TAG_REFERENCE = "Reference"; + + /** Tag of Element Signature **/ + public static final String _TAG_SIGNATURE = "Signature"; + + /** Tag of Element SignatureMethod **/ + public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; + + /** Tag of Element HMACOutputLength **/ + public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; + + /** Tag of Element SignatureProperties **/ + public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; + + /** Tag of Element SignatureProperty **/ + public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; + + /** Tag of Element SignatureValue **/ + public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; + + /** Tag of Element SignedInfo **/ + public static final String _TAG_SIGNEDINFO = "SignedInfo"; + + /** Tag of Element Transform **/ + public static final String _TAG_TRANSFORM = "Transform"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element XPath **/ + public static final String _TAG_XPATH = "XPath"; + + /** Tag of Element KeyInfo **/ + public static final String _TAG_KEYINFO = "KeyInfo"; + + /** Tag of Element KeyName **/ + public static final String _TAG_KEYNAME = "KeyName"; + + /** Tag of Element KeyValue **/ + public static final String _TAG_KEYVALUE = "KeyValue"; + + /** Tag of Element RetrievalMethod **/ + public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; + + /** Tag of Element X509Data **/ + public static final String _TAG_X509DATA = "X509Data"; + + /** Tag of Element PGPData **/ + public static final String _TAG_PGPDATA = "PGPData"; + + /** Tag of Element SPKIData **/ + public static final String _TAG_SPKIDATA = "SPKIData"; + + /** Tag of Element MgmtData **/ + public static final String _TAG_MGMTDATA = "MgmtData"; + + /** Tag of Element RSAKeyValue **/ + public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; + + /** Tag of Element Exponent **/ + public static final String _TAG_EXPONENT = "Exponent"; + + /** Tag of Element Modulus **/ + public static final String _TAG_MODULUS = "Modulus"; + + /** Tag of Element DSAKeyValue **/ + public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; + + /** Tag of Element P **/ + public static final String _TAG_P = "P"; + + /** Tag of Element Q **/ + public static final String _TAG_Q = "Q"; + + /** Tag of Element G **/ + public static final String _TAG_G = "G"; + + /** Tag of Element Y **/ + public static final String _TAG_Y = "Y"; + + /** Tag of Element J **/ + public static final String _TAG_J = "J"; + + /** Tag of Element Seed **/ + public static final String _TAG_SEED = "Seed"; + + /** Tag of Element PgenCounter **/ + public static final String _TAG_PGENCOUNTER = "PgenCounter"; + + /** Tag of Element rawX509Certificate **/ + public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; + + /** Tag of Element X509IssuerSerial **/ + public static final String _TAG_X509ISSUERSERIAL= "X509IssuerSerial"; + + /** Tag of Element X509SKI **/ + public static final String _TAG_X509SKI = "X509SKI"; + + /** Tag of Element X509SubjectName **/ + public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; + + /** Tag of Element X509Certificate **/ + public static final String _TAG_X509CERTIFICATE = "X509Certificate"; + + /** Tag of Element X509CRL **/ + public static final String _TAG_X509CRL = "X509CRL"; + + /** Tag of Element X509IssuerName **/ + public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; + + /** Tag of Element X509SerialNumber **/ + public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; + + /** Tag of Element PGPKeyID **/ + public static final String _TAG_PGPKEYID = "PGPKeyID"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_DERENCODEDKEYVALUE = "DEREncodedKeyValue"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_KEYINFOREFERENCE = "KeyInfoReference"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_X509DIGEST = "X509Digest"; + + /** Tag of Element SPKISexp **/ + public static final String _TAG_SPKISEXP = "SPKISexp"; + + /** Digest - Required SHA1 */ + public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + + /** + * @see + * draft-blake-wilson-xmldsig-ecdsa-02.txt + */ + public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = + "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; + + private Constants() { + // we don't allow instantiation + } - /** Field exceptionMessagesResourceBundleDir */ - public static final String exceptionMessagesResourceBundleDir = - "com/sun/org/apache/xml/internal/security/resource"; - - /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ - public static final String exceptionMessagesResourceBundleBase = - exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - //J- - /** - * The URL of the XML Signature specification - */ - public static final String SIGNATURESPECIFICATION_URL = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; - - /** - * The namespace of the XML Signature specification - */ - public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - /** The URL for more algorithm **/ - public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** The URI for XML spec*/ - public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** The URI for XMLNS spec*/ - public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; - - /** Tag of Attr Algorithm**/ - public static final String _ATT_ALGORITHM = "Algorithm"; - /** Tag of Attr URI**/ - public static final String _ATT_URI = "URI"; - /** Tag of Attr Type**/ - public static final String _ATT_TYPE = "Type"; - /** Tag of Attr Id**/ - public static final String _ATT_ID = "Id"; - /** Tag of Attr MimeType**/ - public static final String _ATT_MIMETYPE = "MimeType"; - /** Tag of Attr Encoding**/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr Target**/ - public static final String _ATT_TARGET = "Target"; - - // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) - // KeyValue (DSAKeyValue|RSAKeyValue) - // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) - // RSAKeyValue (Modulus, Exponent) - // RetrievalMethod (Transforms?) - // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) - // X509IssuerSerial (X509IssuerName, X509SerialNumber) - // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) - // SPKIData (SPKISexp) - - /** Tag of Element CanonicalizationMethod **/ - public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; - /** Tag of Element DigestMethod **/ - public static final String _TAG_DIGESTMETHOD = "DigestMethod"; - /** Tag of Element DigestValue **/ - public static final String _TAG_DIGESTVALUE = "DigestValue"; - /** Tag of Element Manifest **/ - public static final String _TAG_MANIFEST = "Manifest"; - /** Tag of Element Methods **/ - public static final String _TAG_METHODS = "Methods"; - /** Tag of Element Object **/ - public static final String _TAG_OBJECT = "Object"; - /** Tag of Element Reference **/ - public static final String _TAG_REFERENCE = "Reference"; - /** Tag of Element Signature **/ - public static final String _TAG_SIGNATURE = "Signature"; - /** Tag of Element SignatureMethod **/ - public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; - /** Tag of Element HMACOutputLength **/ - public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; - /** Tag of Element SignatureProperties **/ - public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; - /** Tag of Element SignatureProperty **/ - public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; - /** Tag of Element SignatureValue **/ - public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; - /** Tag of Element SignedInfo **/ - public static final String _TAG_SIGNEDINFO = "SignedInfo"; - /** Tag of Element Transform **/ - public static final String _TAG_TRANSFORM = "Transform"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element XPath **/ - public static final String _TAG_XPATH = "XPath"; - /** Tag of Element KeyInfo **/ - public static final String _TAG_KEYINFO = "KeyInfo"; - /** Tag of Element KeyName **/ - public static final String _TAG_KEYNAME = "KeyName"; - /** Tag of Element KeyValue **/ - public static final String _TAG_KEYVALUE = "KeyValue"; - /** Tag of Element RetrievalMethod **/ - public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; - /** Tag of Element X509Data **/ - public static final String _TAG_X509DATA = "X509Data"; - /** Tag of Element PGPData **/ - public static final String _TAG_PGPDATA = "PGPData"; - /** Tag of Element SPKIData **/ - public static final String _TAG_SPKIDATA = "SPKIData"; - /** Tag of Element MgmtData **/ - public static final String _TAG_MGMTDATA = "MgmtData"; - /** Tag of Element RSAKeyValue **/ - public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; - /** Tag of Element Exponent **/ - public static final String _TAG_EXPONENT = "Exponent"; - /** Tag of Element Modulus **/ - public static final String _TAG_MODULUS = "Modulus"; - /** Tag of Element DSAKeyValue **/ - public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; - /** Tag of Element P **/ - public static final String _TAG_P = "P"; - /** Tag of Element Q **/ - public static final String _TAG_Q = "Q"; - /** Tag of Element G **/ - public static final String _TAG_G = "G"; - /** Tag of Element Y **/ - public static final String _TAG_Y = "Y"; - /** Tag of Element J **/ - public static final String _TAG_J = "J"; - /** Tag of Element Seed **/ - public static final String _TAG_SEED = "Seed"; - /** Tag of Element PgenCounter **/ - public static final String _TAG_PGENCOUNTER = "PgenCounter"; - /** Tag of Element rawX509Certificate **/ - public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; - /** Tag of Element X509IssuerSerial **/ - public static final String _TAG_X509ISSUERSERIAL = "X509IssuerSerial"; - /** Tag of Element X509SKI **/ - public static final String _TAG_X509SKI = "X509SKI"; - /** Tag of Element X509SubjectName **/ - public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; - /** Tag of Element X509Certificate **/ - public static final String _TAG_X509CERTIFICATE = "X509Certificate"; - /** Tag of Element X509CRL **/ - public static final String _TAG_X509CRL = "X509CRL"; - /** Tag of Element X509IssuerName **/ - public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; - /** Tag of Element X509SerialNumber **/ - public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; - /** Tag of Element PGPKeyID **/ - public static final String _TAG_PGPKEYID = "PGPKeyID"; - /** Tag of Element PGPKeyPacket **/ - public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; - /** Tag of Element SPKISexp **/ - public static final String _TAG_SPKISEXP = "SPKISexp"; - - /** Digest - Required SHA1 */ - public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; - - /** - * @see - * draft-blake-wilson-xmldsig-ecdsa-02.txt - */ - public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; - //J+ - - private Constants() { - // we don't allow instantiation - } - - /** - * Sets the namespace prefix which will be used to identify elements in the - * XML Signature Namespace. - * - *
      -    * Constants.setSignatureSpecNSprefix("dsig");
      -    * 
      - * - * @param newPrefix is the new namespace prefix. - * @throws XMLSecurityException - * @see com.sun.org.apache.xml.internal.security.utils.Constants#getSignatureSpecNSprefix - * $todo$ Add consistency checking for valid prefix - */ - public static void setSignatureSpecNSprefix(String newPrefix) throws XMLSecurityException { - ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, newPrefix); - } - - /** - * Returns the XML namespace prefix which is used for elements in the XML - * Signature namespace. - * - * It is defaulted to dsig, but can be changed using the - * {@link #setSignatureSpecNSprefix} function. - * - * @return the current used namespace prefix - * @see #setSignatureSpecNSprefix - */ - public static String getSignatureSpecNSprefix() { - return ElementProxy.getDefaultPrefix(Constants.SignatureSpecNS); - } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java 2013-06-28 11:34:22.448907167 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java 2013-06-28 11:34:22.272912645 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; @@ -29,16 +31,16 @@ * */ public class DigesterOutputStream extends ByteArrayOutputStream { + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName()); + final MessageDigestAlgorithm mda; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (DigesterOutputStream.class.getName()); /** * @param mda */ public DigesterOutputStream(MessageDigestAlgorithm mda) { - this.mda=mda; + this.mda = mda; } /** @inheritDoc */ @@ -55,9 +57,9 @@ public void write(byte[] arg0, int arg1, int arg2) { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } @@ -65,9 +67,9 @@ } /** - * @return the digest value + * @return the digest value */ public byte[] getDigestValue() { - return mda.digest(); + return mda.digest(); } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java 2013-06-28 11:34:23.060888118 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java 2013-06-28 11:34:22.892893347 -0400 @@ -1,17 +1,41 @@ +/* + * 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.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public interface ElementChecker { - /** - * Check that the elemnt is the one expect - * - * @throws XMLSecurityException - */ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) - throws XMLSecurityException; + /** + * Check that the element is the one expect + * + * @throws XMLSecurityException + */ + void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) + throws XMLSecurityException; - public boolean isNamespaceElement(Node el, String type, String ns); + boolean isNamespaceElement(Node el, String type, String ns); } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java 2013-06-28 11:34:23.740866952 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java 2013-06-28 11:34:23.568872305 -0400 @@ -1,60 +1,90 @@ +/* + * 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.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public abstract class ElementCheckerImpl implements ElementChecker { - public boolean isNamespaceElement(Node el, String type, String ns) { - if ((el == null) || - ns!=el.getNamespaceURI() || !el.getLocalName().equals(type)){ - return false; - } - - return true; - } - /** A checker for DOM that interns NS */ - public static class InternedNsChecker extends ElementCheckerImpl{ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); - - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((namespaceSHOULDBE!=namespaceIS) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + + public boolean isNamespaceElement(Node el, String type, String ns) { + if ((el == null) || + ns != el.getNamespaceURI() || !el.getLocalName().equals(type)){ + return false; } - /** A checker for DOM that interns NS */ - public static class FullChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); - - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((!namespaceSHOULDBE.equals(namespaceIS)) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } - } - - /** An empty checker if schema checking is used */ - public static class EmptyChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - } - } + return true; + } + + /** A checker for DOM that interns NS */ + public static class InternedNsChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((expectedNamespace != namespaceIS) || + !expectedLocalname.equals(localnameIS)) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } + } + } + + /** A checker for DOM that interns NS */ + public static class FullChecker extends ElementCheckerImpl { + + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((!expectedNamespace.equals(namespaceIS)) || + !expectedLocalname.equals(localnameIS) ) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } + } + } + + /** An empty checker if schema checking is used */ + public static class EmptyChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + // empty + } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java 2013-06-28 11:34:24.364847529 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java 2013-06-28 11:34:24.204852509 -0400 @@ -41,18 +41,18 @@ */ public abstract class ElementProxy { - protected static final java.util.logging.Logger log = + protected static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ElementProxy.class.getName()); /** Field constructionElement */ - protected Element _constructionElement = null; + protected Element constructionElement = null; /** Field baseURI */ - protected String _baseURI = null; + protected String baseURI = null; /** Field doc */ - protected Document _doc = null; - + protected Document doc = null; + /** Field prefixMappings */ private static Map prefixMappings = new ConcurrentHashMap(); @@ -60,7 +60,7 @@ * Constructor ElementProxy * */ - public ElementProxy() { + public ElementProxy() { } /** @@ -73,11 +73,11 @@ throw new RuntimeException("Document is null"); } - this._doc = doc; - this._constructionElement = - createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName()); + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal(this.doc, this.getBaseNamespace(), this.getBaseLocalName()); } - + /** * Constructor ElementProxy * @@ -94,13 +94,13 @@ log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")"); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; this.guaranteeThatElementInCorrectSpace(); } - + /** * Returns the namespace of the Elements of the sub-class. * @@ -114,11 +114,11 @@ * @return the localname of the Elements of the sub-class. */ public abstract String getBaseLocalName(); - - + + protected Element createElementForFamilyLocal( Document doc, String namespace, String localName - ) { + ) { Element result = null; if (namespace == null) { result = doc.createElementNS(null, localName); @@ -132,7 +132,7 @@ result = doc.createElementNS(namespace, prefix + ":" + localName); result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace); } - } + } return result; } @@ -184,9 +184,9 @@ log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\""); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; } @@ -196,7 +196,7 @@ * @return the Element which was constructed by the Object. */ public final Element getElement() { - return this._constructionElement; + return this.constructionElement; } /** @@ -208,9 +208,9 @@ HelperNodeList nl = new HelperNodeList(); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); nl.appendChild(this.getElement()); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); return nl; } @@ -221,7 +221,7 @@ * @return the Document where this element is contained. */ public Document getDocument() { - return this._doc; + return this.doc; } /** @@ -230,7 +230,7 @@ * @return the base uri of the namespace of this element */ public String getBaseURI() { - return this._baseURI; + return this.baseURI; } /** @@ -243,12 +243,12 @@ String expectedLocalName = this.getBaseLocalName(); String expectedNamespaceUri = this.getBaseNamespace(); - String actualLocalName = this._constructionElement.getLocalName(); - String actualNamespaceUri = this._constructionElement.getNamespaceURI(); + String actualLocalName = this.constructionElement.getLocalName(); + String actualNamespaceUri = this.constructionElement.getNamespaceURI(); - if(!expectedNamespaceUri.equals(actualNamespaceUri) - && !expectedLocalName.equals(actualLocalName)) { - Object exArgs[] = { actualNamespaceUri + ":" + actualLocalName, + if(!expectedNamespaceUri.equals(actualNamespaceUri) + && !expectedLocalName.equals(actualLocalName)) { + Object exArgs[] = { actualNamespaceUri + ":" + actualLocalName, expectedNamespaceUri + ":" + expectedLocalName}; throw new XMLSecurityException("xml.WrongElement", exArgs); } @@ -262,11 +262,11 @@ */ public void addBigIntegerElement(BigInteger bi, String localname) { if (bi != null) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); Base64.fillElementWithBigInteger(e, bi); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -278,11 +278,11 @@ */ public void addBase64Element(byte[] bytes, String localname) { if (bytes != null) { - Element e = Base64.encodeToElement(this._doc, localname, bytes); + Element e = Base64.encodeToElement(this.doc, localname, bytes); - this._constructionElement.appendChild(e); + this.constructionElement.appendChild(e); if (!XMLUtils.ignoreLineBreaks()) { - this._constructionElement.appendChild(this._doc.createTextNode("\n")); + this.constructionElement.appendChild(this.doc.createTextNode("\n")); } } } @@ -294,12 +294,12 @@ * @param localname */ public void addTextElement(String text, String localname) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); - Text t = this._doc.createTextNode(text); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); + Text t = this.doc.createTextNode(text); e.appendChild(t); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -309,10 +309,10 @@ */ public void addBase64Text(byte[] bytes) { if (bytes != null) { - Text t = XMLUtils.ignoreLineBreaks() - ? this._doc.createTextNode(Base64.encode(bytes)) - : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); - this._constructionElement.appendChild(t); + Text t = XMLUtils.ignoreLineBreaks() + ? this.doc.createTextNode(Base64.encode(bytes)) + : this.doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); + this.constructionElement.appendChild(t); } } @@ -323,9 +323,9 @@ */ public void addText(String text) { if (text != null) { - Text t = this._doc.createTextNode(text); + Text t = this.doc.createTextNode(text); - this._constructionElement.appendChild(t); + this.constructionElement.appendChild(t); } } @@ -342,7 +342,7 @@ ) throws Base64DecodingException { return Base64.decodeBigIntegerFromText( XMLUtils.selectNodeText( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ) ); } @@ -360,7 +360,7 @@ throws XMLSecurityException { Element e = XMLUtils.selectNode( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ); return Base64.decode(e); @@ -375,7 +375,7 @@ */ public String getTextFromChildElement(String localname, String namespace) { return XMLUtils.selectNode( - this._constructionElement.getFirstChild(), + this.constructionElement.getFirstChild(), namespace, localname, 0).getTextContent(); @@ -388,17 +388,17 @@ * @throws XMLSecurityException */ public byte[] getBytesFromTextChild() throws XMLSecurityException { - return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement)); + return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this.constructionElement)); } /** * Method getTextFromTextChild * - * @return the Text obtained by concatenating all the text nodes of this + * @return the Text obtained by concatenating all the text nodes of this * element */ public String getTextFromTextChild() { - return XMLUtils.getFullTextChildrenFromElement(this._constructionElement); + return XMLUtils.getFullTextChildrenFromElement(this.constructionElement); } /** @@ -410,8 +410,8 @@ */ public int length(String namespace, String localname) { int number = 0; - Node sibling = this._constructionElement.getFirstChild(); - while (sibling != null) { + Node sibling = this.constructionElement.getFirstChild(); + while (sibling != null) { if (localname.equals(sibling.getLocalName()) && namespace.equals(sibling.getNamespaceURI())) { number++; @@ -448,18 +448,18 @@ ns = "xmlns:" + prefix; } - Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); + Attr a = this.constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); - if (a != null) { + if (a != null) { if (!a.getNodeValue().equals(uri)) { - Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) }; + Object exArgs[] = { ns, this.constructionElement.getAttributeNS(null, ns) }; throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs); } return; } - this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); + this.constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); } /** @@ -479,7 +479,7 @@ throw new XMLSecurityException("prefix.AlreadyAssigned", exArgs); } } - + if (Constants.SignatureSpecNS.equals(namespace)) { XMLUtils.setDsPrefix(prefix); } @@ -488,7 +488,7 @@ } prefixMappings.put(namespace, prefix); } - + /** * This method registers the default prefixes. */ @@ -515,16 +515,4 @@ return prefixMappings.get(namespace); } - protected void setLocalIdAttribute(String attrName, String value) { - - if (value != null) { - Attr attr = getDocument().createAttributeNS(null, attrName); - attr.setValue(value); - getElement().setAttributeNodeNS(attr); - getElement().setIdAttributeNode(attr, true); - } - else { - getElement().removeAttributeNS(null, attrName); - } - } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java 2013-06-28 11:34:24.988828106 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java 2013-06-28 11:34:24.812833584 -0400 @@ -2,179 +2,238 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; - - -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - - -/** - * - * @author $Author: mullan $ - */ public class EncryptionConstants { - //J- - // Attributes that exist in XML Signature in the same way + // Attributes that exist in XML Signature in the same way /** Tag of Attr Algorithm **/ - public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - /** Tag of Attr Id**/ - public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Attr Target **/ - public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Tag of Attr Type **/ - public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** Tag of Attr URI **/ - public static final String _ATT_URI = Constants._ATT_URI; - - // Attributes new in XML Encryption - /** Tag of Attr encoding **/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr recipient **/ - public static final String _ATT_RECIPIENT = "Recipient"; - /** Tag of Attr mimetype **/ - public static final String _ATT_MIMETYPE = "MimeType"; - - /** Tag of Element CarriedKeyName **/ - public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Tag of Element CipherData **/ - public static final String _TAG_CIPHERDATA = "CipherData"; - /** Tag of Element CipherReference **/ - public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Tag of Element CipherValue **/ - public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Tag of Element DataReference **/ - public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Tag of Element EncryptedData **/ - public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - /** Tag of Element EncryptedKey **/ - public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** Tag of Element EncryptionMethod **/ - public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; - /** Tag of Element EncryptionProperties **/ - public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; - /** Tag of Element EncryptionProperty **/ - public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; - /** Tag of Element KeyReference **/ - public static final String _TAG_KEYREFERENCE = "KeyReference"; - /** Tag of Element KeySize **/ - public static final String _TAG_KEYSIZE = "KeySize"; - /** Tag of Element OAEPparams **/ - public static final String _TAG_OAEPPARAMS = "OAEPparams"; - /** Tag of Element ReferenceList **/ - public static final String _TAG_REFERENCELIST = "ReferenceList"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element AgreementMethod **/ - public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; - /** Tag of Element KA-Nonce **/ - public static final String _TAG_KA_NONCE = "KA-Nonce"; - /** Tag of Element OriginatorKeyInfo **/ - public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; - /** Tag of Element RecipientKeyInfo **/ - public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; - - /** Field ENCRYPTIONSPECIFICATION_URL */ - public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; - - /** The namespace of the XML Encryption Syntax and Processing */ - public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#"; - - /** URI for content*/ - public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; - /** URI for element*/ - public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; - /** URI for mediatype*/ - public static final String TYPE_MEDIATYPE = "http://www.isi.edu/in-notes/iana/assignments/media-types/"; // + "*/*"; - - /** Block Encryption - REQUIRED TRIPLEDES */ - public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; - /** Block Encryption - REQUIRED AES-128 */ - public static final String ALGO_ID_BLOCKCIPHER_AES128 = EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; - /** Block Encryption - REQUIRED AES-256 */ - public static final String ALGO_ID_BLOCKCIPHER_AES256 = EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; - /** Block Encryption - OPTIONAL AES-192 */ - public static final String ALGO_ID_BLOCKCIPHER_AES192 = EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; - - /** Key Transport - REQUIRED RSA-v1.5*/ - public static final String ALGO_ID_KEYTRANSPORT_RSA15 = EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; - /** Key Transport - REQUIRED RSA-OAEP */ - public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; - - /** Key Agreement - OPTIONAL Diffie-Hellman */ - public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh"; - - /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ - public static final String ALGO_ID_KEYWRAP_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; - /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES128 = EncryptionConstants.EncryptionSpecNS + "kw-aes128"; - /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES256 = EncryptionConstants.EncryptionSpecNS + "kw-aes256"; - /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES192 = EncryptionConstants.EncryptionSpecNS + "kw-aes192"; - - /* - // Message Digest - REQUIRED SHA1 - public static final String ALGO_ID_DIGEST_SHA160 = Constants.ALGO_ID_DIGEST_SHA1; - // Message Digest - RECOMMENDED SHA256 - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - // Message Digest - OPTIONAL SHA512 - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - // Message Digest - OPTIONAL RIPEMD-160 - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; - */ - - /** Message Authentication - RECOMMENDED XML Digital Signature */ - public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; - - /** Canonicalization - OPTIONAL Canonical XML with Comments */ - public static final String ALGO_ID_C14N_WITHCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ - public static final String ALGO_ID_C14N_OMITCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; - - /** Encoding - REQUIRED base64 */ - public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"; - //J+ - - private EncryptionConstants() { - // we don't allow instantiation - } - - /** - * Method setEncryptionSpecNSprefix - * - * @param newPrefix - * @throws XMLSecurityException - */ - public static void setEncryptionSpecNSprefix(String newPrefix) - throws XMLSecurityException { - ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS, - newPrefix); - } - - /** - * Method getEncryptionSpecNSprefix - * - * @return the prefix for this node. - */ - public static String getEncryptionSpecNSprefix() { - return ElementProxy - .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS); - } + public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; + + /** Tag of Attr Id**/ + public static final String _ATT_ID = Constants._ATT_ID; + + /** Tag of Attr Target **/ + public static final String _ATT_TARGET = Constants._ATT_TARGET; + + /** Tag of Attr Type **/ + public static final String _ATT_TYPE = Constants._ATT_TYPE; + + /** Tag of Attr URI **/ + public static final String _ATT_URI = Constants._ATT_URI; + + // Attributes new in XML Encryption + /** Tag of Attr encoding **/ + public static final String _ATT_ENCODING = "Encoding"; + + /** Tag of Attr recipient **/ + public static final String _ATT_RECIPIENT = "Recipient"; + + /** Tag of Attr mimetype **/ + public static final String _ATT_MIMETYPE = "MimeType"; + + /** Tag of Element CarriedKeyName **/ + public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; + + /** Tag of Element CipherData **/ + public static final String _TAG_CIPHERDATA = "CipherData"; + + /** Tag of Element CipherReference **/ + public static final String _TAG_CIPHERREFERENCE = "CipherReference"; + + /** Tag of Element CipherValue **/ + public static final String _TAG_CIPHERVALUE = "CipherValue"; + + /** Tag of Element DataReference **/ + public static final String _TAG_DATAREFERENCE = "DataReference"; + + /** Tag of Element EncryptedData **/ + public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; + + /** Tag of Element EncryptedKey **/ + public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; + + /** Tag of Element EncryptionMethod **/ + public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; + + /** Tag of Element EncryptionProperties **/ + public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; + + /** Tag of Element EncryptionProperty **/ + public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; + + /** Tag of Element KeyReference **/ + public static final String _TAG_KEYREFERENCE = "KeyReference"; + + /** Tag of Element KeySize **/ + public static final String _TAG_KEYSIZE = "KeySize"; + + /** Tag of Element OAEPparams **/ + public static final String _TAG_OAEPPARAMS = "OAEPparams"; + + /** Tag of Element MGF **/ + public static final String _TAG_MGF = "MGF"; + + /** Tag of Element ReferenceList **/ + public static final String _TAG_REFERENCELIST = "ReferenceList"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element AgreementMethod **/ + public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; + + /** Tag of Element KA-Nonce **/ + public static final String _TAG_KA_NONCE = "KA-Nonce"; + + /** Tag of Element OriginatorKeyInfo **/ + public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; + + /** Tag of Element RecipientKeyInfo **/ + public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + + /** Field ENCRYPTIONSPECIFICATION_URL */ + public static final String ENCRYPTIONSPECIFICATION_URL = + "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + + /** The namespace of the + * + * XML Encryption Syntax and Processing */ + public static final String EncryptionSpecNS = + "http://www.w3.org/2001/04/xmlenc#"; + + /** + * The namespace of the XML Encryption 1.1 specification + */ + public static final String EncryptionSpec11NS = + "http://www.w3.org/2009/xmlenc11#"; + + /** URI for content*/ + public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; + + /** URI for element*/ + public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; + + /** URI for mediatype*/ + public static final String TYPE_MEDIATYPE = + "http://www.isi.edu/in-notes/iana/assignments/media-types/"; + + /** Block Encryption - REQUIRED TRIPLEDES */ + public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; + + /** Block Encryption - REQUIRED AES-128 */ + public static final String ALGO_ID_BLOCKCIPHER_AES128 = + EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; + + /** Block Encryption - REQUIRED AES-256 */ + public static final String ALGO_ID_BLOCKCIPHER_AES256 = + EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; + + /** Block Encryption - OPTIONAL AES-192 */ + public static final String ALGO_ID_BLOCKCIPHER_AES192 = + EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + + /** Block Encryption - OPTIONAL AES-128-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES128_GCM = + "http://www.w3.org/2009/xmlenc11#aes128-gcm"; + + /** Block Encryption - OPTIONAL AES-192-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES192_GCM = + "http://www.w3.org/2009/xmlenc11#aes192-gcm"; + + /** Block Encryption - OPTIONAL AES-256-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES256_GCM = + "http://www.w3.org/2009/xmlenc11#aes256-gcm"; + + /** Key Transport - REQUIRED RSA-v1.5*/ + public static final String ALGO_ID_KEYTRANSPORT_RSA15 = + EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; + + /** Key Transport - REQUIRED RSA-OAEP */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = + EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + + /** Key Transport - OPTIONAL RSA-OAEP_11 */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP_11 = + EncryptionConstants.EncryptionSpec11NS + "rsa-oaep"; + + /** Key Agreement - OPTIONAL Diffie-Hellman */ + public static final String ALGO_ID_KEYAGREEMENT_DH = + EncryptionConstants.EncryptionSpecNS + "dh"; + + /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ + public static final String ALGO_ID_KEYWRAP_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; + + /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES128 = + EncryptionConstants.EncryptionSpecNS + "kw-aes128"; + + /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES256 = + EncryptionConstants.EncryptionSpecNS + "kw-aes256"; + + /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES192 = + EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + + /** Message Authentication - RECOMMENDED XML Digital Signature */ + public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + + /** Canonicalization - OPTIONAL Canonical XML with Comments */ + public static final String ALGO_ID_C14N_WITHCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; + + /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ + public static final String ALGO_ID_C14N_OMITCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + + /** Encoding - REQUIRED base64 */ + public static final String ALGO_ID_ENCODING_BASE64 = + "http://www.w3.org/2000/09/xmldsig#base64"; + + /** MGF1 with SHA-1 */ + public static final String MGF1_SHA1 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha1"; + + /** MGF1 with SHA-224 */ + public static final String MGF1_SHA224 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha224"; + + /** MGF1 with SHA-256 */ + public static final String MGF1_SHA256 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha256"; + + /** MGF1 with SHA-384 */ + public static final String MGF1_SHA384 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha384"; + + /** MGF1 with SHA-512 */ + public static final String MGF1_SHA512 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha512"; + + + private EncryptionConstants() { + // we don't allow instantiation + } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java 2013-06-28 11:34:25.672806816 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java 2013-06-28 11:34:25.508811920 -0400 @@ -2,62 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This is the base object for all objects which map directly to an Element from * the xenc spec. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class EncryptionElementProxy extends ElementProxy { - /** - * Constructor EncryptionElementProxy - * - * @param doc - */ - public EncryptionElementProxy(Document doc) { - super(doc); - } - - /** - * Constructor EncryptionElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public EncryptionElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } - - /** @inheritDoc */ - public final String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } + /** + * Constructor EncryptionElementProxy + * + * @param doc + */ + public EncryptionElementProxy(Document doc) { + super(doc); + } + + /** + * Constructor EncryptionElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public EncryptionElementProxy(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } + + /** @inheritDoc */ + public final String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java 2013-06-28 11:34:26.260788513 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java 2013-06-28 11:34:26.096793618 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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.utils; @@ -28,75 +30,69 @@ import org.w3c.dom.NodeList; /** - * * @author Christian Geuer-Pollmann - * */ public class HelperNodeList implements NodeList { - /** Field nodes */ - List nodes = new ArrayList(20); - boolean _allNodesMustHaveSameParent = false; - - /** - * - */ - public HelperNodeList() { - this(false); - } - - - /** - * @param allNodesMustHaveSameParent - */ - public HelperNodeList(boolean allNodesMustHaveSameParent) { - this._allNodesMustHaveSameParent = allNodesMustHaveSameParent; - } - - /** - * Method item - * - * @param index - * @return node with inde i - */ - public Node item(int index) { - - // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes"); - - return nodes.get(index); - } - - /** - * Method getLength - * - * @return length of the list - */ - public int getLength() { - return nodes.size(); - } - - /** - * Method appendChild - * - * @param node - * @throws IllegalArgumentException - */ - public void appendChild(Node node) throws IllegalArgumentException { - if (this._allNodesMustHaveSameParent && this.getLength() > 0) { - if (this.item(0).getParentNode() != node.getParentNode()) { + /** Field nodes */ + List nodes = new ArrayList(); + boolean allNodesMustHaveSameParent = false; + + /** + * + */ + public HelperNodeList() { + this(false); + } + + + /** + * @param allNodesMustHaveSameParent + */ + public HelperNodeList(boolean allNodesMustHaveSameParent) { + this.allNodesMustHaveSameParent = allNodesMustHaveSameParent; + } + + /** + * Method item + * + * @param index + * @return node with index i + */ + public Node item(int index) { + return nodes.get(index); + } + + /** + * Method getLength + * + * @return length of the list + */ + public int getLength() { + return nodes.size(); + } + + /** + * Method appendChild + * + * @param node + * @throws IllegalArgumentException + */ + public void appendChild(Node node) throws IllegalArgumentException { + if (this.allNodesMustHaveSameParent && this.getLength() > 0 + && this.item(0).getParentNode() != node.getParentNode()) { throw new IllegalArgumentException("Nodes have not the same Parent"); - } - } - nodes.add(node); - } - - /** - * @return the document that contains this nodelist - */ - public Document getOwnerDocument() { - if (this.getLength() == 0) { - return null; - } - return XMLUtils.getOwnerDocument(this.item(0)); - } + } + nodes.add(node); + } + + /** + * @return the document that contains this nodelist + */ + public Document getOwnerDocument() { + if (this.getLength() == 0) { + return null; + } + return XMLUtils.getOwnerDocument(this.item(0)); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/I18n.java 2013-06-28 11:34:26.880769214 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/I18n.java 2013-06-28 11:34:26.700774818 -0400 @@ -62,7 +62,7 @@ * exceptionMessagesResourceBundleBase * * @param message - * @param args is an Object[] array of strings which are inserted into + * @param args is an Object[] array of strings which are inserted into * the String which is retrieved from the ResouceBundle * @return message translated */ @@ -98,7 +98,7 @@ return "No message with ID \"" + msgID + "\" found in resource bundle \"" + Constants.exceptionMessagesResourceBundleBase + "\""; - } + } return I18n.NOT_INITIALIZED_MSG; } } @@ -122,7 +122,7 @@ + "\". Original Exception was a " + originalException.getClass().getName() + " and message " + originalException.getMessage(); - } + } return I18n.NOT_INITIALIZED_MSG; } } @@ -142,11 +142,11 @@ return "No message with ID \"" + msgID + "\" found in resource bundle \"" + Constants.exceptionMessagesResourceBundleBase + "\""; - } + } return I18n.NOT_INITIALIZED_MSG; } } - + /** * Method init * --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java 2013-06-28 11:34:27.500749916 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java 2013-06-28 11:34:27.328755270 -0400 @@ -2,85 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.WeakHashMap; -import java.util.Map; - import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; /** * Purpose of this class is to enable the XML Parser to keep track of ID * attributes. This is done by 'registering' attributes of type ID at the - * IdResolver. This is necessary if we create a document from scratch and we - * sign some resources with a URI using a fragent identifier... - *
      - * The problem is that if you do not validate a document, you cannot use the - * getElementByID functionality. So this modules uses some implicit - * knowledge on selected Schemas and DTDs to pick the right Element for a given - * ID: We know that all @Id attributes in an Element from the XML - * Signature namespace are of type ID. - * - * @author $Author: mullan $ - * @see "Identity Crisis" on xml.com + * IdResolver. + * @deprecated */ +@Deprecated public class IdResolver { - /** {@link java.util.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IdResolver.class.getName()); - - private static Map>> docMap = - new WeakHashMap>>(); - - /** - * Constructor IdResolver - * - */ private IdResolver() { - // we don't allow instantiation - } - - /** - * Method registerElementById - * - * @param element the element to register - * @param idValue the value of the ID attribute - */ - public static void registerElementById(Element element, String idValue) { - Document doc = element.getOwnerDocument(); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - if (elementMap == null) { - elementMap = new WeakHashMap>(); - docMap.put(doc, elementMap); - } - } - elementMap.put(idValue, new WeakReference(element)); + // we don't allow instantiation } /** @@ -90,205 +47,18 @@ * @param id the ID attribute */ public static void registerElementById(Element element, Attr id) { - IdResolver.registerElementById(element, id.getNodeValue()); + element.setIdAttributeNode(id, true); } /** * Method getElementById * * @param doc the document - * @param id the value of the ID + * @param id the value of the ID * @return the element obtained by the id, or null if it is not found. */ public static Element getElementById(Document doc, String id) { - - Element result = IdResolver.getElementByIdType(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdType method: " - + result.getTagName()); - - return result; - } - - result = IdResolver.getElementByIdUsingDOM(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdUsingDOM method: " - + result.getTagName()); - - return result; - } - // this must be done so that Xalan can catch ALL namespaces - //XMLUtils.circumventBug2650(doc); - result = IdResolver.getElementBySearching(doc, id); - - if (result != null) { - IdResolver.registerElementById(result, id); - - return result; - } - - return null; - } - - - /** - * Method getElementByIdUsingDOM - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdUsingDOM(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdUsingDOM() Search for ID " + id); return doc.getElementById(id); } - /** - * Method getElementByIdType - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdType(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdType() Search for ID " + id); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - } - if (elementMap != null) { - WeakReference weakReference = elementMap.get(id); - if (weakReference != null) { - return weakReference.get(); - } - } - return null; - } - - private static java.util.List names; - private static int namesLength; - static { - String namespaces[]={ - Constants.SignatureSpecNS, - EncryptionConstants.EncryptionSpecNS, - "http://schemas.xmlsoap.org/soap/security/2000-12", - "http://www.w3.org/2002/03/xkms#", - "urn:oasis:names:tc:SAML:1.0:assertion", - "urn:oasis:names:tc:SAML:1.0:protocol" - }; - names = Arrays.asList(namespaces); - namesLength = names.size(); - } - - - private static Element getElementBySearching(Node root,String id) { - Element []els=new Element[namesLength + 1]; - getEl(root,id,els); - for (int i=0;i2) - continue; - String value=n.getNodeValue(); - if (name.charAt(0)=='I') { - char ch=name.charAt(1); - if (ch=='d' && value.equals(id)) { - els[index]=el; - if (index==0) { - return 1; - } - } else if (ch=='D' &&value.endsWith(id)) { - if (index!=3) { - index=namesLength; - } - els[index]=el; - } - } else if ( "id".equals(name) && value.equals(id) ) { - if (index!=2) { - index=namesLength; - } - els[index]=el; - } - } - //For an element namespace search for importants - if ((elementIndex==3)&&( - el.getAttribute("OriginalRequestID").equals(id) || - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[3]=el; - } else if ((elementIndex==4)&&( - el.getAttribute("AssertionID").equals(id))) { - els[4]=el; - } else if ((elementIndex==5)&&( - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[5]=el; - } - return 0; - } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java 2013-06-28 11:34:28.200728127 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java 2013-06-28 11:34:28.032733357 -0400 @@ -2,82 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; - import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; - /** - * This {@link org.xml.sax.ErrorHandler} does absulutely nothing but logging + * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but log * the events. * * @author Christian Geuer-Pollmann */ public class IgnoreAllErrorHandler implements ErrorHandler { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - IgnoreAllErrorHandler.class.getName()); - - /** Field throwExceptions */ - static final boolean warnOnExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); - - /** Field throwExceptions */ - static final boolean throwExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); - - - /** @inheritDoc */ - public void warning(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName()); + + /** Field throwExceptions */ + private static final boolean warnOnExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); + + /** Field throwExceptions */ + private static final boolean throwExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); + + + /** @inheritDoc */ + public void warning(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } - /** @inheritDoc */ - public void error(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.SEVERE, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void error(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.SEVERE, "", ex); } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } - - /** @inheritDoc */ - public void fatalError(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void fatalError(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); + } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; } + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java 2013-06-28 11:34:28.836708331 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java 2013-06-28 11:34:28.668713560 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; @@ -33,8 +35,8 @@ */ public class JavaUtils { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(JavaUtils.class.getName()); private JavaUtils() { @@ -45,7 +47,7 @@ * Method getBytesFromFile * * @param fileName - * @return the bytes readed from the file + * @return the bytes read from the file * * @throws FileNotFoundException * @throws IOException @@ -55,9 +57,11 @@ byte refBytes[] = null; - FileInputStream fisRef = new FileInputStream(fileName); + FileInputStream fisRef = null; + UnsyncByteArrayOutputStream baos = null; try { - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); + fisRef = new FileInputStream(fileName); + baos = new UnsyncByteArrayOutputStream(); byte buf[] = new byte[1024]; int len; @@ -67,7 +71,12 @@ refBytes = baos.toByteArray(); } finally { - fisRef.close(); + if (baos != null) { + baos.close(); + } + if (fisRef != null) { + fisRef.close(); + } } return refBytes; @@ -80,7 +89,6 @@ * @param bytes */ public static void writeBytesToFilename(String filename, byte[] bytes) { - FileOutputStream fos = null; try { if (filename != null && bytes != null) { @@ -91,41 +99,50 @@ fos.write(bytes); fos.close(); } else { - log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + } } } catch (IOException ex) { if (fos != null) { try { fos.close(); - } catch (IOException ioe) {} + } catch (IOException ioe) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe); + } + } } } } /** - * This method reads all bytes from the given InputStream till EOF and + * This method reads all bytes from the given InputStream till EOF and * returns them as a byte array. * * @param inputStream - * @return the bytes readed from the stream + * @return the bytes read from the stream * * @throws FileNotFoundException * @throws IOException */ - public static byte[] getBytesFromStream(InputStream inputStream) - throws IOException { - - byte refBytes[] = null; - - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int len; - - while ((len = inputStream.read(buf)) > 0) { - baos.write(buf, 0, len); + public static byte[] getBytesFromStream(InputStream inputStream) throws IOException { + UnsyncByteArrayOutputStream baos = null; + + byte[] retBytes = null; + try { + baos = new UnsyncByteArrayOutputStream(); + byte buf[] = new byte[4 * 1024]; + int len; + + while ((len = inputStream.read(buf)) > 0) { + baos.write(buf, 0, len); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); } - refBytes = baos.toByteArray(); - return refBytes; + return retBytes; } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java 2013-06-28 11:34:29.524686916 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java 2013-06-28 11:34:29.348692395 -0400 @@ -2,573 +2,473 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; - - import java.io.IOException; import java.io.StringReader; - -/** - * - * @author $Author: mullan $ - */ public class RFC2253Parser { + + /** + * Method rfc2253toXMLdsig + * + * @param dn + * @return normalized string + */ + public static String rfc2253toXMLdsig(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, true); + + return rfctoXML(normalized); + } + + /** + * Method xmldsigtoRFC2253 + * + * @param dn + * @return normalized string + */ + public static String xmldsigtoRFC2253(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, false); + + return xmltoRFC(normalized); + } + + /** + * Method normalize + * + * @param dn + * @return normalized string + */ + public static String normalize(String dn) { + return normalize(dn, true); + } + + /** + * Method normalize + * + * @param dn + * @param toXml + * @return normalized string + */ + public static String normalize(String dn, boolean toXml) { + //if empty string + if ((dn == null) || dn.equals("")) { + return ""; + } + + try { + String DN = semicolonToComma(dn); + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; + + //for name component + for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) { + l += countQuotes(DN, j, k); + + if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ","); + + i = k + 1; + l = 0; + } + } + + sb.append(parseRDN(trim(DN.substring(i)), toXml)); + return sb.toString(); + } catch (IOException ex) { + return dn; + } + } + + /** + * Method parseRDN + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseRDN(String str, boolean toXml) throws IOException { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** {@link java.util.logging} logging facility */ - /* static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(RFC2253Parser.class.getName()); - */ - - static boolean _TOXML = true; - - /** - * Method rfc2253toXMLdsig - * - * @param dn - * @return normalized string - * - */ - public static String rfc2253toXMLdsig(String dn) { - - _TOXML = true; - - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); - - return rfctoXML(normalized); - } - - /** - * Method xmldsigtoRFC2253 - * - * @param dn - * @return normalized string - */ - public static String xmldsigtoRFC2253(String dn) { - - _TOXML = false; - - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); - - return xmltoRFC(normalized); - } - - /** - * Method normalize - * - * @param dn - * @return normalized string - */ - public static String normalize(String dn) { - - //if empty string - if ((dn == null) || dn.equals("")) { - return ""; - } - - try { - String _DN = semicolonToComma(dn); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; - - //for name component - for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) { - l += countQuotes(_DN, j, k); + for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - if ((k > 0) && (_DN.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseRDN(_DN.substring(i, k).trim()) + ","); + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+"); - i = k + 1; - l = 0; + i = k + 1; + l = 0; } - } + } - sb.append(parseRDN(trim(_DN.substring(i)))); + sb.append(parseATAV(trim(str.substring(i)), toXml)); - return sb.toString(); - } catch (IOException ex) { - return dn; - } - } - - /** - * Method parseRDN - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseRDN(String str) throws IOException { - - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; - - for (int j = 0; (k = str.indexOf("+", j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); - - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseATAV(trim(str.substring(i, k))) + "+"); - - i = k + 1; - l = 0; - } - } - - sb.append(parseATAV(trim(str.substring(i)))); - - return sb.toString(); - } - - /** - * Method parseATAV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseATAV(String str) throws IOException { - - int i = str.indexOf("="); - - if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { - return str; - } - String attrType = normalizeAT(str.substring(0, i)); - // only normalize if value is a String - String attrValue = null; - if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { - attrValue = str.substring(i + 1); - } else { - attrValue = normalizeV(str.substring(i + 1)); - } - - return attrType + "=" + attrValue; - - } - - /** - * Method normalizeAT - * - * @param str - * @return normalized string - */ - static String normalizeAT(String str) { - - String at = str.toUpperCase().trim(); - - if (at.startsWith("OID")) { - at = at.substring(3); - } - - return at; - } - - /** - * Method normalizeV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String normalizeV(String str) throws IOException { - - String value = trim(str); - - if (value.startsWith("\"")) { - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(value.substring(1, - value.length() - 1)); - int i = 0; - char c; + return sb.toString(); + } - for (; (i = sr.read()) > -1; ) { - c = (char) i; + /** + * Method parseATAV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseATAV(String str, boolean toXml) throws IOException { + int i = str.indexOf('='); + + if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { + return str; + } + String attrType = normalizeAT(str.substring(0, i)); + // only normalize if value is a String + String attrValue = null; + if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { + attrValue = str.substring(i + 1); + } else { + attrValue = normalizeV(str.substring(i + 1), toXml); + } + + return attrType + "=" + attrValue; + + } + + /** + * Method normalizeAT + * + * @param str + * @return normalized string + */ + static String normalizeAT(String str) { + + String at = str.toUpperCase().trim(); + + if (at.startsWith("OID")) { + at = at.substring(3); + } + + return at; + } + + /** + * Method normalizeV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String normalizeV(String str, boolean toXml) throws IOException { + String value = trim(str); + + if (value.startsWith("\"")) { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(value.substring(1, value.length() - 1)); + int i = 0; + char c; + + while ((i = sr.read()) > -1) { + c = (char) i; - //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 - if ((c == ',') || (c == '=') || (c == '+') || (c == '<') + //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 + if ((c == ',') || (c == '=') || (c == '+') || (c == '<') || (c == '>') || (c == '#') || (c == ';')) { - sb.append('\\'); + sb.append('\\'); + } + + sb.append(c); } - sb.append(c); - } + value = trim(sb.toString()); + } - value = trim(sb.toString()); - } + if (toXml) { + if (value.startsWith("#")) { + value = '\\' + value; + } + } else { + if (value.startsWith("\\#")) { + value = value.substring(1); + } + } - if (_TOXML == true) { - if (value.startsWith("#")) { - value = '\\' + value; - } - } else { - if (value.startsWith("\\#")) { - value = value.substring(1); - } - } - - return value; - } - - /** - * Method rfctoXML - * - * @param string - * @return normalized string - */ - static String rfctoXML(String string) { - - try { - String s = changeLess32toXML(string); - - return changeWStoXML(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method xmltoRFC - * - * @param string - * @return normalized string - */ - static String xmltoRFC(String string) { - - try { - String s = changeLess32toRFC(string); - - return changeWStoRFC(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method changeLess32toRFC - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toRFC(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; + return value; + } - if (c == '\\') { - sb.append(c); + /** + * Method rfctoXML + * + * @param string + * @return normalized string + */ + static String rfctoXML(String string) { + try { + String s = changeLess32toXML(string); + + return changeWStoXML(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method xmltoRFC + * + * @param string + * @return normalized string + */ + static String xmltoRFC(String string) { + try { + String s = changeLess32toRFC(string); + + return changeWStoRFC(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method changeLess32toRFC + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toRFC(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; - char c1 = (char) sr.read(); - char c2 = (char) sr.read(); + while ((i = sr.read()) > -1) { + c = (char) i; - //65 (A) 97 (a) - if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) + if (c == '\\') { + sb.append(c); + + char c1 = (char) sr.read(); + char c2 = (char) sr.read(); + + //65 (A) 97 (a) + if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) && (((c2 >= 48) && (c2 <= 57)) || ((c2 >= 65) && (c2 <= 70)) || ((c2 >= 97) && (c2 <= 102)))) { - char ch = (char) Byte.parseByte("" + c1 + c2, 16); + char ch = (char) Byte.parseByte("" + c1 + c2, 16); - sb.append(ch); + sb.append(ch); + } else { + sb.append(c1); + sb.append(c2); + } } else { - sb.append(c1); - sb.append(c2); + sb.append(c); } - } else { - sb.append(c); - } - } - - return sb.toString(); - } - - /** - * Method changeLess32toXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toXML(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - - for (; (i = sr.read()) > -1; ) { - if (i < 32) { - sb.append('\\'); - sb.append(Integer.toHexString(i)); - } else { - sb.append((char) i); - } - } - - return sb.toString(); - } - - /** - * Method changeWStoXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeWStoXML(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - char c1 = (char) sr.read(); + } + + return sb.toString(); + } - if (c1 == ' ') { - sb.append('\\'); + /** + * Method changeLess32toXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + + while ((i = sr.read()) > -1) { + if (i < 32) { + sb.append('\\'); + sb.append(Integer.toHexString(i)); + } else { + sb.append((char) i); + } + } - String s = "20"; + return sb.toString(); + } - sb.append(s); + /** + * Method changeWStoXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeWStoXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; + + while ((i = sr.read()) > -1) { + c = (char) i; + + if (c == '\\') { + char c1 = (char) sr.read(); + + if (c1 == ' ') { + sb.append('\\'); + + String s = "20"; + + sb.append(s); + } else { + sb.append('\\'); + sb.append(c1); + } } else { - sb.append('\\'); - sb.append(c1); + sb.append(c); } - } else { - sb.append(c); - } - } - - return sb.toString(); - } - - /** - * Method changeWStoRFC - * - * @param string - * @return normalized string - */ - static String changeWStoRFC(String string) { - - StringBuffer sb = new StringBuffer(); - int i = 0; - int k; - - for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { - sb.append(trim(string.substring(i, k)) + "\\ "); - - i = k + 3; - } - - sb.append(string.substring(i)); - - return sb.toString(); - } - - /** - * Method semicolonToComma - * - * @param str - * @return normalized string - */ - static String semicolonToComma(String str) { - return removeWSandReplace(str, ";", ","); - } - - /** - * Method removeWhiteSpace - * - * @param str - * @param symbol - * @return normalized string - */ - static String removeWhiteSpace(String str, String symbol) { - return removeWSandReplace(str, symbol, symbol); - } - - /** - * Method removeWSandReplace - * - * @param str - * @param symbol - * @param replace - * @return normalized string - */ - static String removeWSandReplace(String str, String symbol, String replace) { - - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; - - for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); - - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(trim(str.substring(i, k)) + replace); - - i = k + 1; - l = 0; - } - } - - sb.append(trim(str.substring(i))); - - return sb.toString(); - } - - /** - * Returns the number of Quotation from i to j - * - * @param s - * @param i - * @param j - * @return number of quotes - */ - private static int countQuotes(String s, int i, int j) { - - int k = 0; - - for (int l = i; l < j; l++) { - if (s.charAt(l) == '"') { - k++; - } - } - - return k; - } - - //only for the end of a space character occurring at the end of the string from rfc2253 - - /** - * Method trim - * - * @param str - * @return the string - */ - static String trim(String str) { - - String trimed = str.trim(); - int i = str.indexOf(trimed) + trimed.length(); - - if ((str.length() > i) && trimed.endsWith("\\") - &&!trimed.endsWith("\\\\")) { - if (str.charAt(i) == ' ') { + } + + return sb.toString(); + } + + /** + * Method changeWStoRFC + * + * @param string + * @return normalized string + */ + static String changeWStoRFC(String string) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int k; + + for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { + sb.append(trim(string.substring(i, k)) + "\\ "); + + i = k + 3; + } + + sb.append(string.substring(i)); + + return sb.toString(); + } + + /** + * Method semicolonToComma + * + * @param str + * @return normalized string + */ + static String semicolonToComma(String str) { + return removeWSandReplace(str, ";", ","); + } + + /** + * Method removeWhiteSpace + * + * @param str + * @param symbol + * @return normalized string + */ + static String removeWhiteSpace(String str, String symbol) { + return removeWSandReplace(str, symbol, symbol); + } + + /** + * Method removeWSandReplace + * + * @param str + * @param symbol + * @param replace + * @return normalized string + */ + static String removeWSandReplace(String str, String symbol, String replace) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; + + for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); + + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(trim(str.substring(i, k)) + replace); + + i = k + 1; + l = 0; + } + } + + sb.append(trim(str.substring(i))); + + return sb.toString(); + } + + /** + * Returns the number of Quotation from i to j + * + * @param s + * @param i + * @param j + * @return number of quotes + */ + private static int countQuotes(String s, int i, int j) { + int k = 0; + + for (int l = i; l < j; l++) { + if (s.charAt(l) == '"') { + k++; + } + } + + return k; + } + + //only for the end of a space character occurring at the end of the string from rfc2253 + + /** + * Method trim + * + * @param str + * @return the string + */ + static String trim(String str) { + + String trimed = str.trim(); + int i = str.indexOf(trimed) + trimed.length(); + + if ((str.length() > i) && trimed.endsWith("\\") + && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) { trimed = trimed + " "; - } - } + } - return trimed; - } + return trimed; + } - /** - * Method main - * - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - - testToXML("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToXML("CN=Steve Kille , O=Isode Limited,C=GB"); - testToXML("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ "); - testToXML("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToXML("CN=Before\\0DAfter,O=Test,C=GB"); - testToXML("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToXML("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToXML(test7); - } - - testToRFC("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToRFC("CN=Steve Kille , O=Isode Limited,C=GB"); - testToRFC("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 "); - testToRFC("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToRFC("CN=Before\\12After,O=Test,C=GB"); - testToRFC("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToRFC("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToRFC(test7); - } - } - - /** Field i */ - static int counter = 0; - - /** - * Method test - * - * @param st - */ - static void testToXML(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + rfc2253toXMLdsig(st)); - System.out.println(""); - } - - /** - * Method testToRFC - * - * @param st - */ - static void testToRFC(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + xmldsigtoRFC2253(st)); - System.out.println(""); - } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java 2013-06-28 11:34:30.212665501 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java 2013-06-28 11:34:30.044670730 -0400 @@ -2,70 +2,69 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * Class SignatureElementProxy * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ + * @author $Author: coheigea $ */ public abstract class SignatureElementProxy extends ElementProxy { - protected SignatureElementProxy() { - }; - /** - * Constructor SignatureElementProxy - * - * @param doc - */ - public SignatureElementProxy(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - this._doc = doc; - this._constructionElement = XMLUtils.createElementInSignatureSpace(this._doc, - this.getBaseLocalName()); - } - - /** - * Constructor SignatureElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SignatureElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - - } - - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } + + protected SignatureElementProxy() { + }; + + /** + * Constructor SignatureElementProxy + * + * @param doc + */ + public SignatureElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName()); + } + + /** + * Constructor SignatureElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java 2013-06-28 11:34:30.860645331 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java 2013-06-28 11:34:30.688650685 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; @@ -30,53 +32,50 @@ * */ public class SignerOutputStream extends ByteArrayOutputStream { + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignerOutputStream.class.getName()); + final SignatureAlgorithm sa; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (SignerOutputStream.class.getName()); /** * @param sa */ public SignerOutputStream(SignatureAlgorithm sa) { - this.sa=sa; + this.sa = sa; } /** @inheritDoc */ public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); try { sa.update(arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(int arg0) { - super.write(arg0); try { sa.update((byte)arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(byte[] arg0, int arg1, int arg2) { - super.write(arg0, arg1, arg2); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } try { - sa.update(arg0,arg1,arg2); + sa.update(arg0, arg1, arg2); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java 2013-06-28 11:34:31.544624040 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java 2013-06-28 11:34:31.368629519 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; @@ -24,75 +26,73 @@ import java.io.OutputStream; /** - * A class that buffers writte without synchronize its methods + * A class that buffers without synchronizing its methods * @author raul - * */ public class UnsyncBufferedOutputStream extends OutputStream { - final OutputStream out; - - final byte[] buf; - static final int size=8*1024; - private static ThreadLocal bufCahce = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[size]; - } - }; - int pointer=0; - /** - * Creates a buffered output stream without synchronization - * @param out the outputstream to buffer - */ - public UnsyncBufferedOutputStream(OutputStream out) { - buf=bufCahce.get(); - this.out=out; - } - - /** @inheritDoc */ - public void write(byte[] arg0) throws IOException { - write(arg0,0,arg0.length); - } - - /** @inheritDoc */ - public void write(byte[] arg0, int arg1, int len) throws IOException { - int newLen=pointer+len; - if (newLen> size) { - flushBuffer(); - if (len>size) { - out.write(arg0,arg1,len); - return; - } - newLen=len; - } - System.arraycopy(arg0,arg1,buf,pointer,len); - pointer=newLen; - } - - private final void flushBuffer() throws IOException { - if (pointer>0) - out.write(buf,0,pointer); - pointer=0; - - } - - /** @inheritDoc */ - public void write(int arg0) throws IOException { - if (pointer>= size) { - flushBuffer(); - } - buf[pointer++]=(byte)arg0; - - } - - /** @inheritDoc */ - public void flush() throws IOException { - flushBuffer(); - out.flush(); - } - - /** @inheritDoc */ - public void close() throws IOException { - flush(); - } + static final int size = 8*1024; + + private int pointer = 0; + private final OutputStream out; + + private final byte[] buf; + + /** + * Creates a buffered output stream without synchronization + * @param out the outputstream to buffer + */ + public UnsyncBufferedOutputStream(OutputStream out) { + buf = new byte[size]; + this.out = out; + } + + /** @inheritDoc */ + public void write(byte[] arg0) throws IOException { + write(arg0, 0, arg0.length); + } + + /** @inheritDoc */ + public void write(byte[] arg0, int arg1, int len) throws IOException { + int newLen = pointer+len; + if (newLen > size) { + flushBuffer(); + if (len > size) { + out.write(arg0, arg1,len); + return; + } + newLen = len; + } + System.arraycopy(arg0, arg1, buf, pointer, len); + pointer = newLen; + } + + private void flushBuffer() throws IOException { + if (pointer > 0) { + out.write(buf, 0, pointer); + } + pointer = 0; + + } + + /** @inheritDoc */ + public void write(int arg0) throws IOException { + if (pointer >= size) { + flushBuffer(); + } + buf[pointer++] = (byte)arg0; + + } + + /** @inheritDoc */ + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } + + /** @inheritDoc */ + public void close() throws IOException { + flush(); + out.close(); + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java 2013-06-28 11:34:32.184604119 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java 2013-06-28 11:34:32.008609598 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2010 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; @@ -27,23 +29,22 @@ * @author raul * */ -public class UnsyncByteArrayOutputStream extends OutputStream { +public class UnsyncByteArrayOutputStream extends OutputStream { + private static final int INITIAL_SIZE = 8192; - private static ThreadLocal bufCache = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[INITIAL_SIZE]; - } - }; private byte[] buf; private int size = INITIAL_SIZE; private int pos = 0; public UnsyncByteArrayOutputStream() { - buf = bufCache.get(); + buf = new byte[INITIAL_SIZE]; } public void write(byte[] arg0) { + if ((Integer.MAX_VALUE - pos) < arg0.length) { + throw new OutOfMemoryError(); + } int newPos = pos + arg0.length; if (newPos > size) { expandSize(newPos); @@ -53,6 +54,9 @@ } public void write(byte[] arg0, int arg1, int arg2) { + if ((Integer.MAX_VALUE - pos) < arg2) { + throw new OutOfMemoryError(); + } int newPos = pos + arg2; if (newPos > size) { expandSize(newPos); @@ -62,11 +66,14 @@ } public void write(int arg0) { + if ((Integer.MAX_VALUE - pos) == 0) { + throw new OutOfMemoryError(); + } int newPos = pos + 1; if (newPos > size) { expandSize(newPos); } - buf[pos++] = (byte)arg0; + buf[pos++] = (byte)arg0; } public byte[] toByteArray() { @@ -78,11 +85,15 @@ public void reset() { pos = 0; } - + private void expandSize(int newPos) { int newSize = size; while (newPos > newSize) { - newSize = newSize<<2; + newSize = newSize << 1; + // Deal with overflow + if (newSize < 0) { + newSize = Integer.MAX_VALUE; + } } byte newBuf[] = new byte[newSize]; System.arraycopy(buf, 0, newBuf, 0, pos); --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java 2013-06-28 11:34:32.864582953 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java 2013-06-28 11:34:32.700588058 -0400 @@ -2,35 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils; - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Set; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -42,10 +41,9 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; - - /** * DOM and XML accessibility and comfort functions. * @@ -53,37 +51,48 @@ */ public class XMLUtils { - private static boolean ignoreLineBreaks = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"); - } - }); - + private static boolean ignoreLineBreaks = + AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks")); + } + }).booleanValue(); + private static volatile String dsPrefix = "ds"; + private static volatile String ds11Prefix = "dsig11"; private static volatile String xencPrefix = "xenc"; + private static volatile String xenc11Prefix = "xenc11"; + + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLUtils.class.getName()); - private static final java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLUtils.class.getName()); - - /** - * Constructor XMLUtils - * - */ - private XMLUtils() { - - // we don't allow instantiation - } /** + * Constructor XMLUtils + * + */ + private XMLUtils() { + // we don't allow instantiation + } + + /** * Set the prefix for the digital signature namespace * @param prefix the new prefix for the digital signature namespace */ public static void setDsPrefix(String prefix) { dsPrefix = prefix; } - + + /** + * Set the prefix for the digital signature 1.1 namespace + * @param prefix the new prefix for the digital signature 1.1 namespace + */ + public static void setDs11Prefix(String prefix) { + ds11Prefix = prefix; + } + /** * Set the prefix for the encryption namespace * @param prefix the new prefix for the encryption namespace @@ -91,198 +100,257 @@ public static void setXencPrefix(String prefix) { xencPrefix = prefix; } + + /** + * Set the prefix for the encryption namespace 1.1 + * @param prefix the new prefix for the encryption namespace 1.1 + */ + public static void setXenc11Prefix(String prefix) { + xenc11Prefix = prefix; + } + + public static Element getNextElement(Node el) { + Node node = el; + while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) { + node = node.getNextSibling(); + } + return (Element)node; + } + + /** + * @param rootNode + * @param result + * @param exclude + * @param com whether comments or not + */ + public static void getSet(Node rootNode, Set result, Node exclude, boolean com) { + if ((exclude != null) && isDescendantOrSelf(exclude, rootNode)) { + return; + } + getSetRec(rootNode, result, exclude, com); + } + + @SuppressWarnings("fallthrough") + private static void getSetRec(final Node rootNode, final Set result, + final Node exclude, final boolean com) { + if (rootNode == exclude) { + return; + } + switch (rootNode.getNodeType()) { + case Node.ELEMENT_NODE: + result.add(rootNode); + Element el = (Element)rootNode; + if (el.hasAttributes()) { + NamedNodeMap nl = el.getAttributes(); + for (int i = 0;i < nl.getLength(); i++) { + result.add(nl.item(i)); + } + } + //no return keep working + case Node.DOCUMENT_NODE: + for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) { + if (r.getNodeType() == Node.TEXT_NODE) { + result.add(r); + while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) { + r = r.getNextSibling(); + } + if (r == null) { + return; + } + } + getSetRec(r, result, exclude, com); + } + return; + case Node.COMMENT_NODE: + if (com) { + result.add(rootNode); + } + return; + case Node.DOCUMENT_TYPE_NODE: + return; + default: + result.add(rootNode); + } + } - public static Element getNextElement(Node el) { - while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) { - el=el.getNextSibling(); - } - return (Element)el; - - } - - /** - * @param rootNode - * @param result - * @param exclude - * @param com wheather comments or not - */ - public static void getSet(Node rootNode,Set result,Node exclude ,boolean com) { - if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){ - return; - } - getSetRec(rootNode,result,exclude,com); - } - - @SuppressWarnings("fallthrough") - static final void getSetRec(final Node rootNode,final Set result, - final Node exclude ,final boolean com) { - //Set result = new HashSet(); - if (rootNode==exclude) { - return; - } - switch (rootNode.getNodeType()) { - case Node.ELEMENT_NODE: - result.add(rootNode); - Element el=(Element)rootNode; - if (el.hasAttributes()) { - NamedNodeMap nl = ((Element)rootNode).getAttributes(); - for (int i=0;iIf an Exception is - * thrown during execution, it's StackTrace is output to System.out, but the - * Exception is not re-thrown. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - * @param addPreamble - */ - public static void outputDOM(Node contextNode, OutputStream os, - boolean addPreamble) { - - try { - if (addPreamble) { - os.write("\n".getBytes()); - } - - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) {} - catch (InvalidCanonicalizerException ex) { - ex.printStackTrace(); - } catch (CanonicalizationException ex) { - ex.printStackTrace(); - } - } - - /** - * Serializes the contextNode into the OutputStream, but - * supresses all Exceptions. - *
      - * NOTE: This should only be used for debugging purposes, - * NOT in a production environment; this method ignores all exceptions, - * so you won't notice if something goes wrong. If you're asking what is to - * be used in a production environment, simply use the code inside the - * try{} statement, but handle the Exceptions appropriately. - * - * @param contextNode - * @param os - */ - public static void outputDOMc14nWithComments(Node contextNode, - OutputStream os) { - - try { - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) { - - // throw new RuntimeException(ex.getMessage()); - } catch (InvalidCanonicalizerException ex) { - - // throw new RuntimeException(ex.getMessage()); - } catch (CanonicalizationException ex) { - - // throw new RuntimeException(ex.getMessage()); - } - } - - - /** - * Method getFullTextChildrenFromElement - * - * @param element - * @return the string of chi;ds - */ - public static String getFullTextChildrenFromElement(Element element) { - - StringBuffer sb = new StringBuffer(); - NodeList children = element.getChildNodes(); - int iMax = children.getLength(); - - for (int i = 0; i < iMax; i++) { - Node curr = children.item(i); - - if (curr.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) curr).getData()); - } - } - - return sb.toString(); - } - - static Map namePrefixes=new HashMap(); - - /** - * Creates an Element in the XML Signature specification namespace. - * - * @param doc the factory Document - * @param elementName the local name of the Element - * @return the Element - */ - public static Element createElementInSignatureSpace(Document doc, - String elementName) { - - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - if ((dsPrefix == null) || (dsPrefix.length() == 0)) { - return doc.createElementNS(Constants.SignatureSpecNS, elementName); - } - String namePrefix= namePrefixes.get(elementName); - if (namePrefix==null) { - StringBuffer tag=new StringBuffer(dsPrefix); - tag.append(':'); - tag.append(elementName); - namePrefix=tag.toString(); - namePrefixes.put(elementName,namePrefix); - } - return doc.createElementNS(Constants.SignatureSpecNS, namePrefix); - } + + /** + * Outputs a DOM tree to an {@link OutputStream}. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + */ + public static void outputDOM(Node contextNode, OutputStream os) { + XMLUtils.outputDOM(contextNode, os, false); + } + + /** + * Outputs a DOM tree to an {@link OutputStream}. If an Exception is + * thrown during execution, it's StackTrace is output to System.out, but the + * Exception is not re-thrown. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + * @param addPreamble + */ + public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) { + try { + if (addPreamble) { + os.write("\n".getBytes("UTF-8")); + } + + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } + + /** + * Serializes the contextNode into the OutputStream, but + * suppresses all Exceptions. + *
      + * NOTE: This should only be used for debugging purposes, + * NOT in a production environment; this method ignores all exceptions, + * so you won't notice if something goes wrong. If you're asking what is to + * be used in a production environment, simply use the code inside the + * try{} statement, but handle the Exceptions appropriately. + * + * @param contextNode + * @param os + */ + public static void outputDOMc14nWithComments(Node contextNode, OutputStream os) { + try { + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } + } + + /** + * Method getFullTextChildrenFromElement + * + * @param element + * @return the string of children + */ + public static String getFullTextChildrenFromElement(Element element) { + StringBuilder sb = new StringBuilder(); + + Node child = element.getFirstChild(); + while (child != null) { + if (child.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text)child).getData()); + } + child = child.getNextSibling(); + } + + return sb.toString(); + } + + /** + * Creates an Element in the XML Signature specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignatureSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + if ((dsPrefix == null) || (dsPrefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpecNS, elementName); + } + return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName); + } + + /** + * Creates an Element in the XML Signature 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignature11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpec11NS, elementName); + } + return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName); + } + + /** + * Creates an Element in the XML Encryption specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryptionSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + if ((xencPrefix == null) || (xencPrefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName + ); + } + + /** + * Creates an Element in the XML Encryption 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryption11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName + ); + } /** * Returns true if the element is in XML Signature namespace and the local @@ -290,14 +358,33 @@ * * @param element * @param localName - * @return true if the element is in XML Signature namespace and the local name equals the supplied one + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one */ public static boolean elementIsInSignatureSpace(Element element, String localName) { + if (element == null){ + return false; + } + + return Constants.SignatureSpecNS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } + + /** + * Returns true if the element is in XML Signature 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one + */ + public static boolean elementIsInSignature11Space(Element element, String localName) { if (element == null) { return false; } - return Constants.SignatureSpecNS.equals(element.getNamespaceURI()) + return Constants.SignatureSpec11NS.equals(element.getNamespaceURI()) && element.getLocalName().equals(localName); } @@ -307,67 +394,83 @@ * * @param element * @param localName - * @return true if the element is in XML Encryption namespace and the local name equals the supplied one + * @return true if the element is in XML Encryption namespace and the local name + * equals the supplied one */ public static boolean elementIsInEncryptionSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } - return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI()) + return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } + + /** + * Returns true if the element is in XML Encryption 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Encryption 1.1 namespace and the local name + * equals the supplied one + */ + public static boolean elementIsInEncryption11Space(Element element, String localName) { + if (element == null){ + return false; + } + return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI()) && element.getLocalName().equals(localName); } - /** - * This method returns the owner document of a particular node. - * This method is necessary because it always returns a - * {@link Document}. {@link Node#getOwnerDocument} returns null - * if the {@link Node} is a {@link Document}. - * - * @param node - * @return the owner document of the node - */ - public static Document getOwnerDocument(Node node) { - - if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { + /** + * This method returns the owner document of a particular node. + * This method is necessary because it always returns a + * {@link Document}. {@link Node#getOwnerDocument} returns null + * if the {@link Node} is a {@link Document}. + * + * @param node + * @return the owner document of the node + */ + public static Document getOwnerDocument(Node node) { + if (node.getNodeType() == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { return node.getOwnerDocument(); - } catch (NullPointerException npe) { + } catch (NullPointerException npe) { throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + npe.getMessage() + "\""); - } - - } + } + } /** - * This method returns the first non-null owner document of the Node's in this Set. + * This method returns the first non-null owner document of the Nodes in this Set. * This method is necessary because it always returns a * {@link Document}. {@link Node#getOwnerDocument} returns null * if the {@link Node} is a {@link Document}. * * @param xpathNodeSet - * @return the owner document + * @return the owner document */ public static Document getOwnerDocument(Set xpathNodeSet) { - NullPointerException npe = null; - for (Node node : xpathNodeSet) { - int nodeType =node.getNodeType(); - if (nodeType == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { - if (nodeType==Node.ATTRIBUTE_NODE) { - return ((Attr)node).getOwnerElement().getOwnerDocument(); - } - return node.getOwnerDocument(); - } catch (NullPointerException e) { - npe = e; - } - - } - throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + NullPointerException npe = null; + for (Node node : xpathNodeSet) { + int nodeType = node.getNodeType(); + if (nodeType == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { + if (nodeType == Node.ATTRIBUTE_NODE) { + return ((Attr)node).getOwnerElement().getOwnerDocument(); + } + return node.getOwnerDocument(); + } catch (NullPointerException e) { + npe = e; + } + } + + throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + (npe == null ? "" : npe.getMessage()) + "\""); } @@ -380,169 +483,185 @@ * @param namespace * @return the element. */ - public static Element createDSctx(Document doc, String prefix, - String namespace) { + public static Element createDSctx(Document doc, String prefix, String namespace) { + if ((prefix == null) || (prefix.trim().length() == 0)) { + throw new IllegalArgumentException("You must supply a prefix"); + } - if ((prefix == null) || (prefix.trim().length() == 0)) { - throw new IllegalArgumentException("You must supply a prefix"); - } - - Element ctx = doc.createElementNS(null, "namespaceContext"); - - ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), - namespace); - - return ctx; - } - - /** - * Method addReturnToElement - * - * @param e - */ - public static void addReturnToElement(Element e) { - - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.appendChild(doc.createTextNode("\n")); - } - } - - public static void addReturnToElement(Document doc, HelperNodeList nl) { - if (!ignoreLineBreaks) { - nl.appendChild(doc.createTextNode("\n")); - } - } - - public static void addReturnBeforeChild(Element e, Node child) { - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.insertBefore(doc.createTextNode("\n"), child); - } - } - - /** - * Method convertNodelistToSet - * - * @param xpathNodeSet - * @return the set with the nodelist - */ - public static Set convertNodelistToSet(NodeList xpathNodeSet) { - - if (xpathNodeSet == null) { - return new HashSet(); - } - - int length = xpathNodeSet.getLength(); - Set set = new HashSet(length); - - for (int i = 0; i < length; i++) { - set.add(xpathNodeSet.item(i)); - } - - return set; - } - - - /** - * This method spreads all namespace attributes in a DOM document to their - * children. This is needed because the XML Signature XPath transform - * must evaluate the XPath against all nodes in the input, even against - * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are - * not fully visible in the Xalan XPath model, so we have to do this by - * hand in DOM spaces so that the nodes become visible in XPath space. - * - * @param doc - * @see Namespace axis resolution is not XPath compliant - */ - public static void circumventBug2650(Document doc) { - - Element documentElement = doc.getDocumentElement(); - - // if the document element has no xmlns definition, we add xmlns="" - Attr xmlnsAttr = - documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - - if (xmlnsAttr == null) { - documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); - } - - XMLUtils.circumventBug2650internal(doc); - } - - /** - * This is the work horse for {@link #circumventBug2650}. - * - * @param node - * @see Namespace axis resolution is not XPath compliant - */ - @SuppressWarnings("fallthrough") - private static void circumventBug2650internal(Node node) { - Node parent=null; - Node sibling=null; - final String namespaceNs=Constants.NamespaceSpecNS; - do { - switch (node.getNodeType()) { - case Node.ELEMENT_NODE : - Element element = (Element) node; - if (!element.hasChildNodes()) - break; - if (element.hasAttributes()) { - NamedNodeMap attributes = element.getAttributes(); - int attributesLength = attributes.getLength(); - - for (Node child = element.getFirstChild(); child!=null; - child=child.getNextSibling()) { - - if (child.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - Element childElement = (Element) child; - - for (int i = 0; i < attributesLength; i++) { - Attr currentAttr = (Attr) attributes.item(i); - if (namespaceNs!=currentAttr.getNamespaceURI()) - continue; - if (childElement.hasAttributeNS(namespaceNs, - currentAttr.getLocalName())) { - continue; - } - childElement.setAttributeNS(namespaceNs, - currentAttr.getName(), - currentAttr.getNodeValue()); + Element ctx = doc.createElementNS(null, "namespaceContext"); + + ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace); + + return ctx; + } + + /** + * Method addReturnToElement + * + * @param e + */ + public static void addReturnToElement(Element e) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.appendChild(doc.createTextNode("\n")); + } + } + + public static void addReturnToElement(Document doc, HelperNodeList nl) { + if (!ignoreLineBreaks) { + nl.appendChild(doc.createTextNode("\n")); + } + } + + public static void addReturnBeforeChild(Element e, Node child) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.insertBefore(doc.createTextNode("\n"), child); + } + } + + /** + * Method convertNodelistToSet + * + * @param xpathNodeSet + * @return the set with the nodelist + */ + public static Set convertNodelistToSet(NodeList xpathNodeSet) { + if (xpathNodeSet == null) { + return new HashSet(); + } + int length = xpathNodeSet.getLength(); + Set set = new HashSet(length); + for (int i = 0; i < length; i++) { + set.add(xpathNodeSet.item(i)); + } + + return set; + } + + /** + * This method spreads all namespace attributes in a DOM document to their + * children. This is needed because the XML Signature XPath transform + * must evaluate the XPath against all nodes in the input, even against + * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are + * not fully visible in the Xalan XPath model, so we have to do this by + * hand in DOM spaces so that the nodes become visible in XPath space. + * + * @param doc + * @see + * Namespace axis resolution is not XPath compliant + */ + public static void circumventBug2650(Document doc) { + + Element documentElement = doc.getDocumentElement(); + + // if the document element has no xmlns definition, we add xmlns="" + Attr xmlnsAttr = + documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); + + if (xmlnsAttr == null) { + documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); + } + + XMLUtils.circumventBug2650internal(doc); + } + + /** + * This is the work horse for {@link #circumventBug2650}. + * + * @param node + * @see + * Namespace axis resolution is not XPath compliant + */ + @SuppressWarnings("fallthrough") + private static void circumventBug2650internal(Node node) { + Node parent = null; + Node sibling = null; + final String namespaceNs = Constants.NamespaceSpecNS; + do { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + Element element = (Element) node; + if (!element.hasChildNodes()) { + break; } - } - } - case Node.ENTITY_REFERENCE_NODE : - case Node.DOCUMENT_NODE : - parent=node; - sibling=node.getFirstChild(); - break; - } - while ((sibling==null) && (parent!=null)) { - sibling=parent.getNextSibling(); - parent=parent.getParentNode(); - }; - if (sibling==null) { - return; - } - - node=sibling; - sibling=node.getNextSibling(); - } while (true); - } + if (element.hasAttributes()) { + NamedNodeMap attributes = element.getAttributes(); + int attributesLength = attributes.getLength(); + + for (Node child = element.getFirstChild(); child!=null; + child = child.getNextSibling()) { + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + Element childElement = (Element) child; + + for (int i = 0; i < attributesLength; i++) { + Attr currentAttr = (Attr) attributes.item(i); + if (!namespaceNs.equals(currentAttr.getNamespaceURI())) { + continue; + } + if (childElement.hasAttributeNS(namespaceNs, + currentAttr.getLocalName())) { + continue; + } + childElement.setAttributeNS(namespaceNs, + currentAttr.getName(), + currentAttr.getNodeValue()); + } + } + } + case Node.ENTITY_REFERENCE_NODE : + case Node.DOCUMENT_NODE : + parent = node; + sibling = node.getFirstChild(); + break; + } + while ((sibling == null) && (parent != null)) { + sibling = parent.getNextSibling(); + parent = parent.getParentNode(); + } + if (sibling == null) { + return; + } + + node = sibling; + sibling = node.getNextSibling(); + } while (true); + } + /** * @param sibling * @param nodeName * @param number - * @return nodes with the constrain + * @return nodes with the constraint */ public static Element selectDsNode(Node sibling, String nodeName, int number) { while (sibling != null) { - if (Constants.SignatureSpecNS.equals(sibling.getNamespaceURI()) + if (Constants.SignatureSpecNS.equals(sibling.getNamespaceURI()) + && sibling.getLocalName().equals(nodeName)) { + if (number == 0){ + return (Element)sibling; + } + number--; + } + sibling = sibling.getNextSibling(); + } + return null; + } + + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constraint + */ + public static Element selectDs11Node(Node sibling, String nodeName, int number) { + while (sibling != null) { + if (Constants.SignatureSpec11NS.equals(sibling.getNamespaceURI()) && sibling.getLocalName().equals(nodeName)) { if (number == 0){ return (Element)sibling; @@ -562,7 +681,7 @@ */ public static Element selectXencNode(Node sibling, String nodeName, int number) { while (sibling != null) { - if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI()) + if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI()) && sibling.getLocalName().equals(nodeName)) { if (number == 0){ return (Element)sibling; @@ -574,42 +693,61 @@ return null; } - /** - * @param sibling - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectDsNodeText(Node sibling, String nodeName, int number) { - Node n=selectDsNode(sibling,nodeName,number); - if (n==null) { - return null; - } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDsNodeText(Node sibling, String nodeName, int number) { + Node n = selectDsNode(sibling,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); } return (Text)n; - } - - /** - * @param sibling - * @param uri - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { - Node n=selectNode(sibling,uri,nodeName,number); - if (n==null) { - return null; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDs11NodeText(Node sibling, String nodeName, int number) { + Node n = selectDs11Node(sibling,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; + } + + /** + * @param sibling + * @param uri + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { + Node n = selectNode(sibling,uri,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - return (Text)n; - } /** * @param sibling @@ -620,7 +758,7 @@ */ public static Element selectNode(Node sibling, String uri, String nodeName, int number) { while (sibling != null) { - if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) + if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) && sibling.getLocalName().equals(nodeName)) { if (number == 0){ return (Element)sibling; @@ -634,23 +772,32 @@ /** * @param sibling - * @param nodeName + * @param nodeName * @return nodes with the constrain */ public static Element[] selectDsNodes(Node sibling, String nodeName) { - return selectNodes(sibling,Constants.SignatureSpecNS, nodeName); + return selectNodes(sibling, Constants.SignatureSpecNS, nodeName); } - + + /** + * @param sibling + * @param nodeName + * @return nodes with the constrain + */ + public static Element[] selectDs11Nodes(Node sibling, String nodeName) { + return selectNodes(sibling, Constants.SignatureSpec11NS, nodeName); + } + /** * @param sibling * @param uri * @param nodeName - * @return nodes with the constrain + * @return nodes with the constraint */ - public static Element[] selectNodes(Node sibling, String uri, String nodeName) { + public static Element[] selectNodes(Node sibling, String uri, String nodeName) { List list = new ArrayList(); while (sibling != null) { - if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) + if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) && sibling.getLocalName().equals(nodeName)) { list.add((Element)sibling); } @@ -659,77 +806,121 @@ return list.toArray(new Element[list.size()]); } - /** - * @param signatureElement - * @param inputSet - * @return nodes with the constrain - */ + /** + * @param signatureElement + * @param inputSet + * @return nodes with the constrain + */ public static Set excludeNodeFromSet(Node signatureElement, Set inputSet) { - Set resultSet = new HashSet(); - Iterator iterator = inputSet.iterator(); + Set resultSet = new HashSet(); + Iterator iterator = inputSet.iterator(); - while (iterator.hasNext()) { + while (iterator.hasNext()) { Node inputNode = iterator.next(); - if (!XMLUtils - .isDescendantOrSelf(signatureElement, inputNode)) { - resultSet.add(inputNode); - } - } - return resultSet; - } - - /** - * Returns true if the descendantOrSelf is on the descendant-or-self axis - * of the context node. - * - * @param ctx - * @param descendantOrSelf - * @return true if the node is descendant - */ - static public boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { - - if (ctx == descendantOrSelf) { - return true; - } + if (!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)) { + resultSet.add(inputNode); + } + } + return resultSet; + } + + /** + * Method getStrFromNode + * + * @param xpathnode + * @return the string for the node. + */ + public static String getStrFromNode(Node xpathnode) { + if (xpathnode.getNodeType() == Node.TEXT_NODE) { + // we iterate over all siblings of the context node because eventually, + // the text is "polluted" with pi's or comments + StringBuilder sb = new StringBuilder(); + + for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); + currentSibling != null; + currentSibling = currentSibling.getNextSibling()) { + if (currentSibling.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text) currentSibling).getData()); + } + } - Node parent = descendantOrSelf; + return sb.toString(); + } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { + return ((Attr) xpathnode).getNodeValue(); + } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + return ((ProcessingInstruction) xpathnode).getNodeValue(); + } - while (true) { - if (parent == null) { - return false; - } + return null; + } - if (parent == ctx) { + /** + * Returns true if the descendantOrSelf is on the descendant-or-self axis + * of the context node. + * + * @param ctx + * @param descendantOrSelf + * @return true if the node is descendant + */ + public static boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + if (ctx == descendantOrSelf) { return true; - } + } + + Node parent = descendantOrSelf; + + while (true) { + if (parent == null) { + return false; + } - if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { - parent = ((Attr) parent).getOwnerElement(); - } else { - parent = parent.getParentNode(); - } - } - } + if (parent == ctx) { + return true; + } + + if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { + parent = ((Attr) parent).getOwnerElement(); + } else { + parent = parent.getParentNode(); + } + } + } public static boolean ignoreLineBreaks() { return ignoreLineBreaks; } - + /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no two Elements have ID Attributes that match the "value" - * argument, if this is the case then "false" is returned. Note that a - * return value of "true" does not necessarily mean that a matching Element - * has been found, just that no wrapping attack has been detected. - */ - public static boolean protectAgainstWrappingAttack(Node startNode, - String value) - { + * Returns the attribute value for the attribute with the specified name. + * Returns null if there is no such attribute, or + * the empty string if the attribute value is empty. + * + *

      This works around a limitation of the DOM + * Element.getAttributeNode method, which does not distinguish + * between an unspecified attribute and an attribute with a value of + * "" (it returns "" for both cases). + * + * @param elem the element containing the attribute + * @param name the name of the attribute + * @return the attribute value (may be null if unspecified) + */ + public static String getAttributeValue(Element elem, String name) { + Attr attr = elem.getAttributeNodeNS(null, name); + return (attr == null) ? null : attr.getValue(); + } + + /** + * This method is a tree-search to help prevent against wrapping attacks. It checks that no + * two Elements have ID Attributes that match the "value" argument, if this is the case then + * "false" is returned. Note that a return value of "true" does not necessarily mean that + * a matching Element has been found, just that no wrapping attack has been detected. + */ + public static boolean protectAgainstWrappingAttack(Node startNode, String value) { Node startParent = startNode.getParentNode(); Node processedNode = null; Element foundElement = null; - + String id = value.trim(); if (id.charAt(0) == '#') { id = id.substring(1); @@ -738,7 +929,7 @@ while (startNode != null) { if (startNode.getNodeType() == Node.ELEMENT_NODE) { Element se = (Element) startNode; - + NamedNodeMap attributes = se.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { @@ -764,7 +955,7 @@ // close node processing, get sibling startNode = processedNode.getNextSibling(); } - + // no more siblings, get parent, all children // of parent are processed. while (startNode == null) { @@ -778,20 +969,18 @@ } return true; } - + /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no other Element than the given "knownElement" argument - * has an ID attribute that matches the "value" argument, which is the ID - * value of "knownElement". If this is the case then "false" is returned. - */ - public static boolean protectAgainstWrappingAttack(Node startNode, - Element knownElement, - String value) - { + * This method is a tree-search to help prevent against wrapping attacks. It checks that no other + * Element than the given "knownElement" argument has an ID attribute that matches the "value" + * argument, which is the ID value of "knownElement". If this is the case then "false" is returned. + */ + public static boolean protectAgainstWrappingAttack( + Node startNode, Element knownElement, String value + ) { Node startParent = startNode.getParentNode(); Node processedNode = null; - + String id = value.trim(); if (id.charAt(0) == '#') { id = id.substring(1); @@ -800,14 +989,12 @@ while (startNode != null) { if (startNode.getNodeType() == Node.ELEMENT_NODE) { Element se = (Element) startNode; - + NamedNodeMap attributes = se.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr)attributes.item(i); - if (attr.isId() && id.equals(attr.getValue()) - && se != knownElement) - { + if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) { log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!"); return false; } @@ -823,7 +1010,7 @@ // close node processing, get sibling startNode = processedNode.getNextSibling(); } - + // no more siblings, get parent, all children // of parent are processed. while (startNode == null) { --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java 2013-06-28 11:34:33.588560418 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java 2013-06-28 11:34:33.412565896 -0400 @@ -42,12 +42,12 @@ public class ResourceResolver { /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(ResourceResolver.class.getName()); - + /** these are the system-wide resolvers */ private static List resolverList = new ArrayList(); - + /** Field resolverSpi */ private final ResourceResolverSpi resolverSpi; @@ -73,7 +73,7 @@ throws ResourceResolverException { return getInstance(uri, baseURI, false); } - + /** * Method getInstance * @@ -85,49 +85,55 @@ * @throws ResourceResolverException */ public static final ResourceResolver getInstance( - Attr uri, String baseURI, boolean secureValidation + Attr uriAttr, String baseURI, boolean secureValidation ) throws ResourceResolverException { + ResourceResolverContext context = new ResourceResolverContext(uriAttr, baseURI, secureValidation); + return internalGetInstance(context); + } + + private static ResourceResolver internalGetInstance(ResourceResolverContext context) + throws ResourceResolverException { synchronized (resolverList) { for (ResourceResolver resolver : resolverList) { ResourceResolver resolverTmp = resolver; if (!resolver.resolverSpi.engineIsThreadSafe()) { try { - resolverTmp = + resolverTmp = new ResourceResolver(resolver.resolverSpi.getClass().newInstance()); } catch (InstantiationException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } catch (IllegalAccessException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } } - + if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, + log.log(java.util.logging.Level.FINE, "check resolvability by class " + resolverTmp.getClass().getName() ); } - - resolverTmp.resolverSpi.secureValidation = secureValidation; - if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) { + + if ((resolverTmp != null) && resolverTmp.canResolve(context)) { // Check to see whether the Resolver is allowed - if (secureValidation + if (context.secureValidation && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) { Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() }; throw new ResourceResolverException( - "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI + "signature.Reference.ForbiddenResolver", exArgs, context.attr, context.baseUri ); } return resolverTmp; } } } + + Object exArgs[] = { ((context.uriToResolve != null) + ? context.uriToResolve : "null"), context.baseUri }; - Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI }; - - throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI); + throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.attr, context.baseUri); } - + /** * Method getInstance * @@ -143,7 +149,7 @@ ) throws ResourceResolverException { return getInstance(uri, baseURI, individualResolvers, false); } - + /** * Method getInstance * @@ -159,12 +165,14 @@ Attr uri, String baseURI, List individualResolvers, boolean secureValidation ) throws ResourceResolverException { if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "I was asked to create a ResourceResolver and got " + log.log(java.util.logging.Level.FINE, + "I was asked to create a ResourceResolver and got " + (individualResolvers == null ? 0 : individualResolvers.size()) ); } + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + // first check the individual Resolvers if (individualResolvers != null) { for (int i = 0; i < individualResolvers.size(); i++) { @@ -176,15 +184,14 @@ log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass); } - resolver.resolverSpi.secureValidation = secureValidation; - if (resolver.canResolve(uri, baseURI)) { + if (resolver.canResolve(context)) { return resolver; } } } } - return getInstance(uri, baseURI, secureValidation); + return internalGetInstance(context); } /** @@ -196,7 +203,7 @@ @SuppressWarnings("unchecked") public static void register(String className) { try { - Class resourceResolverClass = + Class resourceResolverClass = (Class) Class.forName(className); register(resourceResolverClass, false); } catch (ClassNotFoundException e) { @@ -213,7 +220,7 @@ @SuppressWarnings("unchecked") public static void registerAtStart(String className) { try { - Class resourceResolverClass = + Class resourceResolverClass = (Class) Class.forName(className); register(resourceResolverClass, true); } catch (ClassNotFoundException e) { @@ -222,7 +229,7 @@ } /** - * Registers a ResourceResolverSpi class. This method logs a warning if the class + * Registers a ResourceResolverSpi class. This method logs a warning if the class * cannot be registered. * @param className * @param start @@ -237,9 +244,9 @@ log.log(java.util.logging.Level.WARNING, "Error loading resolver " + className + " disabling it"); } } - + /** - * Registers a ResourceResolverSpi instance. This method logs a warning if the class + * Registers a ResourceResolverSpi instance. This method logs a warning if the class * cannot be registered. * @param resourceResolverSpi * @param start @@ -248,7 +255,7 @@ synchronized(resolverList) { if (start) { resolverList.add(0, new ResourceResolver(resourceResolverSpi)); - } else { + } else { resolverList.add(new ResourceResolver(resourceResolverSpi)); } } @@ -256,7 +263,7 @@ log.log(java.util.logging.Level.FINE, "Registered resolver: " + resourceResolverSpi.toString()); } } - + /** * This method registers the default resolvers. */ @@ -268,6 +275,15 @@ resolverList.add(new ResourceResolver(new ResolverDirectHTTP())); } } + + /** + * @deprecated New clients should use {@link #resolve(Attr, String, boolean)} + */ + @Deprecated + public XMLSignatureInput resolve(Attr uri, String baseURI) + throws ResourceResolverException { + return resolve(uri, baseURI, true); + } /** * Method resolve @@ -278,9 +294,10 @@ * * @throws ResourceResolverException */ - public XMLSignatureInput resolve(Attr uri, String baseURI) + public XMLSignatureInput resolve(Attr uri, String baseURI, boolean secureValidation) throws ResourceResolverException { - return resolverSpi.engineResolve(uri, baseURI); + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + return resolverSpi.engineResolveURI(context); } /** @@ -338,7 +355,7 @@ * @param baseURI * @return true if it can resolve the uri */ - private boolean canResolve(Attr uri, String baseURI) { - return resolverSpi.engineCanResolve(uri, baseURI); + private boolean canResolve(ResourceResolverContext context) { + return this.resolverSpi.engineCanResolveURI(context); } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java 2013-06-28 11:34:34.192541618 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java 2013-06-28 11:34:34.016547096 -0400 @@ -2,144 +2,137 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Attr; - /** * This Exception is thrown if something related to the * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResourceResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Attr uri, String BaseURI) { - - super(_msgID); - - this._uri = uri; - this._BaseURI = BaseURI; - } - - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], Attr uri, - String BaseURI) { - - super(_msgID, exArgs); - - this._uri = uri; - this._BaseURI = BaseURI; - } - - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Exception _originalException, - Attr uri, String BaseURI) { - - super(_msgID, _originalException); - - this._uri = uri; - this._BaseURI = BaseURI; - } - - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], - Exception _originalException, Attr uri, - String BaseURI) { - - super(_msgID, exArgs, _originalException); - - this._uri = uri; - this._BaseURI = BaseURI; - } - - //J- - Attr _uri = null; - /** - * - * @param uri - */ - public void setURI(Attr uri) { - this._uri = uri; - } - - /** - * - * @return the uri - */ - public Attr getURI() { - return this._uri; - } - - String _BaseURI; - - /** - * - * @param BaseURI - */ - public void setBaseURI(String BaseURI) { - this._BaseURI = BaseURI; - } - - /** - * - * @return the basUri - */ - public String getBaseURI() { - return this._BaseURI; - } - //J+ + private static final long serialVersionUID = 1L; + + private Attr uri = null; + + private String baseURI = null; + + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Attr uri, String baseURI) { + super(msgID); + + this.uri = uri; + this.baseURI = baseURI; + } + + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], Attr uri, + String baseURI) { + super(msgID, exArgs); + + this.uri = uri; + this.baseURI = baseURI; + } + + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Exception originalException, + Attr uri, String baseURI) { + super(msgID, originalException); + + this.uri = uri; + this.baseURI = baseURI; + } + + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], + Exception originalException, Attr uri, + String baseURI) { + super(msgID, exArgs, originalException); + + this.uri = uri; + this.baseURI = baseURI; + } + + /** + * + * @param uri + */ + public void setURI(Attr uri) { + this.uri = uri; + } + + /** + * + * @return the uri + */ + public Attr getURI() { + return this.uri; + } + + /** + * + * @param baseURI + */ + public void setbaseURI(String baseURI) { + this.baseURI = baseURI; + } + + /** + * + * @return the baseURI + */ + public String getbaseURI() { + return this.baseURI; + } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java 2013-06-28 11:34:34.840521447 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java 2013-06-28 11:34:34.660527050 -0400 @@ -2,192 +2,239 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver; - import java.util.HashMap; import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import org.w3c.dom.Attr; - /** * During reference validation, we have to retrieve resources from somewhere. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResourceResolverSpi.class.getName()); - - /** Field _properties */ - protected java.util.Map _properties = null; - - protected boolean secureValidation; - - /** - * This is the workhorse method used to resolve resources. - * - * @param uri - * @param BaseURI - * @return the resource wrapped arround a XMLSignatureInput - * - * @throws ResourceResolverException - */ - public abstract XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException; - - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.put(key, value); - } - - /** - * Method engineGetProperty - * - * @param key - * @return the value of the property - */ - public String engineGetProperty(String key) { - if (_properties==null) { - return null; - } - return this._properties.get(key); - } - - /** - * - * @param properties - */ - public void engineAddProperies(Map properties) { - if (properties!=null) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.putAll(properties); - } - } - /** - * Tells if the implementation does can be reused by several threads safely. - * It normally means that the implemantation does not have any member, or there is - * member change betwen engineCanResolve & engineResolve invocations. Or it mantians all - * member info in ThreadLocal methods. - */ - public boolean engineIsThreadSafe() { - return false; - } - /** - * This method helps the {@link ResourceResolver} to decide whether a - * {@link ResourceResolverSpi} is able to perform the requested action. - * - * @param uri - * @param BaseURI - * @return true if the engine can resolve the uri - */ - public abstract boolean engineCanResolve(Attr uri, String BaseURI); - - /** - * Method engineGetPropertyKeys - * - * @return the property keys - */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } - - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understands the property - */ - public boolean understandsProperty(String propertyToTest) { - - String[] understood = this.engineGetPropertyKeys(); - - if (understood != null) { - for (int i = 0; i < understood.length; i++) { - if (understood[i].equals(propertyToTest)) { - return true; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResourceResolverSpi.class.getName()); + + /** Field properties */ + protected java.util.Map properties = null; + + /** + * Deprecated - used to carry state about whether resolution was being done in a secure fashion, + * but was not thread safe, so the resolution information is now passed as parameters to methods. + * + * @deprecated Secure validation flag is now passed to methods. + */ + @Deprecated + protected final boolean secureValidation = true; + + /** + * This is the workhorse method used to resolve resources. + * + * @param uri + * @param BaseURI + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + * + * @deprecated New clients should override {@link #engineResolveURI(ResourceResolverContext)} + */ + @Deprecated + public XMLSignatureInput engineResolve(Attr uri, String BaseURI) + throws ResourceResolverException { + throw new UnsupportedOperationException(); + } + + /** + * This is the workhorse method used to resolve resources. + * @param context Context to use to resolve resources. + * + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + // The default implementation, to preserve backwards compatibility in the + // test cases, calls the old resolver API. + return engineResolve(context.attr, context.baseUri); + } + + /** + * 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 the value of the property + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } + return properties.get(key); + } + + /** + * + * @param newProperties + */ + public void engineAddProperies(Map newProperties) { + if (newProperties != null && !newProperties.isEmpty()) { + if (properties == null) { + properties = new HashMap(); } - } - } + properties.putAll(newProperties); + } + } + + /** + * Tells if the implementation does can be reused by several threads safely. + * It normally means that the implementation does not have any member, or there is + * member change between engineCanResolve & engineResolve invocations. Or it maintains all + * member info in ThreadLocal methods. + */ + public boolean engineIsThreadSafe() { + return false; + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + * @param uri + * @param BaseURI + * @return true if the engine can resolve the uri + * + * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)} + */ + @Deprecated + public boolean engineCanResolve(Attr uri, String BaseURI) { + // This method used to be abstract, so any calls to "super" are bogus. + throw new UnsupportedOperationException(); + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + *

      New clients should override this method, and not override {@link #engineCanResolve(Attr, String)} + *

      + * @param context Context in which to do resolution. + * @return true if the engine can resolve the uri + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + // To preserve backward compatibility with existing resolvers that might override the old method, + // call the old deprecated API. + return engineCanResolve( context.attr, context.baseUri ); + } + + /** + * Method engineGetPropertyKeys + * + * @return the property keys + */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } + + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understands the property + */ + public boolean understandsProperty(String propertyToTest) { + String[] understood = this.engineGetPropertyKeys(); + + if (understood != null) { + for (int i = 0; i < understood.length; i++) { + if (understood[i].equals(propertyToTest)) { + return true; + } + } + } - return false; - } + return false; + } - /** - * Fixes a platform dependent filename to standard URI form. - * - * @param str The string to fix. - * - * @return Returns the fixed URI string. - */ - public static String fixURI(String str) { - - // handle platform dependent strings - str = str.replace(java.io.File.separatorChar, '/'); - - if (str.length() >= 4) { - - // str =~ /^\W:\/([^/])/ # to speak perl ;-)) - char ch0 = Character.toUpperCase(str.charAt(0)); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - char ch3 = str.charAt(3); - boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) - && (ch1 == ':') && (ch2 == '/') - && (ch3 != '/')); + /** + * Fixes a platform dependent filename to standard URI form. + * + * @param str The string to fix. + * + * @return Returns the fixed URI string. + */ + public static String fixURI(String str) { - if (isDosFilename) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); - } - } + // handle platform dependent strings + str = str.replace(java.io.File.separatorChar, '/'); - // Windows fix - if (str.length() >= 2) { - char ch1 = str.charAt(1); + if (str.length() >= 4) { - if (ch1 == ':') { + // str =~ /^\W:\/([^/])/ # to speak perl ;-)) char ch0 = Character.toUpperCase(str.charAt(0)); + char ch1 = str.charAt(1); + char ch2 = str.charAt(2); + char ch3 = str.charAt(3); + boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) + && (ch1 == ':') && (ch2 == '/') + && (ch3 != '/')); + + if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); + } + } - if (('A' <= ch0) && (ch0 <= 'Z')) { - str = "/" + str; + // Windows fix + if (str.length() >= 2) { + char ch1 = str.charAt(1); + + if (ch1 == ':') { + char ch0 = Character.toUpperCase(str.charAt(0)); + + if (('A' <= ch0) && (ch0 <= 'Z')) { + str = "/" + str; + } } - } - } + } - // done - return str; - } + // done + return str; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java 2013-06-28 11:34:35.480501526 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java 2013-06-28 11:34:35.308506880 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver.implementations; @@ -27,51 +29,56 @@ import java.io.InputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ - public class ResolverAnonymous extends ResourceResolverSpi { - private XMLSignatureInput _input = null; + private InputStream inStream = null; + + @Override + public boolean engineIsThreadSafe() { + return true; + } - /** - * @param filename + /** + * @param filename * @throws FileNotFoundException * @throws IOException */ - public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { - this._input = new XMLSignatureInput(new FileInputStream(filename)); - } + public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { + inStream = new FileInputStream(filename); + } + + /** + * @param is + */ + public ResolverAnonymous(InputStream is) { + inStream = is; + } + + /** @inheritDoc */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) { + return new XMLSignatureInput(inStream); + } - /** - * @param is + /** + * @inheritDoc */ - public ResolverAnonymous(InputStream is) { - this._input = new XMLSignatureInput(is); - } - - /** @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) { - return this._input; - } - - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - return true; - } - return false; - } - - /** @inheritDoc */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } + @Override + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return true; + } + return false; + } + + /** @inheritDoc */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java 2013-06-28 11:34:36.152480610 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java 2013-06-28 11:34:35.984485838 -0400 @@ -2,38 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver.implementations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.net.InetSocketAddress; import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URISyntaxException; +import java.net.URI; import java.net.URL; import java.net.URLConnection; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.Base64; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; - /** * A simple ResourceResolver for HTTP requests. This class handles only 'pure' @@ -51,253 +55,219 @@ * resourceResolver.setProperty("http.proxy.password", "secretca"); *
      * - * - * @author $Author: mullan $ * @see Java Tip 42: Write Java apps that work with proxy-based firewalls * @see SUN J2SE docs for network properties * @see The JAVA FAQ Question 9.5: How do I make Java work with a proxy server? - * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!? */ public class ResolverDirectHTTP extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverDirectHTTP.class.getName()); - - /** Field properties[] */ - private static final String properties[] = - { "http.proxy.host", "http.proxy.port", - "http.proxy.username", - "http.proxy.password", - "http.basic.username", - "http.basic.password" }; - - /** Field HttpProxyHost */ - private static final int HttpProxyHost = 0; - - /** Field HttpProxyPort */ - private static final int HttpProxyPort = 1; - - /** Field HttpProxyUser */ - private static final int HttpProxyUser = 2; - - /** Field HttpProxyPass */ - private static final int HttpProxyPass = 3; - - /** Field HttpProxyUser */ - private static final int HttpBasicUser = 4; - - /** Field HttpProxyPass */ - private static final int HttpBasicPass = 5; - - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method resolve - * - * @param uri - * @param BaseURI - * - * @throws ResourceResolverException - * @return - * $todo$ calculate the correct URI from the attribute and the BaseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { - - try { - boolean useProxy = false; - String proxyHost = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyHost]); - String proxyPort = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPort]); - - if ((proxyHost != null) && (proxyPort != null)) { - useProxy = true; - } - - String oldProxySet = null; - String oldProxyHost = null; - String oldProxyPort = null; - // switch on proxy usage - if (useProxy) { + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName()); + + /** Field properties[] */ + private static final String properties[] = { + "http.proxy.host", "http.proxy.port", + "http.proxy.username", "http.proxy.password", + "http.basic.username", "http.basic.password" + }; + + /** Field HttpProxyHost */ + private static final int HttpProxyHost = 0; + + /** Field HttpProxyPort */ + private static final int HttpProxyPort = 1; + + /** Field HttpProxyUser */ + private static final int HttpProxyUser = 2; + + /** Field HttpProxyPass */ + private static final int HttpProxyPass = 3; + + /** Field HttpProxyUser */ + private static final int HttpBasicUser = 4; + + /** Field HttpProxyPass */ + private static final int HttpBasicPass = 5; + + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * Method resolve + * + * @param uri + * @param baseURI + * + * @throws ResourceResolverException + * @return + * $todo$ calculate the correct URI from the attribute and the baseURI + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { + + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + URL url = uriNew.toURL(); + URLConnection urlConnection; + urlConnection = openConnection(url); + + // check if Basic authentication is required + String auth = urlConnection.getHeaderField("WWW-Authenticate"); + + if (auth != null && auth.startsWith("Basic")) { + // do http basic authentication + String user = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]); + String pass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]); + + if ((user != null) && (pass != null)) { + urlConnection = openConnection(url); + + String password = user + ":" + pass; + String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1")); + + // set authentication property in the http header + urlConnection.setRequestProperty("Authorization", + "Basic " + encodedPassword); + } + } + + String mimeType = urlConnection.getHeaderField("Content-Type"); + InputStream inputStream = urlConnection.getInputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte buf[] = new byte[4096]; + int read = 0; + int summarized = 0; + + while ((read = inputStream.read(buf)) >= 0) { + baos.write(buf, 0, read); + summarized += read; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Use of HTTP proxy enabled: " + proxyHost + ":" - + proxyPort); + log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString()); } - oldProxySet = System.getProperty("http.proxySet"); - oldProxyHost = System.getProperty("http.proxyHost"); - oldProxyPort = System.getProperty("http.proxyPort"); - System.setProperty("http.proxySet", "true"); - System.setProperty("http.proxyHost", proxyHost); - System.setProperty("http.proxyPort", proxyPort); - } - - boolean switchBackProxy = ((oldProxySet != null) - && (oldProxyHost != null) - && (oldProxyPort != null)); - - // calculate new URI - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); - - // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - URL url = new URL(uriNewNoFrag.toString()); - URLConnection urlConnection = url.openConnection(); - - { - - // set proxy pass - String proxyUser = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyUser]); - String proxyPass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPass]); + + XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); + + result.setSourceURI(uriNew.toString()); + result.setMIMEType(mimeType); + + return result; + } catch (URISyntaxException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (MalformedURLException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IOException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IllegalArgumentException e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } + + private URLConnection openConnection(URL url) throws IOException { + + String proxyHostProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]); + String proxyPortProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]); + String proxyUser = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]); + String proxyPass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]); + + Proxy proxy = null; + if ((proxyHostProp != null) && (proxyPortProp != null)) { + int port = Integer.parseInt(proxyPortProp); + proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port)); + } + + URLConnection urlConnection; + if (proxy != null) { + urlConnection = url.openConnection(proxy); if ((proxyUser != null) && (proxyPass != null)) { - String password = proxyUser + ":" + proxyPass; - String encodedPassword = Base64.encode(password.getBytes()); + String password = proxyUser + ":" + proxyPass; + String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1")); - // or was it Proxy-Authenticate ? - urlConnection.setRequestProperty("Proxy-Authorization", - encodedPassword); + urlConnection.setRequestProperty("Proxy-Authorization", authString); } - } - - { + } else { + urlConnection = url.openConnection(); + } + + return urlConnection; + } + + /** + * We resolve http URIs without fragment... + * + * @param uri + * @param baseURI + * @return true if can be resolved + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + } + return false; + } - // check if Basic authentication is required - String auth = urlConnection.getHeaderField("WWW-Authenticate"); + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + } + return false; + } - if (auth != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } - // do http basic authentication - if (auth.startsWith("Basic")) { - String user = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicUser]); - String pass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicPass]); - - if ((user != null) && (pass != null)) { - urlConnection = url.openConnection(); - - String password = user + ":" + pass; - String encodedPassword = - Base64.encode(password.getBytes()); - - // set authentication property in the http header - urlConnection.setRequestProperty("Authorization", - "Basic " - + encodedPassword); - } - } + if (context.uriToResolve.startsWith("http:") || + (context.baseUri != null && context.baseUri.startsWith("http:") )) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); } - } + return true; + } - String mimeType = urlConnection.getHeaderField("Content-Type"); - InputStream inputStream = urlConnection.getInputStream(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte buf[] = new byte[4096]; - int read = 0; - int summarized = 0; - - while ((read = inputStream.read(buf)) >= 0) { - baos.write(buf, 0, read); - - summarized += read; - } - - log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " - + uriNew.toString()); - - XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); - - // XMLSignatureInput result = new XMLSignatureInput(inputStream); - result.setSourceURI(uriNew.toString()); - result.setMIMEType(mimeType); - - // switch off proxy usage - if (useProxy && switchBackProxy) { - System.setProperty("http.proxySet", oldProxySet); - System.setProperty("http.proxyHost", oldProxyHost); - System.setProperty("http.proxyPort", oldProxyPort); - } - - return result; - } catch (MalformedURLException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } catch (IOException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } - } - - /** - * We resolve http URIs without fragment... - * - * @param uri - * @param BaseURI - * @return true if can be resolved - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); - - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) { - log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); - - return false; - } - - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue); - } - - if ( uriNodeValue.startsWith("http:") || - (BaseURI!=null && BaseURI.startsWith("http:") )) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue); - } - - return true; - } - - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue); - } - - return false; - } - - /** - * @inheritDoc - */ - public String[] engineGetPropertyKeys() { - return ResolverDirectHTTP.properties.clone(); - } - - private URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { - - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve); + } + + return false; + } + + /** + * @inheritDoc + */ + public String[] engineGetPropertyKeys() { + return ResolverDirectHTTP.properties.clone(); + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } + + // if the URI contains a fragment, ignore it + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; + } + return newUri; + } + } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java 2013-06-28 11:34:36.796460564 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java 2013-06-28 11:34:36.624465917 -0400 @@ -2,148 +2,148 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * This resolver is used for resolving same-document URIs like URI="" of URI="#id". * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see The Reference processing model in the XML Signature spec * @see Same-Document URI-References in the XML Signature spec * @see Section 4.2 of RFC 2396 */ public class ResolverFragment extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverFragment.class.getName()); - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method engineResolve - * - * @inheritDoc - * @param uri - * @param baseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException - { - String uriNodeValue = uri.getNodeValue(); - Document doc = uri.getOwnerElement().getOwnerDocument(); - - Node selectedElem = null; - if (uriNodeValue.equals("")) { + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverFragment.class.getName()); + + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * Method engineResolve + * + * @inheritDoc + * @param uri + * @param baseURI + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { - /* - * Identifies the node-set (minus any comment nodes) of the XML - * resource containing the signature - */ + Document doc = context.attr.getOwnerElement().getOwnerDocument(); - log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + Node selectedElem = null; + if (context.uriToResolve.equals("")) { + /* + * Identifies the node-set (minus any comment nodes) of the XML + * resource containing the signature + */ + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + } selectedElem = doc; } else { - /* * URI="#chapter1" * Identifies a node-set containing the element with ID attribute * value 'chapter1' of the XML resource containing the signature. * XML Signature (and its applications) modify this node-set to - * include the element plus all descendents including namespaces and + * include the element plus all descendants including namespaces and * attributes -- but not comments. */ - String id = uriNodeValue.substring(1); + String id = context.uriToResolve.substring(1); selectedElem = doc.getElementById(id); if (selectedElem == null) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Try to catch an Element with ID " + id + " and Element was " + selectedElem + ); + } } XMLSignatureInput result = new XMLSignatureInput(selectedElem); result.setExcludeComments(true); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * Method engineCanResolve - * @inheritDoc - * @param uri - * @param BaseURI - * - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || - ( - (uriNodeValue.charAt(0)=='#') - && !((uriNodeValue.charAt(1)=='x') && uriNodeValue.startsWith("#xpointer(")) - ) - ){ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + uriNodeValue + "\""); - return true; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + uriNodeValue + "\""); - return false; - } + /** + * Method engineCanResolve + * @inheritDoc + * @param uri + * @param baseURI + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); + } + return false; + } + + if (context.uriToResolve.equals("") || + ((context.uriToResolve.charAt(0) == '#') && !context.uriToResolve.startsWith("#xpointer(")) + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + context.uriToResolve + "\""); + } + return true; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + context.uriToResolve + "\""); + } + return false; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java 2013-06-28 11:34:37.464439771 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java 2013-06-28 11:34:37.296445001 -0400 @@ -2,156 +2,160 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver.implementations; import java.io.FileInputStream; +import java.net.URI; +import java.net.URISyntaxException; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** * A simple ResourceResolver for requests into the local filesystem. - * - * @author $Author: mullan $ */ public class ResolverLocalFilesystem extends ResourceResolverSpi { + + private static final int FILE_URI_LENGTH = "file:/".length(); - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverLocalFilesystem.class.getName()); - + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverLocalFilesystem.class.getName()); + + @Override public boolean engineIsThreadSafe() { - return true; - } - /** - * @inheritDoc - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + return true; + } - try { - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); + /** + * @inheritDoc + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + + String fileName = + ResolverLocalFilesystem.translateUriToFilename(uriNew.toString()); + FileInputStream inputStream = new FileInputStream(fileName); + XMLSignatureInput result = new XMLSignatureInput(inputStream); + + result.setSourceURI(uriNew.toString()); + + return result; + } catch (Exception e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } - // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); + /** + * Method translateUriToFilename + * + * @param uri + * @return the string of the filename + */ + private static String translateUriToFilename(String uri) { + + String subStr = uri.substring(FILE_URI_LENGTH); + + if (subStr.indexOf("%20") > -1) { + int offset = 0; + int index = 0; + StringBuilder temp = new StringBuilder(subStr.length()); + do { + index = subStr.indexOf("%20",offset); + if (index == -1) { + temp.append(subStr.substring(offset)); + } else { + temp.append(subStr.substring(offset, index)); + temp.append(' '); + offset = index + 3; + } + } while(index != -1); + subStr = temp.toString(); + } + + if (subStr.charAt(1) == ':') { + // we're running M$ Windows, so this works fine + return subStr; + } + // we're running some UNIX, so we have to prepend a slash + return "/" + subStr; + } + + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#') || + context.uriToResolve.startsWith("http:")) { + return false; + } + + try { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } + + if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } - uriNewNoFrag.setFragment(null); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "But I can't"); + } + + return false; + } - String fileName = - ResolverLocalFilesystem - .translateUriToFilename(uriNewNoFrag.toString()); - FileInputStream inputStream = new FileInputStream(fileName); - XMLSignatureInput result = new XMLSignatureInput(inputStream); - - result.setSourceURI(uriNew.toString()); - - return result; - } catch (Exception e) { - throw new ResourceResolverException("generic.EmptyMessage", e, uri, - BaseURI); - } - } - - private static int FILE_URI_LENGTH="file:/".length(); - /** - * Method translateUriToFilename - * - * @param uri - * @return the string of the filename - */ - private static String translateUriToFilename(String uri) { - - String subStr = uri.substring(FILE_URI_LENGTH); - - if (subStr.indexOf("%20") > -1) - { - int offset = 0; - int index = 0; - StringBuffer temp = new StringBuffer(subStr.length()); - do - { - index = subStr.indexOf("%20",offset); - if (index == -1) temp.append(subStr.substring(offset)); - else - { - temp.append(subStr.substring(offset,index)); - temp.append(' '); - offset = index+3; - } - } - while(index != -1); - subStr = temp.toString(); - } - - if (subStr.charAt(1) == ':') { - // we're running M$ Windows, so this works fine - return subStr; - } - // we're running some UNIX, so we have to prepend a slash - return "/" + subStr; - } - - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#') || - uriNodeValue.startsWith("http:")) { - return false; - } - - try { - //URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue()); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue/*uriNew.toString()*/); - - if ( uriNodeValue.startsWith("file:") || - BaseURI.startsWith("file:")/*uriNew.getScheme().equals("file")*/) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue/*uriNew.toString()*/); - - return true; - } - } catch (Exception e) {} - - log.log(java.util.logging.Level.FINE, "But I can't"); - - return false; - } - - private static URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { - - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } + + // if the URI contains a fragment, ignore it + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; + } + return newUri; + } } --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java 2013-06-28 11:34:38.168417858 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java 2013-06-28 11:34:38.000423088 -0400 @@ -2,36 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * 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.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Handles barename XPointer Reference URIs. *
      @@ -45,155 +44,137 @@ * nodes of the parse tree (all descendants, plus all attributes, * plus all namespaces nodes). * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResolverXPointer extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverXPointer.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverXPointer.class.getName()); + + private static final String XP = "#xpointer(id("; + private static final int XP_LENGTH = XP.length(); + @Override public boolean engineIsThreadSafe() { return true; } - + /** * @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException { + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { Node resultNode = null; - Document doc = uri.getOwnerElement().getOwnerDocument(); + Document doc = context.attr.getOwnerElement().getOwnerDocument(); - String uriStr = uri.getNodeValue(); - if (isXPointerSlash(uriStr)) { + if (isXPointerSlash(context.uriToResolve)) { resultNode = doc; - - } else if (isXPointerId(uriStr)) { - String id = getXPointerId(uriStr); + } else if (isXPointerId(context.uriToResolve)) { + String id = getXPointerId(context.uriToResolve); resultNode = doc.getElementById(id); - - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } if (resultNode == null) { - Object exArgs[] = { id }; + Object exArgs[] = { id }; - throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + throw new ResourceResolverException( + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } } XMLSignatureInput result = new XMLSignatureInput(resultNode); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - String uriStr =uri.getNodeValue(); - if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) { - return true; - } - - return false; - } - - /** - * Method isXPointerSlash - * - * @param uri - * @return true if begins with xpointer - */ - private static boolean isXPointerSlash(String uri) { - - if (uri.equals("#xpointer(/)")) { - return true; - } - - return false; - } - - - private static final String XP="#xpointer(id("; - private static final int XP_LENGTH=XP.length(); - /** - * Method isXPointerId - * - * @param uri - * @return it it has an xpointer id - * - */ - private static boolean isXPointerId(String uri) { - - - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH, - uri.length() - - 2); - - // log.log(java.util.logging.Level.FINE, "idPlusDelim=" + idPlusDelim); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Id=" - + idPlusDelim.substring(1, idLen)); + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) { + return true; + } + + return false; + } + /** + * Method isXPointerSlash + * + * @param uri + * @return true if begins with xpointer + */ + private static boolean isXPointerSlash(String uri) { + if (uri.equals("#xpointer(/)")) { return true; - } - } + } - return false; - } + return false; + } - /** - * Method getXPointerId - * - * @param uri - * @return xpointerId to search. - */ - private static String getXPointerId(String uri) { - - - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - - 2); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - return idPlusDelim.substring(1, idLen); - } - } + /** + * Method isXPointerId + * + * @param uri + * @return whether it has an xpointer id + */ + private static boolean isXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2); + + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Id = " + idPlusDelim.substring(1, idLen)); + } + return true; + } + } - return null; - } + return false; + } + + /** + * Method getXPointerId + * + * @param uri + * @return xpointerId to search. + */ + private static String getXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - 2); + + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + return idPlusDelim.substring(1, idLen); + } + } + + return null; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java 2013-06-28 11:34:38.868396070 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java 2013-06-28 11:34:38.696401423 -0400 @@ -2,42 +2,43 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DigesterOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $ + * $Id: DigesterOutputStream.java,v 1.5 2005/12/20 20:02:39 mullan Exp $ */ package org.jcp.xml.dsig.internal; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; -import java.util.logging.Logger; -import java.util.logging.Level; import com.sun.org.apache.xml.internal.security.utils.UnsyncByteArrayOutputStream; /** * This class has been modified slightly to use java.security.MessageDigest - * objects as input, rather than + * objects as input, rather than * com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm objects. * It also optionally caches the input bytes. * @@ -45,10 +46,12 @@ * @author Sean Mullan */ public class DigesterOutputStream extends OutputStream { - private boolean buffer = false; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal"); + + private final boolean buffer; private UnsyncByteArrayOutputStream bos; private final MessageDigest md; - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal"); /** * Creates a DigesterOutputStream. @@ -73,40 +76,34 @@ } } - /** @inheritDoc */ - public void write(byte[] input) { - write(input, 0, input.length); - } - - /** @inheritDoc */ public void write(int input) { if (buffer) { bos.write(input); } md.update((byte)input); } - - /** @inheritDoc */ + + @Override public void write(byte[] input, int offset, int len) { if (buffer) { bos.write(input, offset, len); } - if (log.isLoggable(Level.FINER)) { - log.log(Level.FINER, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(len); - for (int i=offset; i<(offset+len); i++) { - sb.append((char) input[i]); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Pre-digested input:"); + StringBuilder sb = new StringBuilder(len); + for (int i = offset; i < (offset + len); i++) { + sb.append((char)input[i]); } - log.log(Level.FINER, sb.toString()); + log.log(java.util.logging.Level.FINE, sb.toString()); } md.update(input, offset, len); } - + /** - * @return the digest value + * @return the digest value */ public byte[] getDigestValue() { - return md.digest(); + return md.digest(); } /** @@ -120,4 +117,11 @@ return null; } } + + @Override + public void close() throws IOException { + if (buffer) { + bos.close(); + } + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java 2013-06-28 11:34:39.540375153 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java 2013-06-28 11:34:39.364380631 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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 org.jcp.xml.dsig.internal; @@ -24,7 +26,7 @@ import javax.crypto.Mac; /** - * Derived from Apache sources and changed to use Mac objects instead of + * Derived from Apache sources and changed to use Mac objects instead of * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects. * * @author raul @@ -38,19 +40,13 @@ this.mac = mac; } - /** @inheritDoc */ - public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); - mac.update(arg0); - } - - /** @inheritDoc */ + @Override public void write(int arg0) { super.write(arg0); mac.update((byte) arg0); } - - /** @inheritDoc */ + + @Override public void write(byte[] arg0, int arg1, int arg2) { super.write(arg0, arg1, arg2); mac.update(arg0, arg1, arg2); --- old/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java 2013-06-28 11:34:40.192354858 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java 2013-06-28 11:34:40.024360088 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: SignerOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $ + * $Id: SignerOutputStream.java,v 1.2 2005/09/15 14:29:02 mullan Exp $ */ package org.jcp.xml.dsig.internal; @@ -31,9 +33,9 @@ import java.security.SignatureException; /** - * Derived from Apache sources and changed to use java.security.Signature - * objects as input instead of com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm - * objects. + * Derived from Apache sources and changed to use java.security.Signature + * objects as input instead of + * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects. * * @author raul * @author Sean Mullan @@ -42,36 +44,26 @@ private final Signature sig; public SignerOutputStream(Signature sig) { - this.sig=sig; - } - - /** @inheritDoc */ - public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); - try { - sig.update(arg0); - } catch (SignatureException e) { - throw new RuntimeException(""+e); - } + this.sig = sig; } - /** @inheritDoc */ + @Override public void write(int arg0) { super.write(arg0); try { sig.update((byte)arg0); } catch (SignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException(e); } } - /** @inheritDoc */ + @Override public void write(byte[] arg0, int arg1, int arg2) { super.write(arg0, arg1, arg2); try { - sig.update(arg0,arg1,arg2); + sig.update(arg0, arg1, arg2); } catch (SignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException(e); } } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java 2013-06-28 11:34:40.860334066 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java 2013-06-28 11:34:40.688339419 -0400 @@ -2,44 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheCanonicalizer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheCanonicalizer.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.OutputStream; import java.security.spec.AlgorithmParameterSpec; import java.security.InvalidAlgorithmParameterException; import java.util.Set; -import java.util.logging.Logger; -import java.util.logging.Level; import javax.xml.crypto.*; import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.TransformException; import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; @@ -48,7 +46,7 @@ import com.sun.org.apache.xml.internal.security.transforms.Transform; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; +import org.w3c.dom.Node; public abstract class ApacheCanonicalizer extends TransformService { @@ -56,59 +54,69 @@ com.sun.org.apache.xml.internal.security.Init.init(); } - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); protected Canonicalizer apacheCanonicalizer; private Transform apacheTransform; protected String inclusiveNamespaces; protected C14NMethodParameterSpec params; protected Document ownerDoc; protected Element transformElem; - - public final AlgorithmParameterSpec getParameterSpec() { + + public final AlgorithmParameterSpec getParameterSpec() + { return params; } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } - - public Data canonicalize(Data data, XMLCryptoContext xc) - throws TransformException { + + public Data canonicalize(Data data, XMLCryptoContext xc) + throws TransformException + { return canonicalize(data, xc, null); } - public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - + public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) + throws TransformException + { if (apacheCanonicalizer == null) { try { apacheCanonicalizer = Canonicalizer.getInstance(getAlgorithm()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created canonicalizer for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created canonicalizer for algorithm: " + getAlgorithm()); } } catch (InvalidCanonicalizerException ice) { throw new TransformException ("Couldn't find Canonicalizer for: " + getAlgorithm() + - ": " + ice.getMessage(), ice); + ": " + ice.getMessage(), ice); } } @@ -119,10 +127,10 @@ } try { - Set nodeSet = null; + Set nodeSet = null; if (data instanceof ApacheData) { - XMLSignatureInput in = - ((ApacheData) data).getXMLSignatureInput(); + XMLSignatureInput in = + ((ApacheData)data).getXMLSignatureInput(); if (in.isElement()) { if (inclusiveNamespaces != null) { return new OctetStreamData(new ByteArrayInputStream @@ -141,7 +149,7 @@ Utils.readBytesFromStream(in.getOctetStream())))); } } else if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; if (inclusiveNamespaces != null) { return new OctetStreamData(new ByteArrayInputStream (apacheCanonicalizer.canonicalizeSubtree @@ -152,12 +160,13 @@ (subTree.getRoot()))); } } else if (data instanceof NodeSetData) { - NodeSetData nsd = (NodeSetData) data; + NodeSetData nsd = (NodeSetData)data; // convert Iterator to Set - nodeSet = Utils.toNodeSet(nsd.iterator()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Canonicalizing " + nodeSet.size() - + " nodes"); + @SuppressWarnings("unchecked") + Set ns = Utils.toNodeSet(nsd.iterator()); + nodeSet = ns; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Canonicalizing " + nodeSet.size() + " nodes"); } } else { return new OctetStreamData(new ByteArrayInputStream( @@ -179,7 +188,8 @@ } public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } @@ -193,12 +203,11 @@ if (apacheTransform == null) { try { - apacheTransform = new Transform - (ownerDoc, getAlgorithm(), transformElem.getChildNodes()); + apacheTransform = + new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); apacheTransform.setElement(transformElem, xc.getBaseURI()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created transform for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + getAlgorithm()); } } catch (Exception ex) { throw new TransformException @@ -208,26 +217,27 @@ XMLSignatureInput in; if (data instanceof ApacheData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "ApacheData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ApacheData = true"); } - in = ((ApacheData) data).getXMLSignatureInput(); + in = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof NodeSetData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = true"); } if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; in = new XMLSignatureInput(subTree.getRoot()); in.setExcludeComments(subTree.excludeComments()); } else { - Set nodeSet = - Utils.toNodeSet(((NodeSetData) data).iterator()); + @SuppressWarnings("unchecked") + Set nodeSet = + Utils.toNodeSet(((NodeSetData)data).iterator()); in = new XMLSignatureInput(nodeSet); } } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = false"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = false"); } try { in = new XMLSignatureInput --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java 2013-06-28 11:34:41.552312526 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java 2013-06-28 11:34:41.372318129 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheData.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -30,7 +32,7 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; /** - * XMLSignatureInput Data wrapper. + * XMLSignatureInput Data wrapper. * * @author Sean Mullan */ @@ -39,5 +41,5 @@ /** * Returns the XMLSignatureInput. */ - public XMLSignatureInput getXMLSignatureInput(); + XMLSignatureInput getXMLSignatureInput(); } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java 2013-06-28 11:34:42.212291983 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java 2013-06-28 11:34:42.040297336 -0400 @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheNodeSetData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheNodeSetData.java 1203890 2011-11-18 22:47:56Z mullan $ */ package org.jcp.xml.dsig.internal.dom; import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; @@ -65,24 +66,22 @@ return xi; } - private Set getNodeSet(List nodeFilters) { + private Set getNodeSet(List nodeFilters) { if (xi.isNeedsToBeExpanded()) { XMLUtils.circumventBug2650 (XMLUtils.getOwnerDocument(xi.getSubNode())); } - Set inputSet = new LinkedHashSet(); - XMLUtils.getSet - (xi.getSubNode(), inputSet, null, !xi.isExcludeComments()); - Set nodeSet = new LinkedHashSet(); - Iterator i = inputSet.iterator(); - while (i.hasNext()) { - Node currentNode = (Node) i.next(); - Iterator it = nodeFilters.iterator(); + Set inputSet = new LinkedHashSet(); + XMLUtils.getSet(xi.getSubNode(), inputSet, + null, !xi.isExcludeComments()); + Set nodeSet = new LinkedHashSet(); + for (Node currentNode : inputSet) { + Iterator it = nodeFilters.iterator(); boolean skipNode = false; while (it.hasNext() && !skipNode) { - NodeFilter nf = (NodeFilter) it.next(); - if (nf.isNodeInclude(currentNode)!=1) { + NodeFilter nf = it.next(); + if (nf.isNodeInclude(currentNode) != 1) { skipNode = true; } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java 2013-06-28 11:34:42.884271066 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java 2013-06-28 11:34:42.712276420 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheOctetStreamData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheOctetStreamData.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,13 +33,14 @@ import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; -public class ApacheOctetStreamData extends OctetStreamData +public class ApacheOctetStreamData extends OctetStreamData implements ApacheData { private XMLSignatureInput xi; public ApacheOctetStreamData(XMLSignatureInput xi) - throws CanonicalizationException, IOException { + throws CanonicalizationException, IOException + { super(xi.getOctetStream(), xi.getSourceURI(), xi.getMIMEType()); this.xi = xi; } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java 2013-06-28 11:34:43.596248904 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java 2013-06-28 11:34:43.420254382 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -30,11 +32,9 @@ import java.security.InvalidAlgorithmParameterException; import java.security.spec.AlgorithmParameterSpec; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; +import org.w3c.dom.Node; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -58,48 +58,59 @@ com.sun.org.apache.xml.internal.security.Init.init(); } - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Transform apacheTransform; protected Document ownerDoc; protected Element transformElem; protected TransformParameterSpec params; - + public final AlgorithmParameterSpec getParameterSpec() { return params; } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } - transformElem = (Element) + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } + transformElem = (Element) ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } - transformElem = (Element) + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } + transformElem = (Element) ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } - return transformIt(data, xc, (OutputStream) null); + return transformIt(data, xc, (OutputStream)null); } public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } @@ -110,61 +121,62 @@ } private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - + throws TransformException + { if (ownerDoc == null) { throw new TransformException("transform must be marshalled"); } if (apacheTransform == null) { try { - apacheTransform = new Transform - (ownerDoc, getAlgorithm(), transformElem.getChildNodes()); + apacheTransform = + new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); apacheTransform.setElement(transformElem, xc.getBaseURI()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created transform for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + + getAlgorithm()); } } catch (Exception ex) { - throw new TransformException - ("Couldn't find Transform for: " + getAlgorithm(), ex); - } + throw new TransformException("Couldn't find Transform for: " + + getAlgorithm(), ex); + } } - + if (Utils.secureValidation(xc)) { String algorithm = getAlgorithm(); if (Transforms.TRANSFORM_XSLT.equals(algorithm)) { throw new TransformException( - "Transform " + algorithm + - " is forbidden when secure validation is enabled"); + "Transform " + algorithm + " is forbidden when secure validation is enabled" + ); } } XMLSignatureInput in; if (data instanceof ApacheData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "ApacheData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ApacheData = true"); } - in = ((ApacheData) data).getXMLSignatureInput(); + in = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof NodeSetData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = true"); } if (data instanceof DOMSubTreeData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "DOMSubTreeData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "DOMSubTreeData = true"); } - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; in = new XMLSignatureInput(subTree.getRoot()); in.setExcludeComments(subTree.excludeComments()); } else { - Set nodeSet = - Utils.toNodeSet(((NodeSetData) data).iterator()); + @SuppressWarnings("unchecked") + Set nodeSet = + Utils.toNodeSet(((NodeSetData)data).iterator()); in = new XMLSignatureInput(nodeSet); } } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = false"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = false"); } try { in = new XMLSignatureInput --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java 2013-06-28 11:34:44.288227364 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java 2013-06-28 11:34:44.116232718 -0400 @@ -2,33 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMBase64Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMBase64Transform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.security.InvalidAlgorithmParameterException; -import javax.xml.crypto.XMLStructure; import javax.xml.crypto.dsig.spec.TransformParameterSpec; /** @@ -38,7 +39,7 @@ * @author Sean Mullan */ public final class DOMBase64Transform extends ApacheTransform { - + public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params != null) { --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java 2013-06-28 11:34:44.948206820 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java 2013-06-28 11:34:44.776212174 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalXMLC14N11Method.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id$ */ package org.jcp.xml.dsig.internal.dom; @@ -44,7 +46,7 @@ public final class DOMCanonicalXMLC14N11Method extends ApacheCanonicalizer { public static final String C14N_11 = "http://www.w3.org/2006/12/xml-c14n11"; - public static final String C14N_11_WITH_COMMENTS + public static final String C14N_11_WITH_COMMENTS = "http://www.w3.org/2006/12/xml-c14n11#WithComments"; public void init(TransformParameterSpec params) --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java 2013-06-28 11:34:45.624185779 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java 2013-06-28 11:34:45.452191132 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalXMLC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCanonicalXMLC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java 2013-06-28 11:34:46.308164489 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java 2013-06-28 11:34:46.136169842 -0400 @@ -2,33 +2,36 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalizationMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCanonicalizationMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.Provider; +import java.security.spec.AlgorithmParameterSpec; import org.w3c.dom.Element; @@ -40,7 +43,7 @@ * * @author Sean Mullan */ -public class DOMCanonicalizationMethod extends DOMTransform +public class DOMCanonicalizationMethod extends DOMTransform implements CanonicalizationMethod { /** @@ -49,7 +52,8 @@ * @param spi TransformService */ public DOMCanonicalizationMethod(TransformService spi) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { super(spi); if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) { @@ -59,14 +63,16 @@ } /** - * Creates a DOMCanonicalizationMethod from an element. This - * ctor invokes the abstract {@link #unmarshalParams unmarshalParams} + * Creates a DOMCanonicalizationMethod from an element. This + * ctor invokes the abstract {@link #unmarshalParams unmarshalParams} * method to unmarshal any algorithm-specific input parameters. * * @param cmElem a CanonicalizationMethod element */ public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { super(cmElem, context, provider); if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) { @@ -88,15 +94,18 @@ * canonicalizing the data */ public Data canonicalize(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return transform(data, xc); } public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { return transform(data, xc, os); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -105,12 +114,24 @@ if (!(o instanceof CanonicalizationMethod)) { return false; } - CanonicalizationMethod ocm = (CanonicalizationMethod) o; + CanonicalizationMethod ocm = (CanonicalizationMethod)o; return (getAlgorithm().equals(ocm.getAlgorithm()) && DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec())); } + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + private static boolean isC14Nalg(String alg) { return (alg.equals(CanonicalizationMethod.INCLUSIVE) || alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) || --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java 2013-06-28 11:34:47.004142825 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java 2013-06-28 11:34:46.828148303 -0400 @@ -2,41 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCryptoBinary.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCryptoBinary.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.math.BigInteger; import javax.xml.crypto.*; import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.*; import org.w3c.dom.Node; import org.w3c.dom.Text; import com.sun.org.apache.xml.internal.security.utils.Base64; /** - * A DOM-based representation of the XML CryptoBinary simple type + * A DOM-based representation of the XML CryptoBinary simple type * as defined in the W3C specification for XML-Signature Syntax and Processing. * The XML Schema Definition is defined as: * @@ -46,7 +47,7 @@ * * * - * + * * @author Sean Mullan */ public final class DOMCryptoBinary extends DOMStructure { @@ -94,7 +95,7 @@ return bigNum; } - public void marshal(Node parent, String prefix, DOMCryptoContext context) + public void marshal(Node parent, String prefix, DOMCryptoContext context) throws MarshalException { parent.appendChild (DOMUtils.getOwnerDocument(parent).createTextNode(value)); --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java 2013-06-28 11:34:47.676121907 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java 2013-06-28 11:34:47.500127386 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMDigestMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMDigestMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -42,10 +44,10 @@ * * @author Sean Mullan */ -public abstract class DOMDigestMethod extends DOMStructure +public abstract class DOMDigestMethod extends DOMStructure implements DigestMethod { - final static String SHA384 = + static final String SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384"; // see RFC 4051 private DigestMethodParameterSpec params; @@ -57,13 +59,14 @@ * appropriate for this digest method */ DOMDigestMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null && !(params instanceof DigestMethodParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type DigestMethodParameterSpec"); } - checkParams((DigestMethodParameterSpec) params); - this.params = (DigestMethodParameterSpec) params; + checkParams((DigestMethodParameterSpec)params); + this.params = (DigestMethodParameterSpec)params; } /** @@ -96,8 +99,8 @@ } else if (alg.equals(DigestMethod.SHA512)) { return new SHA512(dmElem); } else { - throw new MarshalException - ("unsupported DigestMethod algorithm: " + alg); + throw new MarshalException("unsupported DigestMethod algorithm: " + + alg); } } @@ -112,11 +115,12 @@ * appropriate for this digest method */ void checkParams(DigestMethodParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { throw new InvalidAlgorithmParameterException("no parameters " + - "should be specified for the " + getMessageDigestAlgorithm() - + " DigestMethod algorithm"); + "should be specified for the " + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } } @@ -125,32 +129,35 @@ } /** - * Unmarshals DigestMethodParameterSpec from the specified + * Unmarshals DigestMethodParameterSpec from the specified * Element. By default, this method throws an exception since - * most DigestMethod algorithms do not have parameters. Subclasses should + * most DigestMethod algorithms do not have parameters. Subclasses should * override it if they have parameters. * * @param paramsElem the Element holding the input params * @return the algorithm-specific DigestMethodParameterSpec * @throws MarshalException if the parameters cannot be unmarshalled */ - DigestMethodParameterSpec - unmarshalParams(Element paramsElem) throws MarshalException { + DigestMethodParameterSpec unmarshalParams(Element paramsElem) + throws MarshalException + { throw new MarshalException("no parameters should " + - "be specified for the " + getMessageDigestAlgorithm() + - " DigestMethod algorithm"); + "be specified for the " + + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } /** - * This method invokes the abstract {@link #marshalParams marshalParams} + * This method invokes the abstract {@link #marshalParams marshalParams} * method to marshal any algorithm-specific parameters. */ public void marshal(Node parent, String prefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element dmElem = DOMUtils.createElement - (ownerDoc, "DigestMethod", XMLSignature.XMLNS, prefix); + Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod", + XMLSignature.XMLNS, prefix); DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm()); if (params != null) { @@ -160,6 +167,7 @@ parent.appendChild(dmElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -168,13 +176,24 @@ if (!(o instanceof DigestMethod)) { return false; } - DigestMethod odm = (DigestMethod) o; + DigestMethod odm = (DigestMethod)o; boolean paramsEqual = (params == null ? odm.getParameterSpec() == null : params.equals(odm.getParameterSpec())); return (getAlgorithm().equals(odm.getAlgorithm()) && paramsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (params != null) { + result = 31 * result + params.hashCode(); + } + result = 31 * result + getAlgorithm().hashCode(); + + return result; + } /** * Marshals the algorithm-specific parameters to an Element and @@ -187,10 +206,12 @@ * @throws MarshalException if the parameters cannot be marshalled */ void marshalParams(Element parent, String prefix) - throws MarshalException { + throws MarshalException + { throw new MarshalException("no parameters should " + - "be specified for the " + getMessageDigestAlgorithm() + - " DigestMethod algorithm"); + "be specified for the " + + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } /** --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java 2013-06-28 11:34:48.368100368 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java 2013-06-28 11:34:48.200105597 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMEnvelopedTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMEnvelopedTransform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java 2013-06-28 11:34:49.024079949 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java 2013-06-28 11:34:48.852085303 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMExcC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMExcC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -50,18 +52,20 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { if (!(params instanceof ExcC14NParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type ExcC14NParameterSpec"); } - this.params = (C14NMethodParameterSpec) params; + this.params = (C14NMethodParameterSpec)params; } } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { super.init(parent, context); Element paramsElem = DOMUtils.getFirstChildElement(transformElem); if (paramsElem == null) { @@ -77,7 +81,7 @@ this.inclusiveNamespaces = prefixListAttr; int begin = 0; int end = prefixListAttr.indexOf(' '); - List prefixList = new ArrayList(); + List prefixList = new ArrayList(); while (end != -1) { prefixList.add(prefixListAttr.substring(begin, end)); begin = end + 1; @@ -90,39 +94,42 @@ } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); AlgorithmParameterSpec spec = getParameterSpec(); if (spec == null) { return; } - String prefix = - DOMUtils.getNSPrefix(context, CanonicalizationMethod.EXCLUSIVE); - Element excElem = DOMUtils.createElement - (ownerDoc, "InclusiveNamespaces", - CanonicalizationMethod.EXCLUSIVE, prefix); + String prefix = DOMUtils.getNSPrefix(context, + CanonicalizationMethod.EXCLUSIVE); + Element eElem = DOMUtils.createElement(ownerDoc, + "InclusiveNamespaces", + CanonicalizationMethod.EXCLUSIVE, + prefix); if (prefix == null || prefix.length() == 0) { - excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", - CanonicalizationMethod.EXCLUSIVE); + eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", + CanonicalizationMethod.EXCLUSIVE); } else { - excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", - "xmlns:" + prefix, CanonicalizationMethod.EXCLUSIVE); + eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns:" + prefix, + CanonicalizationMethod.EXCLUSIVE); } - ExcC14NParameterSpec params = (ExcC14NParameterSpec) spec; + ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec; StringBuffer prefixListAttr = new StringBuffer(""); - List prefixList = params.getPrefixList(); + @SuppressWarnings("unchecked") + List prefixList = params.getPrefixList(); for (int i = 0, size = prefixList.size(); i < size; i++) { - prefixListAttr.append((String) prefixList.get(i)); + prefixListAttr.append(prefixList.get(i)); if (i < size - 1) { prefixListAttr.append(" "); } } - DOMUtils.setAttribute(excElem, "PrefixList", prefixListAttr.toString()); + DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString()); this.inclusiveNamespaces = prefixListAttr.toString(); - transformElem.appendChild(excElem); + transformElem.appendChild(eElem); } public String getParamsNSURI() { @@ -130,13 +137,13 @@ } public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - + throws TransformException + { // ignore comments if dereferencing same-document URI that require // you to omit comments, even if the Transform says otherwise - // this is to be compliant with section 4.3.3.3 of W3C Rec. if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; if (subTree.excludeComments()) { try { apacheCanonicalizer = Canonicalizer.getInstance --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java 2013-06-28 11:34:49.704058783 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java 2013-06-28 11:34:49.532064136 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMHMACSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMHMACSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -38,8 +40,6 @@ import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.security.spec.AlgorithmParameterSpec; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.crypto.Mac; import javax.crypto.SecretKey; import org.w3c.dom.Document; @@ -52,23 +52,35 @@ * * @author Sean Mullan */ -public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { +public abstract class DOMHMACSignatureMethod extends AbstractDOMSignatureMethod { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + + // see RFC 4051 for these algorithm definitions + static final String HMAC_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; + static final String HMAC_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; + static final String HMAC_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; - private static Logger log = - Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Mac hmac; private int outputLength; private boolean outputLengthSet; + private SignatureMethodParameterSpec params; /** - * Creates a DOMHMACSignatureMethod with the specified params + * Creates a DOMHMACSignatureMethod with the specified params * * @param params algorithm-specific parameters (may be null) * @throws InvalidAlgorithmParameterException if params are inappropriate */ DOMHMACSignatureMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { - super(params); + throws InvalidAlgorithmParameterException + { + checkParams((SignatureMethodParameterSpec)params); + this.params = (SignatureMethodParameterSpec)params; } /** @@ -77,54 +89,64 @@ * @param smElem a SignatureMethod element */ DOMHMACSignatureMethod(Element smElem) throws MarshalException { - super(smElem); + Element paramsElem = DOMUtils.getFirstChildElement(smElem); + if (paramsElem != null) { + params = unmarshalParams(paramsElem); + } + try { + checkParams(params); + } catch (InvalidAlgorithmParameterException iape) { + throw new MarshalException(iape); + } } - void checkParams(SignatureMethodParameterSpec params) - throws InvalidAlgorithmParameterException { + void checkParams(SignatureMethodParameterSpec params) + throws InvalidAlgorithmParameterException + { if (params != null) { if (!(params instanceof HMACParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type HMACParameterSpec"); } - outputLength = ((HMACParameterSpec) params).getOutputLength(); + outputLength = ((HMACParameterSpec)params).getOutputLength(); outputLengthSet = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, - "Setting outputLength from HMACParameterSpec to: " - + outputLength); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Setting outputLength from HMACParameterSpec to: " + outputLength); } - } else { - outputLength = -1; } } + public final AlgorithmParameterSpec getParameterSpec() { + return params; + } + SignatureMethodParameterSpec unmarshalParams(Element paramsElem) - throws MarshalException { - outputLength = new Integer - (paramsElem.getFirstChild().getNodeValue()).intValue(); + throws MarshalException + { + outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue(); outputLengthSet = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "unmarshalled outputLength: " + outputLength); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "unmarshalled outputLength: " + outputLength); } return new HMACParameterSpec(outputLength); } void marshalParams(Element parent, String prefix) - throws MarshalException { - + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength", - XMLSignature.XMLNS, prefix); + XMLSignature.XMLNS, prefix); hmacElem.appendChild(ownerDoc.createTextNode (String.valueOf(outputLength))); parent.appendChild(hmacElem); } - boolean verify(Key key, DOMSignedInfo si, byte[] sig, - XMLValidateContext context) - throws InvalidKeyException, SignatureException, XMLSignatureException { + boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException + { if (key == null || si == null || sig == null) { throw new NullPointerException(); } @@ -133,7 +155,7 @@ } if (hmac == null) { try { - hmac = Mac.getInstance(getSignatureAlgorithm()); + hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -142,15 +164,16 @@ throw new XMLSignatureException ("HMACOutputLength must not be less than " + getDigestLength()); } - hmac.init((SecretKey) key); - si.canonicalize(context, new MacOutputStream(hmac)); + hmac.init((SecretKey)key); + ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac)); byte[] result = hmac.doFinal(); return MessageDigest.isEqual(sig, result); } - byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context) - throws InvalidKeyException, XMLSignatureException { + byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException + { if (key == null || si == null) { throw new NullPointerException(); } @@ -159,7 +182,7 @@ } if (hmac == null) { try { - hmac = Mac.getInstance(getSignatureAlgorithm()); + hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -168,8 +191,8 @@ throw new XMLSignatureException ("HMACOutputLength must not be less than " + getDigestLength()); } - hmac.init((SecretKey) key); - si.canonicalize(context, new MacOutputStream(hmac)); + hmac.init((SecretKey)key); + ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac)); return hmac.doFinal(); } @@ -180,11 +203,15 @@ if (!(spec instanceof HMACParameterSpec)) { return false; } - HMACParameterSpec ospec = (HMACParameterSpec) spec; + HMACParameterSpec ospec = (HMACParameterSpec)spec; return (outputLength == ospec.getOutputLength()); } + Type getAlgorithmType() { + return Type.HMAC; + } + /** * Returns the output length of the hash/digest. */ @@ -201,7 +228,7 @@ public String getAlgorithm() { return SignatureMethod.HMAC_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA1"; } int getDigestLength() { @@ -220,7 +247,7 @@ public String getAlgorithm() { return HMAC_SHA256; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA256"; } int getDigestLength() { @@ -239,7 +266,7 @@ public String getAlgorithm() { return HMAC_SHA384; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA384"; } int getDigestLength() { @@ -258,7 +285,7 @@ public String getAlgorithm() { return HMAC_SHA512; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA512"; } int getDigestLength() { --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java 2013-06-28 11:34:50.392037368 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java 2013-06-28 11:34:50.220042721 -0400 @@ -2,38 +2,40 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyInfo.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; -import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dom.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -48,7 +50,7 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { private final String id; - private final List keyInfoTypes; + private final List keyInfoTypes; /** * Creates a DOMKeyInfo. @@ -62,21 +64,21 @@ * @throws ClassCastException if content contains any entries * that are not of type {@link XMLStructure} */ - public DOMKeyInfo(List content, String id) { + public DOMKeyInfo(List content, String id) { if (content == null) { throw new NullPointerException("content cannot be null"); } - List typesCopy = new ArrayList(content); - if (typesCopy.isEmpty()) { + this.keyInfoTypes = + Collections.unmodifiableList(new ArrayList(content)); + if (this.keyInfoTypes.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } - for (int i = 0, size = typesCopy.size(); i < size; i++) { - if (!(typesCopy.get(i) instanceof XMLStructure)) { + for (int i = 0, size = this.keyInfoTypes.size(); i < size; i++) { + if (!(this.keyInfoTypes.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid KeyInfo type"); } } - this.keyInfoTypes = Collections.unmodifiableList(typesCopy); this.id = id; } @@ -86,7 +88,9 @@ * @param kiElem KeyInfo element */ public DOMKeyInfo(Element kiElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // get Id attribute, if specified Attr attr = kiElem.getAttributeNodeNS(null, "Id"); if (attr != null) { @@ -103,24 +107,24 @@ throw new MarshalException ("KeyInfo must contain at least one type"); } - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nl.item(i); // ignore all non-Element nodes if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } - Element childElem = (Element) child; + Element childElem = (Element)child; String localName = childElem.getLocalName(); if (localName.equals("X509Data")) { content.add(new DOMX509Data(childElem)); } else if (localName.equals("KeyName")) { content.add(new DOMKeyName(childElem)); } else if (localName.equals("KeyValue")) { - content.add(new DOMKeyValue(childElem)); + content.add(DOMKeyValue.unmarshal(childElem)); } else if (localName.equals("RetrievalMethod")) { - content.add - (new DOMRetrievalMethod(childElem, context, provider)); + content.add(new DOMRetrievalMethod(childElem, + context, provider)); } else if (localName.equals("PGPData")) { content.add(new DOMPGPData(childElem)); } else { //may be MgmtData, SPKIData or element from other namespace @@ -139,51 +143,58 @@ } public void marshal(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (parent == null) { throw new NullPointerException("parent is null"); } + if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } - Node pNode = ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); String dsPrefix = DOMUtils.getSignaturePrefix(context); - Element kiElem = DOMUtils.createElement + Element kiElem = DOMUtils.createElement (DOMUtils.getOwnerDocument(pNode), "KeyInfo", XMLSignature.XMLNS, dsPrefix); if (dsPrefix == null || dsPrefix.length() == 0) { - kiElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); + kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns", XMLSignature.XMLNS); } else { - kiElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, - XMLSignature.XMLNS); + kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns:" + dsPrefix, XMLSignature.XMLNS); } - marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext) context); + marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context); } public void marshal(Node parent, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { marshal(parent, null, dsPrefix, context); } public void marshal(Node parent, Node nextSibling, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element kiElem = DOMUtils.createElement - (ownerDoc, "KeyInfo", XMLSignature.XMLNS, dsPrefix); + Element kiElem = DOMUtils.createElement(ownerDoc, "KeyInfo", + XMLSignature.XMLNS, dsPrefix); marshal(parent, kiElem, nextSibling, dsPrefix, context); } private void marshal(Node parent, Element kiElem, Node nextSibling, - String dsPrefix, DOMCryptoContext context) throws MarshalException { + String dsPrefix, DOMCryptoContext context) + throws MarshalException + { // create and append KeyInfoType elements - for (int i = 0, size = keyInfoTypes.size(); i < size; i++) { - XMLStructure kiType = (XMLStructure) keyInfoTypes.get(i); + for (XMLStructure kiType : keyInfoTypes) { if (kiType instanceof DOMStructure) { - ((DOMStructure) kiType).marshal(kiElem, dsPrefix, context); + ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context); } else { DOMUtils.appendChild(kiElem, - ((javax.xml.crypto.dom.DOMStructure) kiType).getNode()); + ((javax.xml.crypto.dom.DOMStructure)kiType).getNode()); } } @@ -193,6 +204,7 @@ parent.insertBefore(kiElem, nextSibling); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -201,11 +213,22 @@ if (!(o instanceof KeyInfo)) { return false; } - KeyInfo oki = (KeyInfo) o; + KeyInfo oki = (KeyInfo)o; - boolean idsEqual = (id == null ? oki.getId() == null : - id.equals(oki.getId())); + boolean idsEqual = (id == null ? oki.getId() == null + : id.equals(oki.getId())); return (keyInfoTypes.equals(oki.getContent()) && idsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + keyInfoTypes.hashCode(); + + return result; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java 2013-06-28 11:34:51.072016202 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java 2013-06-28 11:34:50.900021555 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyInfoFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyInfoFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,8 +33,7 @@ import java.security.PublicKey; import java.util.List; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.*; -import javax.xml.crypto.dom.*; +import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.keyinfo.*; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -51,6 +52,7 @@ return newKeyInfo(content, null); } + @SuppressWarnings("unchecked") public KeyInfo newKeyInfo(List content, String id) { return new DOMKeyInfo(content, id); } @@ -60,17 +62,28 @@ } public KeyValue newKeyValue(PublicKey key) throws KeyException { - return new DOMKeyValue(key); + String algorithm = key.getAlgorithm(); + if (algorithm.equals("DSA")) { + return new DOMKeyValue.DSA(key); + } else if (algorithm.equals("RSA")) { + return new DOMKeyValue.RSA(key); + } else if (algorithm.equals("EC")) { + return new DOMKeyValue.EC(key); + } else { + throw new KeyException("unsupported key algorithm: " + algorithm); + } } public PGPData newPGPData(byte[] keyId) { return newPGPData(keyId, null, null); } + @SuppressWarnings("unchecked") public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) { return new DOMPGPData(keyId, keyPacket, other); } + @SuppressWarnings("unchecked") public PGPData newPGPData(byte[] keyPacket, List other) { return new DOMPGPData(keyPacket, other); } @@ -79,6 +92,7 @@ return newRetrievalMethod(uri, null, null); } + @SuppressWarnings("unchecked") public RetrievalMethod newRetrievalMethod(String uri, String type, List transforms) { if (uri == null) { @@ -87,11 +101,12 @@ return new DOMRetrievalMethod(uri, type, transforms); } + @SuppressWarnings("unchecked") public X509Data newX509Data(List content) { return new DOMX509Data(content); } - public X509IssuerSerial newX509IssuerSerial(String issuerName, + public X509IssuerSerial newX509IssuerSerial(String issuerName, BigInteger serialNumber) { return new DOMX509IssuerSerial(issuerName, serialNumber); } @@ -108,12 +123,15 @@ return DOMURIDereferencer.INSTANCE; } - public KeyInfo unmarshalKeyInfo(XMLStructure xmlStructure) + public KeyInfo unmarshalKeyInfo(XMLStructure xmlStructure) throws MarshalException { if (xmlStructure == null) { throw new NullPointerException("xmlStructure cannot be null"); } - Node node = + if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("xmlStructure must be of type DOMStructure"); + } + Node node = ((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(); node.normalize(); @@ -134,9 +152,14 @@ "support DOM Level 2 and be namespace aware"); } if (tag.equals("KeyInfo")) { - return new DOMKeyInfo(element, null, getProvider()); + return new DOMKeyInfo(element, new UnmarshalContext(), getProvider()); } else { throw new MarshalException("invalid KeyInfo tag: " + tag); } } + + private static class UnmarshalContext extends DOMCryptoContext { + UnmarshalContext() {} + } + } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java 2013-06-28 11:34:51.719996031 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java 2013-06-28 11:34:51.548001386 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyName.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyName.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -45,7 +47,7 @@ private final String name; /** - * Creates a DOMKeyName. + * Creates a DOMKeyName. * * @param name the name of the key identifier * @throws NullPointerException if name is null @@ -71,15 +73,17 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); // prepend namespace prefix, if necessary - Element knElem = DOMUtils.createElement - (ownerDoc, "KeyName", XMLSignature.XMLNS, dsPrefix); + Element knElem = DOMUtils.createElement(ownerDoc, "KeyName", + XMLSignature.XMLNS, dsPrefix); knElem.appendChild(ownerDoc.createTextNode(name)); parent.appendChild(knElem); } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -87,7 +91,15 @@ if (!(obj instanceof KeyName)) { return false; } - KeyName okn = (KeyName) obj; + KeyName okn = (KeyName)obj; return name.equals(okn.getName()); } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + name.hashCode(); + + return result; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java 2013-06-28 11:34:52.399974866 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java 2013-06-28 11:34:52.215980593 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyValue.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyValue.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,14 +33,25 @@ import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.keyinfo.KeyValue; +// import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; import java.security.KeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPublicKey; +import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPublicKeySpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.EllipticCurve; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; @@ -46,59 +59,46 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; +import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; +import com.sun.org.apache.xml.internal.security.utils.Base64; + /** * DOM-based implementation of KeyValue. * * @author Sean Mullan */ -public final class DOMKeyValue extends DOMStructure implements KeyValue { - - private KeyFactory rsakf, dsakf; - private PublicKey publicKey; - private javax.xml.crypto.dom.DOMStructure externalPublicKey; - - // DSAKeyValue CryptoBinaries - private DOMCryptoBinary p, q, g, y, j, seed, pgen; +public abstract class DOMKeyValue extends DOMStructure implements KeyValue { - // RSAKeyValue CryptoBinaries - private DOMCryptoBinary modulus, exponent; + private static final String XMLDSIG_11_XMLNS + = "http://www.w3.org/2009/xmldsig11#"; + private final PublicKey publicKey; - public DOMKeyValue(PublicKey key) throws KeyException { + public DOMKeyValue(PublicKey key) throws KeyException { if (key == null) { throw new NullPointerException("key cannot be null"); } this.publicKey = key; - if (key instanceof DSAPublicKey) { - DSAPublicKey dkey = (DSAPublicKey) key; - DSAParams params = dkey.getParams(); - p = new DOMCryptoBinary(params.getP()); - q = new DOMCryptoBinary(params.getQ()); - g = new DOMCryptoBinary(params.getG()); - y = new DOMCryptoBinary(dkey.getY()); - } else if (key instanceof RSAPublicKey) { - RSAPublicKey rkey = (RSAPublicKey) key; - exponent = new DOMCryptoBinary(rkey.getPublicExponent()); - modulus = new DOMCryptoBinary(rkey.getModulus()); - } else { - throw new KeyException("unsupported key algorithm: " + - key.getAlgorithm()); - } } /** * Creates a DOMKeyValue from an element. * - * @param kvElem a KeyValue element + * @param kvtElem a KeyValue child element */ - public DOMKeyValue(Element kvElem) throws MarshalException { + public DOMKeyValue(Element kvtElem) throws MarshalException { + this.publicKey = unmarshalKeyValue(kvtElem); + } + + static KeyValue unmarshal(Element kvElem) throws MarshalException { Element kvtElem = DOMUtils.getFirstChildElement(kvElem); if (kvtElem.getLocalName().equals("DSAKeyValue")) { - publicKey = unmarshalDSAKeyValue(kvtElem); + return new DSA(kvtElem); } else if (kvtElem.getLocalName().equals("RSAKeyValue")) { - publicKey = unmarshalRSAKeyValue(kvtElem); + return new RSA(kvtElem); + } else if (kvtElem.getLocalName().equals("ECKeyValue")) { + return new EC(kvtElem); } else { - publicKey = null; - externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvtElem); + return new Unknown(kvtElem); } } @@ -111,133 +111,25 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); // create KeyValue element - Element kvElem = DOMUtils.createElement - (ownerDoc, "KeyValue", XMLSignature.XMLNS, dsPrefix); + Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue", + XMLSignature.XMLNS, dsPrefix); marshalPublicKey(kvElem, ownerDoc, dsPrefix, context); parent.appendChild(kvElem); } - private void marshalPublicKey(Node parent, Document doc, String dsPrefix, - DOMCryptoContext context) throws MarshalException { - if (publicKey != null) { - if (publicKey instanceof DSAPublicKey) { - // create and append DSAKeyValue element - marshalDSAPublicKey(parent, doc, dsPrefix, context); - } else if (publicKey instanceof RSAPublicKey) { - // create and append RSAKeyValue element - marshalRSAPublicKey(parent, doc, dsPrefix, context); - } else { - throw new MarshalException(publicKey.getAlgorithm() + - " public key algorithm not supported"); - } - } else { - parent.appendChild(externalPublicKey.getNode()); - } - } + abstract void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) throws MarshalException; - private void marshalDSAPublicKey(Node parent, Document doc, - String dsPrefix, DOMCryptoContext context) throws MarshalException { - Element dsaElem = DOMUtils.createElement - (doc, "DSAKeyValue", XMLSignature.XMLNS, dsPrefix); - // parameters J, Seed & PgenCounter are not included - Element pElem = DOMUtils.createElement - (doc, "P", XMLSignature.XMLNS, dsPrefix); - Element qElem = DOMUtils.createElement - (doc, "Q", XMLSignature.XMLNS, dsPrefix); - Element gElem = DOMUtils.createElement - (doc, "G", XMLSignature.XMLNS, dsPrefix); - Element yElem = DOMUtils.createElement - (doc, "Y", XMLSignature.XMLNS, dsPrefix); - p.marshal(pElem, dsPrefix, context); - q.marshal(qElem, dsPrefix, context); - g.marshal(gElem, dsPrefix, context); - y.marshal(yElem, dsPrefix, context); - dsaElem.appendChild(pElem); - dsaElem.appendChild(qElem); - dsaElem.appendChild(gElem); - dsaElem.appendChild(yElem); - parent.appendChild(dsaElem); - } - - private void marshalRSAPublicKey(Node parent, Document doc, - String dsPrefix, DOMCryptoContext context) throws MarshalException { - Element rsaElem = DOMUtils.createElement - (doc, "RSAKeyValue", XMLSignature.XMLNS, dsPrefix); - Element modulusElem = DOMUtils.createElement - (doc, "Modulus", XMLSignature.XMLNS, dsPrefix); - Element exponentElem = DOMUtils.createElement - (doc, "Exponent", XMLSignature.XMLNS, dsPrefix); - modulus.marshal(modulusElem, dsPrefix, context); - exponent.marshal(exponentElem, dsPrefix, context); - rsaElem.appendChild(modulusElem); - rsaElem.appendChild(exponentElem); - parent.appendChild(rsaElem); - } - - private DSAPublicKey unmarshalDSAKeyValue(Element kvtElem) - throws MarshalException { - if (dsakf == null) { - try { - dsakf = KeyFactory.getInstance("DSA"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("unable to create DSA KeyFactory: " + - e.getMessage()); - } - } - Element curElem = DOMUtils.getFirstChildElement(kvtElem); - // check for P and Q - if (curElem.getLocalName().equals("P")) { - p = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - q = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - if (curElem.getLocalName().equals("G")) { - g = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - y = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - if (curElem != null && curElem.getLocalName().equals("J")) { - j = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - if (curElem != null) { - seed = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - pgen = new DOMCryptoBinary(curElem.getFirstChild()); - } - //@@@ do we care about j, pgenCounter or seed? - DSAPublicKeySpec spec = new DSAPublicKeySpec - (y.getBigNum(), p.getBigNum(), q.getBigNum(), g.getBigNum()); - return (DSAPublicKey) generatePublicKey(dsakf, spec); - } - - private RSAPublicKey unmarshalRSAKeyValue(Element kvtElem) - throws MarshalException { - if (rsakf == null) { - try { - rsakf = KeyFactory.getInstance("RSA"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("unable to create RSA KeyFactory: " + - e.getMessage()); - } - } - Element modulusElem = DOMUtils.getFirstChildElement(kvtElem); - modulus = new DOMCryptoBinary(modulusElem.getFirstChild()); - Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem); - exponent = new DOMCryptoBinary(exponentElem.getFirstChild()); - RSAPublicKeySpec spec = new RSAPublicKeySpec - (modulus.getBigNum(), exponent.getBigNum()); - return (RSAPublicKey) generatePublicKey(rsakf, spec); - } + abstract PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException; - private PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) { + private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) { try { return kf.generatePublic(keyspec); } catch (InvalidKeySpecException e) { @@ -245,7 +137,8 @@ return null; } } - + + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -254,7 +147,7 @@ return false; } try { - KeyValue kv = (KeyValue) obj; + KeyValue kv = (KeyValue)obj; if (publicKey == null ) { if (kv.getPublicKey() != null) { return false; @@ -266,7 +159,343 @@ // no practical way to determine if the keys are equal return false; } - + return true; } + + @Override + public int hashCode() { + int result = 17; + if (publicKey != null) { + result = 31 * result + publicKey.hashCode(); + } + + return result; + } + + static final class RSA extends DOMKeyValue { + // RSAKeyValue CryptoBinaries + private DOMCryptoBinary modulus, exponent; + private KeyFactory rsakf; + + RSA(PublicKey key) throws KeyException { + super(key); + RSAPublicKey rkey = (RSAPublicKey)key; + exponent = new DOMCryptoBinary(rkey.getPublicExponent()); + modulus = new DOMCryptoBinary(rkey.getModulus()); + } + + RSA(Element elem) throws MarshalException { + super(elem); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) throws MarshalException { + Element rsaElem = DOMUtils.createElement(doc, "RSAKeyValue", + XMLSignature.XMLNS, + dsPrefix); + Element modulusElem = DOMUtils.createElement(doc, "Modulus", + XMLSignature.XMLNS, + dsPrefix); + Element exponentElem = DOMUtils.createElement(doc, "Exponent", + XMLSignature.XMLNS, + dsPrefix); + modulus.marshal(modulusElem, dsPrefix, context); + exponent.marshal(exponentElem, dsPrefix, context); + rsaElem.appendChild(modulusElem); + rsaElem.appendChild(exponentElem); + parent.appendChild(rsaElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (rsakf == null) { + try { + rsakf = KeyFactory.getInstance("RSA"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create RSA KeyFactory: " + e.getMessage()); + } + } + Element modulusElem = DOMUtils.getFirstChildElement(kvtElem); + modulus = new DOMCryptoBinary(modulusElem.getFirstChild()); + Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem); + exponent = new DOMCryptoBinary(exponentElem.getFirstChild()); + RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(), + exponent.getBigNum()); + return generatePublicKey(rsakf, spec); + } + } + + static final class DSA extends DOMKeyValue { + // DSAKeyValue CryptoBinaries + private DOMCryptoBinary p, q, g, y, j; //, seed, pgen; + private KeyFactory dsakf; + + DSA(PublicKey key) throws KeyException { + super(key); + DSAPublicKey dkey = (DSAPublicKey) key; + DSAParams params = dkey.getParams(); + p = new DOMCryptoBinary(params.getP()); + q = new DOMCryptoBinary(params.getQ()); + g = new DOMCryptoBinary(params.getG()); + y = new DOMCryptoBinary(dkey.getY()); + } + + DSA(Element elem) throws MarshalException { + super(elem); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue", + XMLSignature.XMLNS, + dsPrefix); + // parameters J, Seed & PgenCounter are not included + Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS, + dsPrefix); + Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS, + dsPrefix); + Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS, + dsPrefix); + Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS, + dsPrefix); + p.marshal(pElem, dsPrefix, context); + q.marshal(qElem, dsPrefix, context); + g.marshal(gElem, dsPrefix, context); + y.marshal(yElem, dsPrefix, context); + dsaElem.appendChild(pElem); + dsaElem.appendChild(qElem); + dsaElem.appendChild(gElem); + dsaElem.appendChild(yElem); + parent.appendChild(dsaElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (dsakf == null) { + try { + dsakf = KeyFactory.getInstance("DSA"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create DSA KeyFactory: " + e.getMessage()); + } + } + Element curElem = DOMUtils.getFirstChildElement(kvtElem); + // check for P and Q + if (curElem.getLocalName().equals("P")) { + p = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + q = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + } + if (curElem.getLocalName().equals("G")) { + g = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + } + y = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + if (curElem != null && curElem.getLocalName().equals("J")) { + j = new DOMCryptoBinary(curElem.getFirstChild()); + // curElem = DOMUtils.getNextSiblingElement(curElem); + } + /* + if (curElem != null) { + seed = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + pgen = new DOMCryptoBinary(curElem.getFirstChild()); + } + */ + //@@@ do we care about j, pgenCounter or seed? + DSAPublicKeySpec spec = new DSAPublicKeySpec(y.getBigNum(), + p.getBigNum(), + q.getBigNum(), + g.getBigNum()); + return generatePublicKey(dsakf, spec); + } + } + + static final class EC extends DOMKeyValue { + // ECKeyValue CryptoBinaries + private byte[] ecPublicKey; + private KeyFactory eckf; + private ECParameterSpec ecParams; + private Method encodePoint, decodePoint, getCurveName, + getECParameterSpec; + + EC(PublicKey key) throws KeyException { + super(key); + ECPublicKey ecKey = (ECPublicKey)key; + ECPoint ecPoint = ecKey.getW(); + ecParams = ecKey.getParams(); + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws + ClassNotFoundException, NoSuchMethodException + { + getMethods(); + return null; + } + } + ); + } catch (PrivilegedActionException pae) { + throw new KeyException("ECKeyValue not supported", + pae.getException()); + } + Object[] args = new Object[] { ecPoint, ecParams.getCurve() }; + try { + ecPublicKey = (byte[])encodePoint.invoke(null, args); + } catch (IllegalAccessException iae) { + throw new KeyException(iae); + } catch (InvocationTargetException ite) { + throw new KeyException(ite); + } + } + + EC(Element dmElem) throws MarshalException { + super(dmElem); + } + + void getMethods() throws ClassNotFoundException, NoSuchMethodException { + Class c = Class.forName("sun.security.ec.ECParameters"); + Class[] params = new Class[] { ECPoint.class, EllipticCurve.class }; + encodePoint = c.getMethod("encodePoint", params); + params = new Class[] { ECParameterSpec.class }; + getCurveName = c.getMethod("getCurveName", params); + params = new Class[] { byte[].class, EllipticCurve.class }; + decodePoint = c.getMethod("decodePoint", params); + c = Class.forName("sun.security.ec.NamedCurve"); + params = new Class[] { String.class }; + getECParameterSpec = c.getMethod("getECParameterSpec", params); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS); + Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue", + XMLDSIG_11_XMLNS, + prefix); + Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve", + XMLDSIG_11_XMLNS, + prefix); + Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey", + XMLDSIG_11_XMLNS, + prefix); + Object[] args = new Object[] { ecParams }; + try { + String oid = (String) getCurveName.invoke(null, args); + DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } + String qname = (prefix == null || prefix.length() == 0) + ? "xmlns" : "xmlns:" + prefix; + namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + qname, XMLDSIG_11_XMLNS); + ecKeyValueElem.appendChild(namedCurveElem); + String encoded = Base64.encode(ecPublicKey); + publicKeyElem.appendChild + (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded)); + ecKeyValueElem.appendChild(publicKeyElem); + parent.appendChild(ecKeyValueElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (eckf == null) { + try { + eckf = KeyFactory.getInstance("EC"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create EC KeyFactory: " + e.getMessage()); + } + } + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws + ClassNotFoundException, NoSuchMethodException + { + getMethods(); + return null; + } + } + ); + } catch (PrivilegedActionException pae) { + throw new MarshalException("ECKeyValue not supported", + pae.getException()); + } + ECParameterSpec ecParams = null; + Element curElem = DOMUtils.getFirstChildElement(kvtElem); + if (curElem.getLocalName().equals("ECParameters")) { + throw new UnsupportedOperationException + ("ECParameters not supported"); + } else if (curElem.getLocalName().equals("NamedCurve")) { + String uri = DOMUtils.getAttributeValue(curElem, "URI"); + // strip off "urn:oid" + if (uri.startsWith("urn:oid:")) { + String oid = uri.substring(8); + try { + Object[] args = new Object[] { oid }; + ecParams = (ECParameterSpec) + getECParameterSpec.invoke(null, args); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } + } else { + throw new MarshalException("Invalid NamedCurve URI"); + } + } else { + throw new MarshalException("Invalid ECKeyValue"); + } + curElem = DOMUtils.getNextSiblingElement(curElem); + ECPoint ecPoint = null; + try { + Object[] args = new Object[] { Base64.decode(curElem), + ecParams.getCurve() }; + ecPoint = (ECPoint)decodePoint.invoke(null, args); + } catch (Base64DecodingException bde) { + throw new MarshalException("Invalid EC PublicKey", bde); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } +/* + ecPoint = sun.security.ec.ECParameters.decodePoint( + Base64.decode(curElem), ecParams.getCurve()); +*/ + ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams); + return generatePublicKey(eckf, spec); + } + } + + static final class Unknown extends DOMKeyValue { + private javax.xml.crypto.dom.DOMStructure externalPublicKey; + Unknown(Element elem) throws MarshalException { + super(elem); + } + PublicKey unmarshalKeyValue(Element kvElem) throws MarshalException { + externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvElem); + return null; + } + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + parent.appendChild(externalPublicKey.getNode()); + } + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java 2013-06-28 11:34:53.103952952 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java 2013-06-28 11:34:52.931958306 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMManifest.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -32,6 +34,7 @@ import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -44,7 +47,7 @@ */ public final class DOMManifest extends DOMStructure implements Manifest { - private final List references; + private final List references; private final String id; /** @@ -60,22 +63,22 @@ * @throws ClassCastException if references contains any * entries that are not of type {@link Reference} */ - public DOMManifest(List references, String id) { + public DOMManifest(List references, String id) { if (references == null) { throw new NullPointerException("references cannot be null"); } - List refCopy = new ArrayList(references); - if (refCopy.isEmpty()) { + this.references = + Collections.unmodifiableList(new ArrayList(references)); + if (this.references.isEmpty()) { throw new IllegalArgumentException("list of references must " + "contain at least one entry"); } - for (int i = 0, size = refCopy.size(); i < size; i++) { - if (!(refCopy.get(i) instanceof Reference)) { + for (int i = 0, size = this.references.size(); i < size; i++) { + if (!(this.references.get(i) instanceof Reference)) { throw new ClassCastException ("references["+i+"] is not a valid type"); } } - this.references = Collections.unmodifiableList(refCopy); this.id = id; } @@ -85,7 +88,9 @@ * @param manElem a Manifest element */ public DOMManifest(Element manElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { Attr attr = manElem.getAttributeNodeNS(null, "Id"); if (attr != null) { this.id = attr.getValue(); @@ -93,21 +98,21 @@ } else { this.id = null; } - + boolean secVal = Utils.secureValidation(context); + Element refElem = DOMUtils.getFirstChildElement(manElem); - List refs = new ArrayList(); + List refs = new ArrayList(); + int refCount = 0; while (refElem != null) { refs.add(new DOMReference(refElem, context, provider)); refElem = DOMUtils.getNextSiblingElement(refElem); - + refCount++; if (secVal && (refCount > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) { - String error = "A maxiumum of " + - DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + - " references per Manifest are allowed with" + - " secure validation"; + String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " " + + "references per Manifest are allowed with secure validation"; throw new MarshalException(error); } } @@ -117,28 +122,28 @@ public String getId() { return id; } - + public List getReferences() { return references; } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element manElem = DOMUtils.createElement - (ownerDoc, "Manifest", XMLSignature.XMLNS, dsPrefix); + Element manElem = DOMUtils.createElement(ownerDoc, "Manifest", + XMLSignature.XMLNS, dsPrefix); DOMUtils.setAttributeID(manElem, "Id", id); // add references - for (int i = 0, size = references.size(); i < size; i++) { - DOMReference ref = (DOMReference) references.get(i); - ref.marshal(manElem, dsPrefix, context); + for (Reference ref : references) { + ((DOMReference)ref).marshal(manElem, dsPrefix, context); } parent.appendChild(manElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -147,11 +152,22 @@ if (!(o instanceof Manifest)) { return false; } - Manifest oman = (Manifest) o; + Manifest oman = (Manifest)o; - boolean idsEqual = (id == null ? oman.getId() == null : - id.equals(oman.getId())); + boolean idsEqual = (id == null ? oman.getId() == null + : id.equals(oman.getId())); return (idsEqual && references.equals(oman.getReferences())); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + references.hashCode(); + + return result; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java 2013-06-28 11:34:53.791931539 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java 2013-06-28 11:34:53.599937513 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMPGPData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMPGPData.java 1203846 2011-11-18 21:18:17Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -48,42 +50,42 @@ private final byte[] keyId; private final byte[] keyPacket; - private final List externalElements; + private final List externalElements; /** - * Creates a DOMPGPData containing the specified key packet. + * Creates a DOMPGPData containing the specified key packet. * and optional list of external elements. * - * @param keyPacket a PGP Key Material Packet as defined in section 5.5 of - * RFC 2440. The + * @param keyPacket a PGP Key Material Packet as defined in section 5.5 of + * RFC 2440. The * array is cloned to prevent subsequent modification. * @param other a list of {@link XMLStructure}s representing elements from * an external namespace. The list is defensively copied to prevent * subsequent modification. May be null or empty. - * @throws NullPointerException if keyPacket is + * @throws NullPointerException if keyPacket is * null - * @throws IllegalArgumentException if the key packet is not in the + * @throws IllegalArgumentException if the key packet is not in the * correct format * @throws ClassCastException if other contains any * entries that are not of type {@link XMLStructure} */ - public DOMPGPData(byte[] keyPacket, List other) { + public DOMPGPData(byte[] keyPacket, List other) { if (keyPacket == null) { throw new NullPointerException("keyPacket cannot be null"); } if (other == null || other.isEmpty()) { - this.externalElements = Collections.EMPTY_LIST; + this.externalElements = Collections.emptyList(); } else { - List otherCopy = new ArrayList(other); - for (int i = 0, size = otherCopy.size(); i < size; i++) { - if (!(otherCopy.get(i) instanceof XMLStructure)) { + this.externalElements = + Collections.unmodifiableList(new ArrayList(other)); + for (int i = 0, size = this.externalElements.size(); i < size; i++) { + if (!(this.externalElements.get(i) instanceof XMLStructure)) { throw new ClassCastException ("other["+i+"] is not a valid PGPData type"); } } - this.externalElements = Collections.unmodifiableList(otherCopy); } - this.keyPacket = (byte []) keyPacket.clone(); + this.keyPacket = (byte[])keyPacket.clone(); checkKeyPacket(keyPacket); this.keyId = null; } @@ -92,23 +94,25 @@ * Creates a DOMPGPData containing the specified key id and * optional key packet and list of external elements. * - * @param keyId a PGP public key id as defined in section 11.2 of - * RFC 2440. The + * @param keyId a PGP public key id as defined in section 11.2 of + * RFC 2440. The * array is cloned to prevent subsequent modification. - * @param keyPacket a PGP Key Material Packet as defined in section 5.5 of + * @param keyPacket a PGP Key Material Packet as defined in section 5.5 of * RFC 2440 (may - * be null). The array is cloned to prevent subsequent + * be null). The array is cloned to prevent subsequent * modification. * @param other a list of {@link XMLStructure}s representing elements from * an external namespace. The list is defensively copied to prevent * subsequent modification. May be null or empty. * @throws NullPointerException if keyId is null - * @throws IllegalArgumentException if the key id or packet is not in the + * @throws IllegalArgumentException if the key id or packet is not in the * correct format * @throws ClassCastException if other contains any * entries that are not of type {@link XMLStructure} */ - public DOMPGPData(byte[] keyId, byte[] keyPacket, List other) { + public DOMPGPData(byte[] keyId, byte[] keyPacket, + List other) + { if (keyId == null) { throw new NullPointerException("keyId cannot be null"); } @@ -117,19 +121,20 @@ throw new IllegalArgumentException("keyId must be 8 bytes long"); } if (other == null || other.isEmpty()) { - this.externalElements = Collections.EMPTY_LIST; + this.externalElements = Collections.emptyList(); } else { - List otherCopy = new ArrayList(other); - for (int i = 0, size = otherCopy.size(); i < size; i++) { - if (!(otherCopy.get(i) instanceof XMLStructure)) { + this.externalElements = + Collections.unmodifiableList(new ArrayList(other)); + for (int i = 0, size = this.externalElements.size(); i < size; i++) { + if (!(this.externalElements.get(i) instanceof XMLStructure)) { throw new ClassCastException ("other["+i+"] is not a valid PGPData type"); } } - this.externalElements = Collections.unmodifiableList(otherCopy); } - this.keyId = (byte []) keyId.clone(); - this.keyPacket = keyPacket == null ? null : (byte []) keyPacket.clone(); + this.keyId = (byte[])keyId.clone(); + this.keyPacket = keyPacket == null ? null + : (byte[])keyPacket.clone(); if (keyPacket != null) { checkKeyPacket(keyPacket); } @@ -146,11 +151,11 @@ byte[] keyPacket = null; NodeList nl = pdElem.getChildNodes(); int length = nl.getLength(); - List other = new ArrayList(length); + List other = new ArrayList(length); for (int x = 0; x < length; x++) { Node n = nl.item(x); if (n.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element) n; + Element childElem = (Element)n; String localName = childElem.getLocalName(); try { if (localName.equals("PGPKeyID")) { @@ -172,11 +177,11 @@ } public byte[] getKeyId() { - return (keyId == null ? null : (byte []) keyId.clone()); + return (keyId == null ? null : (byte[])keyId.clone()); } public byte[] getKeyPacket() { - return (keyPacket == null ? null : (byte []) keyPacket.clone()); + return (keyPacket == null ? null : (byte[])keyPacket.clone()); } public List getExternalElements() { @@ -184,16 +189,17 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element pdElem = DOMUtils.createElement - (ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix); + Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData", + XMLSignature.XMLNS, dsPrefix); // create and append PGPKeyID element if (keyId != null) { - Element keyIdElem = DOMUtils.createElement - (ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix); + Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID", + XMLSignature.XMLNS, + dsPrefix); keyIdElem.appendChild (ownerDoc.createTextNode(Base64.encode(keyId))); pdElem.appendChild(keyIdElem); @@ -201,17 +207,19 @@ // create and append PGPKeyPacket element if (keyPacket != null) { - Element keyPktElem = DOMUtils.createElement - (ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix); + Element keyPktElem = DOMUtils.createElement(ownerDoc, + "PGPKeyPacket", + XMLSignature.XMLNS, + dsPrefix); keyPktElem.appendChild (ownerDoc.createTextNode(Base64.encode(keyPacket))); pdElem.appendChild(keyPktElem); } // create and append any elements - for (int i = 0, size = externalElements.size(); i < size; i++) { - DOMUtils.appendChild(pdElem, ((javax.xml.crypto.dom.DOMStructure) - externalElements.get(i)).getNode()); + for (XMLStructure extElem : externalElements) { + DOMUtils.appendChild(pdElem, ((javax.xml.crypto.dom.DOMStructure) + extElem).getNode()); } parent.appendChild(pdElem); @@ -222,33 +230,33 @@ * section 4 of RFC 2440. * * This method only checks if the packet contains a valid tag. The - * contents of the packet should be checked by the application. + * contents of the packet should be checked by the application. */ private void checkKeyPacket(byte[] keyPacket) { // length must be at least 3 (one byte for tag, one byte for length, // and minimally one byte of content if (keyPacket.length < 3) { throw new IllegalArgumentException("keypacket must be at least " + - "3 bytes long"); + "3 bytes long"); } int tag = keyPacket[0]; // first bit must be set if ((tag & 128) != 128) { throw new IllegalArgumentException("keypacket tag is invalid: " + - "bit 7 is not set"); + "bit 7 is not set"); } // make sure using new format if ((tag & 64) != 64) { throw new IllegalArgumentException("old keypacket tag format is " + - "unsupported"); + "unsupported"); } // tag value must be 6, 14, 5 or 7 - if (((tag & 6) != 6) && ((tag & 14) != 14) && + if (((tag & 6) != 6) && ((tag & 14) != 14) && ((tag & 5) != 5) && ((tag & 7) != 7)) { throw new IllegalArgumentException("keypacket tag is invalid: " + - "must be 6, 14, 5, or 7"); + "must be 6, 14, 5, or 7"); } } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java 2013-06-28 11:34:54.463910620 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java 2013-06-28 11:34:54.291915974 -0400 @@ -2,34 +2,36 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * =========================================================================== + * =========================================================================== * * (C) Copyright IBM Corp. 2003 All Rights Reserved. * * =========================================================================== */ /* - * $Id: DOMReference.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMReference.java 1334007 2012-05-04 14:59:46Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -43,8 +45,6 @@ import java.net.URISyntaxException; import java.security.*; import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -63,14 +63,13 @@ * @author Sean Mullan * @author Joyce Leung */ -public final class DOMReference extends DOMStructure +public final class DOMReference extends DOMStructure implements Reference, DOMURIReference { - - /** - * The maximum number of transforms per reference, if secure validation - * is enabled. - */ - public static final int MAXIMUM_TRANSFORM_COUNT = 5; + + /** + * The maximum number of transforms per reference, if secure validation is enabled. + */ + public static final int MAXIMUM_TRANSFORM_COUNT = 5; /** * Look up useC14N11 system property. If true, an explicit C14N11 transform @@ -82,17 +81,18 @@ private static boolean useC14N11 = AccessController.doPrivileged(new PrivilegedAction() { public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.useC14N11"); + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.useC14N11")); } }); - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); - + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private final DigestMethod digestMethod; private final String id; - private final List transforms; - private List allTransforms; + private final List transforms; + private List allTransforms; private final Data appliedTransformData; private Attr here; private final String uri; @@ -124,46 +124,51 @@ * not of type Transform */ public DOMReference(String uri, String type, DigestMethod dm, - List transforms, String id, Provider provider) { + List transforms, String id, + Provider provider) + { this(uri, type, dm, null, null, transforms, id, null, provider); } public DOMReference(String uri, String type, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String id, - Provider provider) { + List appliedTransforms, + Data result, List transforms, + String id, Provider provider) + { this(uri, type, dm, appliedTransforms, result, transforms, id, null, provider); } public DOMReference(String uri, String type, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String id, - byte[] digestValue, Provider provider) { + List appliedTransforms, + Data result, List transforms, + String id, byte[] digestValue, Provider provider) + { if (dm == null) { throw new NullPointerException("DigestMethod must be non-null"); } - this.allTransforms = new ArrayList(); - if (appliedTransforms != null) { - List transformsCopy = new ArrayList(appliedTransforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + if (appliedTransforms == null) { + this.allTransforms = new ArrayList(); + } else { + this.allTransforms = new ArrayList(appliedTransforms); + for (int i = 0, size = this.allTransforms.size(); i < size; i++) { + if (!(this.allTransforms.get(i) instanceof Transform)) { throw new ClassCastException ("appliedTransforms["+i+"] is not a valid type"); } } - this.allTransforms = transformsCopy; } if (transforms == null) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { - List transformsCopy = new ArrayList(transforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + this.transforms = new ArrayList(transforms); + for (int i = 0, size = this.transforms.size(); i < size; i++) { + if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } - this.transforms = transformsCopy; - this.allTransforms.addAll(transformsCopy); + this.allTransforms.addAll(this.transforms); } this.digestMethod = dm; this.uri = uri; @@ -177,39 +182,40 @@ this.type = type; this.id = id; if (digestValue != null) { - this.digestValue = (byte[]) digestValue.clone(); + this.digestValue = (byte[])digestValue.clone(); this.digested = true; } this.appliedTransformData = result; this.provider = provider; } - + /** * Creates a DOMReference from an element. * * @param refElem a Reference element */ - public DOMReference(Element refElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + public DOMReference(Element refElem, XMLCryptoContext context, + Provider provider) + throws MarshalException + { boolean secVal = Utils.secureValidation(context); - + // unmarshal Transforms, if specified Element nextSibling = DOMUtils.getFirstChildElement(refElem); - List transforms = new ArrayList(5); + List transforms = new ArrayList(5); if (nextSibling.getLocalName().equals("Transforms")) { Element transformElem = DOMUtils.getFirstChildElement(nextSibling); - + int transformCount = 0; while (transformElem != null) { transforms.add (new DOMTransform(transformElem, context, provider)); transformElem = DOMUtils.getNextSiblingElement(transformElem); - + transformCount++; if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) { - String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + - " transforms per Reference are allowed" + - " with secure validation"; + String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " " + + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } } @@ -220,12 +226,11 @@ Element dmElem = nextSibling; this.digestMethod = DOMDigestMethod.unmarshal(dmElem); String digestMethodAlgorithm = this.digestMethod.getAlgorithm(); - if (secVal - && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) - { - throw new MarshalException("It is forbidden to use algorithm " + - digestMethod + - " when secure validation is enabled"); + if (secVal + && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) { + throw new MarshalException( + "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled" + ); } // unmarshal DigestValue @@ -238,7 +243,7 @@ // unmarshal attributes this.uri = DOMUtils.getAttributeValue(refElem, "URI"); - + Attr attr = refElem.getAttributeNodeNS(null, "Id"); if (attr != null) { this.id = attr.getValue(); @@ -277,23 +282,24 @@ } public byte[] getDigestValue() { - return (digestValue == null ? null : (byte[]) digestValue.clone()); + return (digestValue == null ? null : (byte[])digestValue.clone()); } public byte[] getCalculatedDigestValue() { - return (calcDigestValue == null ? null - : (byte[]) calcDigestValue.clone()); + return (calcDigestValue == null ? null + : (byte[])calcDigestValue.clone()); } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Marshalling Reference"); + throws MarshalException + { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Marshalling Reference"); } Document ownerDoc = DOMUtils.getOwnerDocument(parent); - refElem = DOMUtils.createElement - (ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix); + refElem = DOMUtils.createElement(ownerDoc, "Reference", + XMLSignature.XMLNS, dsPrefix); // set attributes DOMUtils.setAttributeID(refElem, "Id", id); @@ -302,25 +308,28 @@ // create and append Transforms element if (!allTransforms.isEmpty()) { - Element transformsElem = DOMUtils.createElement - (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix); + Element transformsElem = DOMUtils.createElement(ownerDoc, + "Transforms", + XMLSignature.XMLNS, + dsPrefix); refElem.appendChild(transformsElem); - for (int i = 0, size = allTransforms.size(); i < size; i++) { - DOMStructure transform = - (DOMStructure) allTransforms.get(i); - transform.marshal(transformsElem, dsPrefix, context); + for (Transform transform : allTransforms) { + ((DOMStructure)transform).marshal(transformsElem, + dsPrefix, context); } } // create and append DigestMethod element - ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context); + ((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context); // create and append DigestValue element - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Adding digestValueElem"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Adding digestValueElem"); } - Element digestValueElem = DOMUtils.createElement - (ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix); + Element digestValueElem = DOMUtils.createElement(ownerDoc, + "DigestValue", + XMLSignature.XMLNS, + dsPrefix); if (digestValue != null) { digestValueElem.appendChild (ownerDoc.createTextNode(Base64.encode(digestValue))); @@ -331,8 +340,9 @@ here = refElem.getAttributeNodeNS(null, "URI"); } - public void digest(XMLSignContext signContext) - throws XMLSignatureException { + public void digest(XMLSignContext signContext) + throws XMLSignatureException + { Data data = null; if (appliedTransformData == null) { data = dereference(signContext); @@ -343,8 +353,8 @@ // insert digestValue into DigestValue element String encodedDV = Base64.encode(digestValue); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference object uri = " + uri); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference object uri = " + uri); } Element digestElem = DOMUtils.getLastChildElement(refElem); if (digestElem == null) { @@ -355,13 +365,14 @@ (refElem.getOwnerDocument().createTextNode(encodedDV)); digested = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference digesting completed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference digesting completed"); } } public boolean validate(XMLValidateContext validateContext) - throws XMLSignatureException { + throws XMLSignatureException + { if (validateContext == null) { throw new NullPointerException("validateContext cannot be null"); } @@ -371,11 +382,9 @@ Data data = dereference(validateContext); calcDigestValue = transform(data, validateContext); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Expected digest: " - + Base64.encode(digestValue)); - log.log(Level.FINE, "Actual digest: " - + Base64.encode(calcDigestValue)); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Expected digest: " + Base64.encode(digestValue)); + log.log(java.util.logging.Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue)); } validationStatus = Arrays.equals(digestValue, calcDigestValue); @@ -391,8 +400,9 @@ return dis; } - private Data dereference(XMLCryptoContext context) - throws XMLSignatureException { + private Data dereference(XMLCryptoContext context) + throws XMLSignatureException + { Data data = null; // use user-specified URIDereferencer if specified; otherwise use deflt @@ -402,11 +412,9 @@ } try { data = deref.dereference(this, context); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "URIDereferencer class name: " - + deref.getClass().getName()); - log.log(Level.FINE, "Data class name: " - + data.getClass().getName()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "URIDereferencer class name: " + deref.getClass().getName()); + log.log(java.util.logging.Level.FINE, "Data class name: " + data.getClass().getName()); } } catch (URIReferenceException ure) { throw new XMLSignatureException(ure); @@ -415,13 +423,14 @@ return data; } - private byte[] transform(Data dereferencedData, - XMLCryptoContext context) throws XMLSignatureException { - + private byte[] transform(Data dereferencedData, + XMLCryptoContext context) + throws XMLSignatureException + { if (md == null) { try { md = MessageDigest.getInstance - (((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm()); + (((DOMDigestMethod)digestMethod).getMessageDigestAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -430,28 +439,25 @@ DigesterOutputStream dos; Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference"); - if (cache != null && cache.booleanValue() == true) { + if (cache != null && cache.booleanValue()) { this.derefData = copyDerefData(dereferencedData); dos = new DigesterOutputStream(md, true); } else { dos = new DigesterOutputStream(md); } - OutputStream os = new UnsyncBufferedOutputStream(dos); + OutputStream os = null; Data data = dereferencedData; - for (int i = 0, size = transforms.size(); i < size; i++) { - DOMTransform transform = (DOMTransform) transforms.get(i); - try { + try { + os = new UnsyncBufferedOutputStream(dos); + for (int i = 0, size = transforms.size(); i < size; i++) { + DOMTransform transform = (DOMTransform)transforms.get(i); if (i < size - 1) { data = transform.transform(data, context); } else { data = transform.transform(data, context, os); } - } catch (TransformException te) { - throw new XMLSignatureException(te); } - } - - try { + if (data != null) { XMLSignatureInput xi; // explicitly use C14N 1.1 when generating signature @@ -460,9 +466,9 @@ String c14nalg = CanonicalizationMethod.INCLUSIVE; if (context instanceof XMLSignContext) { if (!c14n11) { - Boolean prop = (Boolean) context.getProperty + Boolean prop = (Boolean)context.getProperty ("com.sun.org.apache.xml.internal.security.useC14N11"); - c14n11 = (prop != null && prop.booleanValue() == true); + c14n11 = (prop != null && prop.booleanValue()); if (c14n11) { c14nalg = "http://www.w3.org/2006/12/xml-c14n11"; } @@ -471,17 +477,20 @@ } } if (data instanceof ApacheData) { - xi = ((ApacheData) data).getXMLSignatureInput(); + xi = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof OctetStreamData) { xi = new XMLSignatureInput (((OctetStreamData)data).getOctetStream()); } else if (data instanceof NodeSetData) { TransformService spi = null; - try { + if (provider == null) { spi = TransformService.getInstance(c14nalg, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance - (c14nalg, "DOM", provider); + } else { + try { + spi = TransformService.getInstance(c14nalg, "DOM", provider); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } } data = spi.transform(data, context); xi = new XMLSignatureInput @@ -491,20 +500,31 @@ } if (context instanceof XMLSignContext && c14n11 && !xi.isOctetStream() && !xi.isOutputStreamSet()) { - DOMTransform t = new DOMTransform - (TransformService.getInstance(c14nalg, "DOM")); + TransformService spi = null; + if (provider == null) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } else { + try { + spi = TransformService.getInstance(c14nalg, "DOM", provider); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } + } + + DOMTransform t = new DOMTransform(spi); Element transformsElem = null; String dsPrefix = DOMUtils.getSignaturePrefix(context); if (allTransforms.isEmpty()) { transformsElem = DOMUtils.createElement( - refElem.getOwnerDocument(), + refElem.getOwnerDocument(), "Transforms", XMLSignature.XMLNS, dsPrefix); - refElem.insertBefore(transformsElem, + refElem.insertBefore(transformsElem, DOMUtils.getFirstChildElement(refElem)); } else { transformsElem = DOMUtils.getFirstChildElement(refElem); } - t.marshal(transformsElem, dsPrefix, (DOMCryptoContext) context); + t.marshal(transformsElem, dsPrefix, + (DOMCryptoContext)context); allTransforms.add(t); xi.updateOutputStream(os, true); } else { @@ -512,12 +532,35 @@ } } os.flush(); - if (cache != null && cache.booleanValue() == true) { + if (cache != null && cache.booleanValue()) { this.dis = dos.getInputStream(); } return dos.getDigestValue(); - } catch (Exception e) { + } catch (NoSuchAlgorithmException e) { + throw new XMLSignatureException(e); + } catch (TransformException e) { + throw new XMLSignatureException(e); + } catch (MarshalException e) { + throw new XMLSignatureException(e); + } catch (IOException e) { throw new XMLSignatureException(e); + } catch (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) { + throw new XMLSignatureException(e); + } finally { + if (os != null) { + try { + os.close(); + } catch (IOException e) { + throw new XMLSignatureException(e); + } + } + if (dos != null) { + try { + dos.close(); + } catch (IOException e) { + throw new XMLSignatureException(e); + } + } } } @@ -525,6 +568,7 @@ return here; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -533,19 +577,41 @@ if (!(o instanceof Reference)) { return false; } - Reference oref = (Reference) o; + Reference oref = (Reference)o; - boolean idsEqual = (id == null ? oref.getId() == null : - id.equals(oref.getId())); - boolean urisEqual = (uri == null ? oref.getURI() == null : - uri.equals(oref.getURI())); - boolean typesEqual = (type == null ? oref.getType() == null : - type.equals(oref.getType())); + boolean idsEqual = (id == null ? oref.getId() == null + : id.equals(oref.getId())); + boolean urisEqual = (uri == null ? oref.getURI() == null + : uri.equals(oref.getURI())); + boolean typesEqual = (type == null ? oref.getType() == null + : type.equals(oref.getType())); boolean digestValuesEqual = Arrays.equals(digestValue, oref.getDigestValue()); - return (digestMethod.equals(oref.getDigestMethod()) && idsEqual && - urisEqual && typesEqual && allTransforms.equals(oref.getTransforms())); + return digestMethod.equals(oref.getDigestMethod()) && idsEqual && + urisEqual && typesEqual && + allTransforms.equals(oref.getTransforms()) && digestValuesEqual; + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (uri != null) { + result = 31 * result + uri.hashCode(); + } + if (type != null) { + result = 31 * result + type.hashCode(); + } + if (digestValue != null) { + result = 31 * result + Arrays.hashCode(digestValue); + } + result = 31 * result + digestMethod.hashCode(); + result = 31 * result + allTransforms.hashCode(); + + return result; } boolean isDigested() { @@ -555,18 +621,17 @@ private static Data copyDerefData(Data dereferencedData) { if (dereferencedData instanceof ApacheData) { // need to make a copy of the Data - ApacheData ad = (ApacheData) dereferencedData; + ApacheData ad = (ApacheData)dereferencedData; XMLSignatureInput xsi = ad.getXMLSignatureInput(); if (xsi.isNodeSet()) { try { - final Set s = xsi.getNodeSet(); + final Set s = xsi.getNodeSet(); return new NodeSetData() { public Iterator iterator() { return s.iterator(); } }; } catch (Exception e) { // log a warning - log.log(Level.WARNING, - "cannot cache dereferenced data: " + e); + log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e); return null; } } else if (xsi.isElement()) { @@ -574,12 +639,12 @@ (xsi.getSubNode(), xsi.isExcludeComments()); } else if (xsi.isOctetStream() || xsi.isByteArray()) { try { - return new OctetStreamData - (xsi.getOctetStream(), xsi.getSourceURI(), xsi.getMIMEType()); + return new OctetStreamData + (xsi.getOctetStream(), xsi.getSourceURI(), + xsi.getMIMEType()); } catch (IOException ioe) { // log a warning - log.log(Level.WARNING, - "cannot cache dereferenced data: " + ioe); + log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe); return null; } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java 2013-06-28 11:34:55.139889579 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java 2013-06-28 11:34:54.959895182 -0400 @@ -2,34 +2,36 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * =========================================================================== + * =========================================================================== * * (C) Copyright IBM Corp. 2003 All Rights Reserved. * * =========================================================================== */ /* - * $Id: DOMRetrievalMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMRetrievalMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -38,6 +40,7 @@ import java.net.URISyntaxException; import java.security.Provider; import java.util.*; + import javax.xml.XMLConstants; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; @@ -50,8 +53,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; -import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; - /** * DOM-based implementation of RetrievalMethod. * @@ -61,13 +62,13 @@ public final class DOMRetrievalMethod extends DOMStructure implements RetrievalMethod, DOMURIReference { - private final List transforms; + private final List transforms; private String uri; private String type; private Attr here; /** - * Creates a DOMRetrievalMethod containing the specified + * Creates a DOMRetrievalMethod containing the specified * URIReference and List of Transforms. * * @param uri the URI @@ -75,32 +76,34 @@ * @param transforms a list of {@link Transform}s. The list is defensively * copied to prevent subsequent modification. May be null * or empty. - * @throws IllegalArgumentException if the format of uri is + * @throws IllegalArgumentException if the format of uri is * invalid, as specified by Reference's URI attribute in the W3C * specification for XML-Signature Syntax and Processing * @throws NullPointerException if uriReference - * is null + * is null * @throws ClassCastException if transforms contains any * entries that are not of type {@link Transform} */ - public DOMRetrievalMethod(String uri, String type, List transforms) { + public DOMRetrievalMethod(String uri, String type, + List transforms) + { if (uri == null) { throw new NullPointerException("uri cannot be null"); } if (transforms == null || transforms.isEmpty()) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { - List transformsCopy = new ArrayList(transforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + this.transforms = Collections.unmodifiableList( + new ArrayList(transforms)); + for (int i = 0, size = this.transforms.size(); i < size; i++) { + if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } - this.transforms = Collections.unmodifiableList(transformsCopy); } this.uri = uri; - if ((uri != null) && (!uri.equals(""))) { + if (!uri.equals("")) { try { new URI(uri); } catch (URISyntaxException e) { @@ -110,27 +113,29 @@ this.type = type; } - + /** * Creates a DOMRetrievalMethod from an element. * * @param rmElem a RetrievalMethod element */ public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // get URI and Type attributes uri = DOMUtils.getAttributeValue(rmElem, "URI"); type = DOMUtils.getAttributeValue(rmElem, "Type"); // get here node here = rmElem.getAttributeNodeNS(null, "URI"); - + boolean secVal = Utils.secureValidation(context); // get Transforms, if specified - List transforms = new ArrayList(); + List transforms = new ArrayList(); Element transformsElem = DOMUtils.getFirstChildElement(rmElem); - + int transformCount = 0; if (transformsElem != null) { Element transformElem = @@ -139,21 +144,17 @@ transforms.add (new DOMTransform(transformElem, context, provider)); transformElem = DOMUtils.getNextSiblingElement(transformElem); - + transformCount++; - if (secVal && - (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) - { - String error = "A maxiumum of " + - DOMReference.MAXIMUM_TRANSFORM_COUNT + - " transforms per Reference are allowed" + - " with secure validation"; + if (secVal && (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) { + String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " " + + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } } } if (transforms.isEmpty()) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { this.transforms = Collections.unmodifiableList(transforms); } @@ -172,11 +173,11 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element rmElem = DOMUtils.createElement - (ownerDoc, "RetrievalMethod", XMLSignature.XMLNS, dsPrefix); + Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod", + XMLSignature.XMLNS, dsPrefix); // add URI and Type attributes DOMUtils.setAttribute(rmElem, "URI", uri); @@ -184,12 +185,14 @@ // add Transforms elements if (!transforms.isEmpty()) { - Element transformsElem = DOMUtils.createElement - (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix); + Element transformsElem = DOMUtils.createElement(ownerDoc, + "Transforms", + XMLSignature.XMLNS, + dsPrefix); rmElem.appendChild(transformsElem); - for (int i = 0, size = transforms.size(); i < size; i++) { - ((DOMTransform) transforms.get(i)).marshal - (transformsElem, dsPrefix, context); + for (Transform transform : transforms) { + ((DOMTransform)transform).marshal(transformsElem, + dsPrefix, context); } } @@ -204,14 +207,14 @@ } public Data dereference(XMLCryptoContext context) - throws URIReferenceException { - + throws URIReferenceException + { if (context == null) { throw new NullPointerException("context cannot be null"); } /* - * If URIDereferencer is specified in context; use it, otherwise use + * If URIDereferencer is specified in context; use it, otherwise use * built-in. */ URIDereferencer deref = context.getURIDereferencer(); @@ -223,9 +226,8 @@ // pass dereferenced data through Transforms try { - for (int i = 0, size = transforms.size(); i < size; i++) { - Transform transform = (Transform) transforms.get(i); - data = ((DOMTransform) transform).transform(data, context); + for (Transform transform : transforms) { + data = ((DOMTransform)transform).transform(data, context); } } catch (Exception e) { throw new URIReferenceException(e); @@ -249,14 +251,13 @@ } public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context) - throws URIReferenceException { - + throws URIReferenceException + { try { - ApacheData data = (ApacheData) dereference(context); + ApacheData data = (ApacheData)dereference(context); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream (data.getXMLSignatureInput().getBytes())); @@ -271,6 +272,7 @@ } } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -278,12 +280,24 @@ if (!(obj instanceof RetrievalMethod)) { return false; } - RetrievalMethod orm = (RetrievalMethod) obj; + RetrievalMethod orm = (RetrievalMethod)obj; - boolean typesEqual = (type == null ? orm.getType() == null : - type.equals(orm.getType())); + boolean typesEqual = (type == null ? orm.getType() == null + : type.equals(orm.getType())); return (uri.equals(orm.getURI()) && transforms.equals(orm.getTransforms()) && typesEqual); } + + @Override + public int hashCode() { + int result = 17; + if (type != null) { + result = 31 * result + type.hashCode(); + } + result = 31 * result + uri.hashCode(); + result = 31 * result + transforms.hashCode(); + + return result; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java 2013-06-28 11:34:55.823868288 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java 2013-06-28 11:34:55.651873642 -0400 @@ -2,44 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; -import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; import java.io.IOException; import java.security.*; import java.security.spec.AlgorithmParameterSpec; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; +import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA; import org.jcp.xml.dsig.internal.SignerOutputStream; /** @@ -47,28 +45,29 @@ * * @author Sean Mullan */ -public abstract class DOMSignatureMethod extends DOMStructure - implements SignatureMethod { +public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { - private static Logger log = - Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private SignatureMethodParameterSpec params; + private Signature signature; + // see RFC 4051 for these algorithm definitions - final static String RSA_SHA256 = + static final String RSA_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; - final static String RSA_SHA384 = + static final String RSA_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; - final static String RSA_SHA512 = + static final String RSA_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; - final static String HMAC_SHA256 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; - final static String HMAC_SHA384 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; - final static String HMAC_SHA512 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; - - private SignatureMethodParameterSpec params; - private Signature signature; + static final String ECDSA_SHA1 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + static final String ECDSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"; + static final String ECDSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; + static final String ECDSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; /** * Creates a DOMSignatureMethod. @@ -77,20 +76,21 @@ * @throws InvalidAlgorithmParameterException if the parameters are not * appropriate for this signature method */ - DOMSignatureMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { - if (params != null && + DOMSignatureMethod(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException + { + if (params != null && !(params instanceof SignatureMethodParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type SignatureMethodParameterSpec"); } - checkParams((SignatureMethodParameterSpec) params); - this.params = (SignatureMethodParameterSpec) params; + checkParams((SignatureMethodParameterSpec)params); + this.params = (SignatureMethodParameterSpec)params; } /** * Creates a DOMSignatureMethod from an element. This ctor - * invokes the abstract {@link #unmarshalParams unmarshalParams} method to + * invokes the {@link #unmarshalParams unmarshalParams} method to * unmarshal any algorithm-specific input parameters. * * @param smElem a SignatureMethod element @@ -119,13 +119,21 @@ return new SHA512withRSA(smElem); } else if (alg.equals(SignatureMethod.DSA_SHA1)) { return new SHA1withDSA(smElem); + } else if (alg.equals(ECDSA_SHA1)) { + return new SHA1withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA256)) { + return new SHA256withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA384)) { + return new SHA384withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA512)) { + return new SHA512withECDSA(smElem); } else if (alg.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(smElem); - } else if (alg.equals(HMAC_SHA256)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(smElem); - } else if (alg.equals(HMAC_SHA384)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(smElem); - } else if (alg.equals(HMAC_SHA512)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(smElem); } else { throw new MarshalException @@ -133,86 +141,14 @@ } } - /** - * Checks if the specified parameters are valid for this algorithm. By - * default, this method throws an exception if parameters are specified - * since most SignatureMethod algorithms do not have parameters. Subclasses - * should override it if they have parameters. - * - * @param params the algorithm-specific params (may be null) - * @throws InvalidAlgorithmParameterException if the parameters are not - * appropriate for this signature method - */ - void checkParams(SignatureMethodParameterSpec params) - throws InvalidAlgorithmParameterException { - if (params != null) { - throw new InvalidAlgorithmParameterException("no parameters " + - "should be specified for the " + getSignatureAlgorithm() - + " SignatureMethod algorithm"); - } - } - public final AlgorithmParameterSpec getParameterSpec() { return params; } - /** - * Unmarshals SignatureMethodParameterSpec from the specified - * Element. By default, this method throws an exception since - * most SignatureMethod algorithms do not have parameters. Subclasses should - * override it if they have parameters. - * - * @param paramsElem the Element holding the input params - * @return the algorithm-specific SignatureMethodParameterSpec - * @throws MarshalException if the parameters cannot be unmarshalled - */ - SignatureMethodParameterSpec - unmarshalParams(Element paramsElem) throws MarshalException { - throw new MarshalException("no parameters should " + - "be specified for the " + getSignatureAlgorithm() + - " SignatureMethod algorithm"); - } - - /** - * This method invokes the abstract {@link #marshalParams marshalParams} - * method to marshal any algorithm-specific parameters. - */ - public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { - Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element smElem = DOMUtils.createElement - (ownerDoc, "SignatureMethod", XMLSignature.XMLNS, dsPrefix); - DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm()); - - if (params != null) { - marshalParams(smElem, dsPrefix); - } - - parent.appendChild(smElem); - } - - /** - * Verifies the passed-in signature with the specified key, using the - * underlying signature or MAC algorithm. - * - * @param key the verification key - * @param si the DOMSignedInfo - * @param signature the signature bytes to be verified - * @param context the XMLValidateContext - * @return true if the signature verified successfully, - * false if not - * @throws NullPointerException if key, si or - * signature are null - * @throws InvalidKeyException if the key is improperly encoded, of - * the wrong type, or parameters are missing, etc - * @throws SignatureException if an unexpected error occurs, such - * as the passed in signature is improperly encoded - * @throws XMLSignatureException if an unexpected error occurs - */ - boolean verify(Key key, DOMSignedInfo si, byte[] sig, - XMLValidateContext context) throws InvalidKeyException, - SignatureException, XMLSignatureException { + boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException + { if (key == null || si == null || sig == null) { throw new NullPointerException(); } @@ -222,49 +158,40 @@ } if (signature == null) { try { - Provider p = (Provider) context.getProperty + Provider p = (Provider)context.getProperty ("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) - ? Signature.getInstance(getSignatureAlgorithm()) - : Signature.getInstance(getSignatureAlgorithm(), p); + ? Signature.getInstance(getJCAAlgorithm()) + : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } - signature.initVerify((PublicKey) key); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Signature provider:"+ signature.getProvider()); - log.log(Level.FINE, "verifying with key: " + key); + signature.initVerify((PublicKey)key); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider()); + log.log(java.util.logging.Level.FINE, "verifying with key: " + key); } - si.canonicalize(context, new SignerOutputStream(signature)); + ((DOMSignedInfo)si).canonicalize(context, + new SignerOutputStream(signature)); - if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) { - try { + try { + Type type = getAlgorithmType(); + if (type == Type.DSA) { return signature.verify(convertXMLDSIGtoASN1(sig)); - } catch (IOException ioe) { - throw new XMLSignatureException(ioe); + } else if (type == Type.ECDSA) { + return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig)); + } else { + return signature.verify(sig); } - } else { - return signature.verify(sig); + } catch (IOException ioe) { + throw new XMLSignatureException(ioe); } } - /** - * Signs the bytes with the specified key, using the underlying - * signature or MAC algorithm. - * - * @param key the signing key - * @param si the DOMSignedInfo - * @param context the XMLSignContext - * @return the signature - * @throws NullPointerException if key or - * si are null - * @throws InvalidKeyException if the key is improperly encoded, of - * the wrong type, or parameters are missing, etc - * @throws XMLSignatureException if an unexpected error occurs - */ - byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context) - throws InvalidKeyException, XMLSignatureException { + byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException + { if (key == null || si == null) { throw new NullPointerException(); } @@ -274,26 +201,30 @@ } if (signature == null) { try { - Provider p = (Provider) context.getProperty + Provider p = (Provider)context.getProperty ("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) - ? Signature.getInstance(getSignatureAlgorithm()) - : Signature.getInstance(getSignatureAlgorithm(), p); + ? Signature.getInstance(getJCAAlgorithm()) + : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } - signature.initSign((PrivateKey) key); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Signature provider:" +signature.getProvider()); - log.log(Level.FINE, "Signing with key: " + key); + signature.initSign((PrivateKey)key); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider()); + log.log(java.util.logging.Level.FINE, "Signing with key: " + key); } - si.canonicalize(context, new SignerOutputStream(signature)); + ((DOMSignedInfo)si).canonicalize(context, + new SignerOutputStream(signature)); try { - if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) { + Type type = getAlgorithmType(); + if (type == Type.DSA) { return convertASN1toXMLDSIG(signature.sign()); + } else if (type == Type.ECDSA) { + return SignatureECDSA.convertASN1toXMLDSIG(signature.sign()); } else { return signature.sign(); } @@ -305,52 +236,6 @@ } /** - * Marshals the algorithm-specific parameters to an Element and - * appends it to the specified parent element. By default, this method - * throws an exception since most SignatureMethod algorithms do not have - * parameters. Subclasses should override it if they have parameters. - * - * @param parent the parent element to append the parameters to - * @param paramsPrefix the algorithm parameters prefix to use - * @throws MarshalException if the parameters cannot be marshalled - */ - void marshalParams(Element parent, String paramsPrefix) - throws MarshalException { - throw new MarshalException("no parameters should " + - "be specified for the " + getSignatureAlgorithm() + - " SignatureMethod algorithm"); - } - - /** - * Returns the java.security.Signature standard algorithm name. - */ - abstract String getSignatureAlgorithm(); - - /** - * Returns true if parameters are equal; false otherwise. - * - * Subclasses should override this method to compare algorithm-specific - * parameters. - */ - boolean paramsEqual(AlgorithmParameterSpec spec) { - return (getParameterSpec() == spec); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof SignatureMethod)) { - return false; - } - SignatureMethod osm = (SignatureMethod) o; - - return (getAlgorithm().equals(osm.getAlgorithm()) && - paramsEqual(osm.getParameterSpec())); - } - - /** * Converts an ASN.1 DSA value to a XML Signature DSA Value. * * The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value @@ -362,8 +247,8 @@ * @see 6.4.1 DSA */ private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { - + throws IOException + { byte rLength = asn1Bytes[3]; int i; @@ -384,7 +269,7 @@ System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i); System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes, - 40 - j, j); + 40 - j, j); return xmldsigBytes; } @@ -402,8 +287,8 @@ * @see 6.4.1 DSA */ private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - + throws IOException + { if (xmldsigBytes.length != 40) { throw new IOException("Invalid XMLDSIG format of DSA signature"); } @@ -431,9 +316,9 @@ byte asn1Bytes[] = new byte[6 + j + l]; asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); + asn1Bytes[1] = (byte)(4 + j + l); asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; + asn1Bytes[3] = (byte)j; System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i); @@ -456,9 +341,12 @@ public String getAlgorithm() { return SignatureMethod.RSA_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA1withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA256withRSA extends DOMSignatureMethod { @@ -472,9 +360,12 @@ public String getAlgorithm() { return RSA_SHA256; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA256withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA384withRSA extends DOMSignatureMethod { @@ -488,9 +379,12 @@ public String getAlgorithm() { return RSA_SHA384; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA384withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA512withRSA extends DOMSignatureMethod { @@ -504,9 +398,12 @@ public String getAlgorithm() { return RSA_SHA512; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA512withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA1withDSA extends DOMSignatureMethod { @@ -520,8 +417,87 @@ public String getAlgorithm() { return SignatureMethod.DSA_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA1withDSA"; } + Type getAlgorithmType() { + return Type.DSA; + } + } + + static final class SHA1withECDSA extends DOMSignatureMethod { + SHA1withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA1withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA1; + } + String getJCAAlgorithm() { + return "SHA1withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA256withECDSA extends DOMSignatureMethod { + SHA256withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA256withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA256; + } + String getJCAAlgorithm() { + return "SHA256withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA384withECDSA extends DOMSignatureMethod { + SHA384withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA384withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA384; + } + String getJCAAlgorithm() { + return "SHA384withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA512withECDSA extends DOMSignatureMethod { + SHA512withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA512withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA512; + } + String getJCAAlgorithm() { + return "SHA512withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java 2013-06-28 11:34:56.531846251 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java 2013-06-28 11:34:56.359851605 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureProperties.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureProperties.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,6 +33,7 @@ import javax.xml.crypto.dsig.*; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -42,17 +45,17 @@ * * @author Sean Mullan */ -public final class DOMSignatureProperties extends DOMStructure +public final class DOMSignatureProperties extends DOMStructure implements SignatureProperties { - + private final String id; - private final List properties; + private final List properties; /** - * Creates a DOMSignatureProperties from the specified + * Creates a DOMSignatureProperties from the specified * parameters. * - * @param properties a list of one or more {@link SignatureProperty}s. The + * @param properties a list of one or more {@link SignatureProperty}s. The * list is defensively copied to protect against subsequent modification. * @param id the Id (may be null) * @return a DOMSignatureProperties @@ -61,20 +64,22 @@ * @throws IllegalArgumentException if properties is empty * @throws NullPointerException if properties */ - public DOMSignatureProperties(List properties, String id) { + public DOMSignatureProperties(List properties, + String id) + { if (properties == null) { throw new NullPointerException("properties cannot be null"); } else if (properties.isEmpty()) { throw new IllegalArgumentException("properties cannot be empty"); } else { - List propsCopy = new ArrayList(properties); - for (int i = 0, size = propsCopy.size(); i < size; i++) { - if (!(propsCopy.get(i) instanceof SignatureProperty)) { + this.properties = Collections.unmodifiableList( + new ArrayList(properties)); + for (int i = 0, size = this.properties.size(); i < size; i++) { + if (!(this.properties.get(i) instanceof SignatureProperty)) { throw new ClassCastException ("properties["+i+"] is not a valid type"); } } - this.properties = Collections.unmodifiableList(propsCopy); } this.id = id; } @@ -85,7 +90,9 @@ * @param propsElem a SignatureProperties element * @throws MarshalException if a marshalling error occurs */ - public DOMSignatureProperties(Element propsElem) throws MarshalException{ + public DOMSignatureProperties(Element propsElem, XMLCryptoContext context) + throws MarshalException + { // unmarshal attributes Attr attr = propsElem.getAttributeNodeNS(null, "Id"); if (attr != null) { @@ -97,11 +104,13 @@ NodeList nodes = propsElem.getChildNodes(); int length = nodes.getLength(); - List properties = new ArrayList(length); + List properties = + new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { - properties.add(new DOMSignatureProperty((Element) child)); + properties.add(new DOMSignatureProperty((Element)child, + context)); } } if (properties.isEmpty()) { @@ -120,25 +129,27 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element propsElem = DOMUtils.createElement - (ownerDoc, "SignatureProperties", XMLSignature.XMLNS, dsPrefix); + Element propsElem = DOMUtils.createElement(ownerDoc, + "SignatureProperties", + XMLSignature.XMLNS, + dsPrefix); // set attributes DOMUtils.setAttributeID(propsElem, "Id", id); // create and append any properties - for (int i = 0, size = properties.size(); i < size; i++) { - DOMSignatureProperty property = - (DOMSignatureProperty) properties.get(i); - property.marshal(propsElem, dsPrefix, context); + for (SignatureProperty property : properties) { + ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix, + context); } - + parent.appendChild(propsElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -147,11 +158,22 @@ if (!(o instanceof SignatureProperties)) { return false; } - SignatureProperties osp = (SignatureProperties) o; + SignatureProperties osp = (SignatureProperties)o; - boolean idsEqual = (id == null ? osp.getId() == null : - id.equals(osp.getId())); + boolean idsEqual = (id == null ? osp.getId() == null + : id.equals(osp.getId())); return (properties.equals(osp.getProperties()) && idsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + properties.hashCode(); + + return result; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java 2013-06-28 11:34:57.219824835 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java 2013-06-28 11:34:57.047830190 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureProperty.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureProperty.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,6 +33,7 @@ import javax.xml.crypto.dsig.*; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -42,12 +45,12 @@ * * @author Sean Mullan */ -public final class DOMSignatureProperty extends DOMStructure +public final class DOMSignatureProperty extends DOMStructure implements SignatureProperty { - + private final String id; private final String target; - private final List content; + private final List content; /** * Creates a SignatureProperty from the specified parameters. @@ -60,10 +63,12 @@ * @throws ClassCastException if content contains any * entries that are not of type {@link XMLStructure} * @throws IllegalArgumentException if content is empty - * @throws NullPointerException if content or + * @throws NullPointerException if content or * target is null */ - public DOMSignatureProperty(List content, String target, String id) { + public DOMSignatureProperty(List content, + String target, String id) + { if (target == null) { throw new NullPointerException("target cannot be null"); } else if (content == null) { @@ -71,14 +76,14 @@ } else if (content.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } else { - List contentCopy = new ArrayList(content); - for (int i = 0, size = contentCopy.size(); i < size; i++) { - if (!(contentCopy.get(i) instanceof XMLStructure)) { + this.content = Collections.unmodifiableList( + new ArrayList(content)); + for (int i = 0, size = this.content.size(); i < size; i++) { + if (!(this.content.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid type"); } } - this.content = Collections.unmodifiableList(contentCopy); } this.target = target; this.id = id; @@ -89,7 +94,9 @@ * * @param propElem a SignatureProperty element */ - public DOMSignatureProperty(Element propElem) throws MarshalException { + public DOMSignatureProperty(Element propElem, XMLCryptoContext context) + throws MarshalException + { // unmarshal attributes target = DOMUtils.getAttributeValue(propElem, "Target"); if (target == null) { @@ -105,7 +112,7 @@ NodeList nodes = propElem.getChildNodes(); int length = nodes.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { content.add(new javax.xml.crypto.dom.DOMStructure(nodes.item(i))); } @@ -129,26 +136,26 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element propElem = DOMUtils.createElement - (ownerDoc, "SignatureProperty", XMLSignature.XMLNS, dsPrefix); + Element propElem = DOMUtils.createElement(ownerDoc, "SignatureProperty", + XMLSignature.XMLNS, dsPrefix); // set attributes DOMUtils.setAttributeID(propElem, "Id", id); DOMUtils.setAttribute(propElem, "Target", target); // create and append any elements and mixed content - for (int i = 0, size = content.size(); i < size; i++) { - javax.xml.crypto.dom.DOMStructure property = - (javax.xml.crypto.dom.DOMStructure) content.get(i); - DOMUtils.appendChild(propElem, property.getNode()); + for (XMLStructure property : content) { + DOMUtils.appendChild(propElem, + ((javax.xml.crypto.dom.DOMStructure)property).getNode()); } - + parent.appendChild(propElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -157,31 +164,43 @@ if (!(o instanceof SignatureProperty)) { return false; } - SignatureProperty osp = (SignatureProperty) o; + SignatureProperty osp = (SignatureProperty)o; + + boolean idsEqual = (id == null ? osp.getId() == null + : id.equals(osp.getId())); - boolean idsEqual = (id == null ? osp.getId() == null : - id.equals(osp.getId())); + @SuppressWarnings("unchecked") + List ospContent = osp.getContent(); + return (equalsContent(ospContent) && + target.equals(osp.getTarget()) && idsEqual); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + target.hashCode(); + result = 31 * result + content.hashCode(); - return (equalsContent(osp.getContent()) && - target.equals(osp.getTarget()) && idsEqual); + return result; } - private boolean equalsContent(List otherContent) { + private boolean equalsContent(List otherContent) { int osize = otherContent.size(); if (content.size() != osize) { return false; } for (int i = 0; i < osize; i++) { - XMLStructure oxs = (XMLStructure) otherContent.get(i); - XMLStructure xs = (XMLStructure) content.get(i); + XMLStructure oxs = otherContent.get(i); + XMLStructure xs = content.get(i); if (oxs instanceof javax.xml.crypto.dom.DOMStructure) { if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) { return false; } - Node onode = - ((javax.xml.crypto.dom.DOMStructure) oxs).getNode(); - Node node = - ((javax.xml.crypto.dom.DOMStructure) xs).getNode(); + Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode(); + Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode(); if (!DOMUtils.nodesEqual(node, onode)) { return false; } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java 2013-06-28 11:34:57.915803172 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java 2013-06-28 11:34:57.743808525 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignedInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -33,13 +35,11 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; -import java.io.IOException; -import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.IOException; import java.security.Provider; import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; + import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -47,7 +47,6 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; -import com.sun.org.apache.xml.internal.security.utils.XMLUtils; /** * DOM-based implementation of SignedInfo. @@ -55,24 +54,24 @@ * @author Sean Mullan */ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { - + /** - * The maximum number of references per Manifest, if secure validation is - * enabled. + * The maximum number of references per Manifest, if secure validation is enabled. */ public static final int MAXIMUM_REFERENCE_COUNT = 30; - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); - + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + /** Signature - NOT Recommended RSAwithMD5 */ - private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = + private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = Constants.MoreAlgorithmsSpecNS + "rsa-md5"; - + /** HMAC - NOT Recommended HMAC-MD5 */ - private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = + private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5"; - - private List references; + + private List references; private CanonicalizationMethod canonicalizationMethod; private SignatureMethod signatureMethod; private String id; @@ -88,21 +87,21 @@ * @param sm the signature method * @param references the list of references. The list is copied. * @throws NullPointerException if - * cm, sm, or references is + * cm, sm, or references is * null * @throws IllegalArgumentException if references is empty * @throws ClassCastException if any of the references are not of * type Reference */ public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, - List references) { + List references) { if (cm == null || sm == null || references == null) { throw new NullPointerException(); } this.canonicalizationMethod = cm; this.signatureMethod = sm; - this.references = Collections.unmodifiableList - (new ArrayList(references)); + this.references = Collections.unmodifiableList( + new ArrayList(references)); if (this.references.isEmpty()) { throw new IllegalArgumentException("list of references must " + "contain at least one entry"); @@ -131,8 +130,8 @@ * @throws ClassCastException if any of the references are not of * type Reference */ - public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, - List references, String id) { + public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, + List references, String id) { this(cm, sm, references); this.id = id; } @@ -142,8 +141,8 @@ * * @param siElem a SignedInfo element */ - public DOMSignedInfo(Element siElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + public DOMSignedInfo(Element siElem, XMLCryptoContext context, Provider provider) + throws MarshalException { localSiElem = siElem; ownerDoc = siElem.getOwnerDocument(); @@ -152,36 +151,35 @@ // unmarshal CanonicalizationMethod Element cmElem = DOMUtils.getFirstChildElement(siElem); - canonicalizationMethod = new DOMCanonicalizationMethod - (cmElem, context, provider); + canonicalizationMethod = new DOMCanonicalizationMethod(cmElem, context, provider); // unmarshal SignatureMethod Element smElem = DOMUtils.getNextSiblingElement(cmElem); signatureMethod = DOMSignatureMethod.unmarshal(smElem); - + boolean secVal = Utils.secureValidation(context); - String sigMethAlg = signatureMethod.getAlgorithm(); - if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(sigMethAlg) - || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(sigMethAlg)))) - { - throw new MarshalException("It is forbidden to use algorithm " + - signatureMethod + - " when secure validation is enabled"); - } + String signatureMethodAlgorithm = signatureMethod.getAlgorithm(); + if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(signatureMethodAlgorithm) + || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(signatureMethodAlgorithm)))) { + throw new MarshalException( + "It is forbidden to use algorithm " + signatureMethod + " when secure validation is enabled" + ); + } + // unmarshal References - ArrayList refList = new ArrayList(5); + ArrayList refList = new ArrayList(5); Element refElem = DOMUtils.getNextSiblingElement(smElem); + int refCount = 0; while (refElem != null) { refList.add(new DOMReference(refElem, context, provider)); refElem = DOMUtils.getNextSiblingElement(refElem); - + refCount++; if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) { - String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + - " references per SignedInfo are allowed with" + - " secure validation"; + String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " " + + "references per Manifest are allowed with secure validation"; throw new MarshalException(error); } } @@ -208,9 +206,8 @@ return canonData; } - public void canonicalize(XMLCryptoContext context,ByteArrayOutputStream bos) + public void canonicalize(XMLCryptoContext context, ByteArrayOutputStream bos) throws XMLSignatureException { - if (context == null) { throw new NullPointerException("context cannot be null"); } @@ -219,14 +216,17 @@ try { os.close(); } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } // Impossible } DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true); try { - Data data = ((DOMCanonicalizationMethod) - canonicalizationMethod).canonicalize(subTree, context, os); + ((DOMCanonicalizationMethod) + canonicalizationMethod).canonicalize(subTree, context, bos); } catch (TransformException te) { throw new XMLSignatureException(te); } @@ -234,53 +234,47 @@ byte[] signedInfoBytes = bos.toByteArray(); // this whole block should only be done if logging is enabled - if (log.isLoggable(Level.FINE)) { - InputStreamReader isr = new InputStreamReader - (new ByteArrayInputStream(signedInfoBytes)); - char[] siBytes = new char[signedInfoBytes.length]; - try { - isr.read(siBytes); - log.log(Level.FINE, "Canonicalized SignedInfo:\n" - + new String(siBytes)); - } catch (IOException ioex) { - log.log(Level.FINE, "IOException reading SignedInfo bytes"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); + StringBuilder sb = new StringBuilder(signedInfoBytes.length); + for (int i = 0; i < signedInfoBytes.length; i++) { + sb.append((char)signedInfoBytes[i]); } - log.log(Level.FINE, "Data to be signed/verified:" - + Base64.encode(signedInfoBytes)); + log.log(java.util.logging.Level.FINE, sb.toString()); + log.log(java.util.logging.Level.FINE, "Data to be signed/verified:" + Base64.encode(signedInfoBytes)); } this.canonData = new ByteArrayInputStream(signedInfoBytes); } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element siElem = DOMUtils.createElement - (ownerDoc, "SignedInfo", XMLSignature.XMLNS, dsPrefix); + Element siElem = DOMUtils.createElement(ownerDoc, "SignedInfo", + XMLSignature.XMLNS, dsPrefix); // create and append CanonicalizationMethod element DOMCanonicalizationMethod dcm = - (DOMCanonicalizationMethod) canonicalizationMethod; - dcm.marshal(siElem, dsPrefix, context); + (DOMCanonicalizationMethod)canonicalizationMethod; + dcm.marshal(siElem, dsPrefix, context); // create and append SignatureMethod element - ((DOMSignatureMethod) signatureMethod).marshal - (siElem, dsPrefix, context); + ((DOMStructure)signatureMethod).marshal(siElem, dsPrefix, context); // create and append Reference elements - for (int i = 0, size = references.size(); i < size; i++) { - DOMReference reference = (DOMReference) references.get(i); - reference.marshal(siElem, dsPrefix, context); + for (Reference reference : references) { + ((DOMReference)reference).marshal(siElem, dsPrefix, context); } // append Id attribute DOMUtils.setAttributeID(siElem, "Id", id); - + parent.appendChild(siElem); localSiElem = siElem; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -289,13 +283,26 @@ if (!(o instanceof SignedInfo)) { return false; } - SignedInfo osi = (SignedInfo) o; + SignedInfo osi = (SignedInfo)o; - boolean idEqual = (id == null ? osi.getId() == null : - id.equals(osi.getId())); + boolean idEqual = (id == null ? osi.getId() == null + : id.equals(osi.getId())); - return (canonicalizationMethod.equals(osi.getCanonicalizationMethod()) - && signatureMethod.equals(osi.getSignatureMethod()) && - references.equals(osi.getReferences()) && idEqual); + return (canonicalizationMethod.equals(osi.getCanonicalizationMethod()) + && signatureMethod.equals(osi.getSignatureMethod()) && + references.equals(osi.getReferences()) && idEqual); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + canonicalizationMethod.hashCode(); + result = 31 * result + signatureMethod.hashCode(); + result = 31 * result + references.hashCode(); + + return result; } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java 2013-06-28 11:34:58.603781757 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java 2013-06-28 11:34:58.435786986 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMStructure.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMStructure.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -46,6 +48,6 @@ } } - public abstract void marshal(Node parent, String dsPrefix, + public abstract void marshal(Node parent, String dsPrefix, DOMCryptoContext context) throws MarshalException; } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java 2013-06-28 11:34:59.255761462 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java 2013-06-28 11:34:59.079766940 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2006 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSubTreeData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id$ */ package org.jcp.xml.dsig.internal.dom; @@ -45,17 +47,15 @@ public class DOMSubTreeData implements NodeSetData { private boolean excludeComments; - private Iterator ni; private Node root; public DOMSubTreeData(Node root, boolean excludeComments) { this.root = root; - this.ni = new DelayedNodeIterator(root, excludeComments); this.excludeComments = excludeComments; } public Iterator iterator() { - return ni; + return new DelayedNodeIterator(root, excludeComments); } public Node getRoot() { @@ -70,10 +70,10 @@ * This is an Iterator that contains a backing node-set that is * not populated until the caller first attempts to advance the iterator. */ - static class DelayedNodeIterator implements Iterator { + static class DelayedNodeIterator implements Iterator { private Node root; - private List nodeSet; - private ListIterator li; + private List nodeSet; + private ListIterator li; private boolean withComments; DelayedNodeIterator(Node root, boolean excludeComments) { @@ -89,13 +89,13 @@ return li.hasNext(); } - public Object next() { + public Node next() { if (nodeSet == null) { nodeSet = dereferenceSameDocumentURI(root); li = nodeSet.listIterator(); } if (li.hasNext()) { - return (Node) li.next(); + return li.next(); } else { throw new NoSuchElementException(); } @@ -109,11 +109,11 @@ * Dereferences a same-document URI fragment. * * @param node the node (document or element) referenced by the - * URI fragment. If null, returns an empty set. + * URI fragment. If null, returns an empty set. * @return a set of nodes (minus any comment nodes) */ - private List dereferenceSameDocumentURI(Node node) { - List nodeSet = new ArrayList(); + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); if (node != null) { nodeSetMinusCommentNodes(node, nodeSet, null); } @@ -129,8 +129,10 @@ * @param nodeSet the set of nodes traversed so far * @param the previous sibling node */ - private void nodeSetMinusCommentNodes(Node node, List nodeSet, - Node prevSibling) { + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { switch (node.getNodeType()) { case Node.ELEMENT_NODE : NamedNodeMap attrs = node.getAttributes(); @@ -140,7 +142,6 @@ } } nodeSet.add(node); - case Node.DOCUMENT_NODE : Node pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { @@ -148,19 +149,30 @@ pSibling = child; } break; + case Node.DOCUMENT_NODE : + pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; case Node.TEXT_NODE : case Node.CDATA_SECTION_NODE: // emulate XPath which only returns the first node in // contiguous text/cdata nodes if (prevSibling != null && (prevSibling.getNodeType() == Node.TEXT_NODE || - prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)){ return; + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; } + nodeSet.add(node); + break; case Node.PROCESSING_INSTRUCTION_NODE : nodeSet.add(node); break; case Node.COMMENT_NODE: - if (withComments) { + if (withComments) { nodeSet.add(node); } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java 2013-06-28 11:34:59.931740420 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java 2013-06-28 11:34:59.763745650 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMTransform.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -35,13 +37,11 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import org.w3c.dom.NodeList; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.dom.DOMSignContext; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; /** * DOM-based abstract implementation of Transform. @@ -69,15 +69,26 @@ * @param transElem a Transform element */ public DOMTransform(Element transElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm"); - try { - spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException e1) { + + if (provider == null) { + try { + spi = TransformService.getInstance(algorithm, "DOM"); + } catch (NoSuchAlgorithmException e1) { + throw new MarshalException(e1); + } + } else { try { spi = TransformService.getInstance(algorithm, "DOM", provider); - } catch (NoSuchAlgorithmException e2) { - throw new MarshalException(e2); + } catch (NoSuchAlgorithmException nsae) { + try { + spi = TransformService.getInstance(algorithm, "DOM"); + } catch (NoSuchAlgorithmException e2) { + throw new MarshalException(e2); + } } } try { @@ -96,25 +107,29 @@ } /** - * This method invokes the abstract {@link #marshalParams marshalParams} + * This method invokes the abstract {@link #marshalParams marshalParams} * method to marshal any algorithm-specific parameters. */ public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element transformElem = null; if (parent.getLocalName().equals("Transforms")) { - transformElem = DOMUtils.createElement - (ownerDoc, "Transform", XMLSignature.XMLNS, dsPrefix); + transformElem = DOMUtils.createElement(ownerDoc, "Transform", + XMLSignature.XMLNS, + dsPrefix); } else { - transformElem = DOMUtils.createElement - (ownerDoc, "CanonicalizationMethod", XMLSignature.XMLNS, dsPrefix); + transformElem = DOMUtils.createElement(ownerDoc, + "CanonicalizationMethod", + XMLSignature.XMLNS, + dsPrefix); } DOMUtils.setAttribute(transformElem, "Algorithm", getAlgorithm()); - spi.marshalParams - (new javax.xml.crypto.dom.DOMStructure(transformElem), context); + spi.marshalParams(new javax.xml.crypto.dom.DOMStructure(transformElem), + context); parent.appendChild(transformElem); } @@ -131,7 +146,8 @@ * executing the transform */ public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return spi.transform(data, xc); } @@ -149,10 +165,12 @@ * executing the transform */ public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { return spi.transform(data, xc, os); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -161,13 +179,25 @@ if (!(o instanceof Transform)) { return false; } - Transform otransform = (Transform) o; + Transform otransform = (Transform)o; return (getAlgorithm().equals(otransform.getAlgorithm()) && - DOMUtils.paramsEqual - (getParameterSpec(), otransform.getParameterSpec())); + DOMUtils.paramsEqual(getParameterSpec(), + otransform.getParameterSpec())); } + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + /** * Transforms the specified data using the underlying transform algorithm. * This method invokes the {@link #marshal marshal} method and passes it @@ -179,15 +209,16 @@ * @param context the marshalling context * @return the transformed data * @throws MarshalException if an exception occurs while marshalling - * @throws NullPointerException if data or context + * @throws NullPointerException if data or context * is null * @throws XMLSignatureException if an unexpected error occurs while * executing the transform */ Data transform(Data data, XMLCryptoContext xc, DOMSignContext context) - throws MarshalException, TransformException { + throws MarshalException, TransformException + { marshal(context.getParent(), - DOMUtils.getSignaturePrefix(context), context); + DOMUtils.getSignaturePrefix(context), context); return transform(data, xc); } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java 2013-06-28 11:35:00.591719877 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java 2013-06-28 11:35:00.419725231 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMURIDereferencer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -37,7 +39,6 @@ import javax.xml.crypto.*; import javax.xml.crypto.dom.*; -import javax.xml.crypto.dsig.*; /** * DOM-based implementation of URIDereferencer. @@ -45,11 +46,11 @@ * @author Sean Mullan */ public class DOMURIDereferencer implements URIDereferencer { - + static final URIDereferencer INSTANCE = new DOMURIDereferencer(); private DOMURIDereferencer() { - // need to call com.sun.org.apache.xml.internal.security.Init.init() + // need to call com.sun.org.apache.xml.internal.security.Init.init() // before calling any apache security code Init.init(); } @@ -69,9 +70,9 @@ String uri = uriRef.getURI(); DOMCryptoContext dcc = (DOMCryptoContext) context; String baseURI = context.getBaseURI(); - + boolean secVal = Utils.secureValidation(context); - + // Check if same-document URI and already registered on the context if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') { String id = uri.substring(1); @@ -82,37 +83,33 @@ id = id.substring(i1+1, i2); } - Node refElem = dcc.getElementById(id); - if (refElem != null) { + Node referencedElem = dcc.getElementById(id); + if (referencedElem != null) { if (secVal) { - Element start = - refElem.getOwnerDocument().getDocumentElement(); - if (!XMLUtils.protectAgainstWrappingAttack(start, - (Element)refElem, - id)) { - String error = "Multiple Elements with the same ID " + - id + " were detected"; + Element start = referencedElem.getOwnerDocument().getDocumentElement(); + if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) { + String error = "Multiple Elements with the same ID " + id + " were detected"; throw new URIReferenceException(error); } } - - XMLSignatureInput result = new XMLSignatureInput(refElem); + + XMLSignatureInput result = new XMLSignatureInput(referencedElem); if (!uri.substring(1).startsWith("xpointer(id(")) { result.setExcludeComments(true); } result.setMIMEType("text/xml"); if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uriAttr.getNodeValue())); + result.setSourceURI(baseURI.concat(uriAttr.getNodeValue())); } else { - result.setSourceURI(uriAttr.getNodeValue()); + result.setSourceURI(uriAttr.getNodeValue()); } return new ApacheNodeSetData(result); } - } + } try { - ResourceResolver apacheResolver = + ResourceResolver apacheResolver = ResourceResolver.getInstance(uriAttr, baseURI, secVal); XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI); if (in.isOctetStream()) { --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java 2013-06-28 11:35:01.271698711 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java 2013-06-28 11:35:01.091704314 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMUtils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMUtils.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -34,7 +36,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.*; @@ -46,7 +47,7 @@ public class DOMUtils { // class cannot be instantiated - private DOMUtils() {} + private DOMUtils() {} /** * Returns the owner document of the specified node. @@ -56,7 +57,7 @@ */ public static Document getOwnerDocument(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; + return (Document)node; } else { return node.getOwnerDocument(); } @@ -72,48 +73,53 @@ * @param prefix the namespace prefix * @return the newly created element */ - public static Element createElement(Document doc, String tag, String nsURI, - String prefix) { + public static Element createElement(Document doc, String tag, + String nsURI, String prefix) + { String qName = (prefix == null || prefix.length() == 0) ? tag : prefix + ":" + tag; return doc.createElementNS(nsURI, qName); } /** - * Sets an element's attribute (using DOM level 2) with the + * Sets an element's attribute (using DOM level 2) with the * specified value and namespace prefix. * * @param elem the element to set the attribute on * @param name the name of the attribute - * @param value the attribute value. If null, no attribute is set. + * @param value the attribute value. If null, no attribute is set. */ public static void setAttribute(Element elem, String name, String value) { - if (value == null) return; + if (value == null) { + return; + } elem.setAttributeNS(null, name, value); } /** - * Sets an element's attribute (using DOM level 2) with the + * Sets an element's attribute (using DOM level 2) with the * specified value and namespace prefix AND registers the ID value with * the specified element. This is for resolving same-document * ID references. * * @param elem the element to set the attribute on * @param name the name of the attribute - * @param value the attribute value. If null, no attribute is set. + * @param value the attribute value. If null, no attribute is set. */ public static void setAttributeID(Element elem, String name, String value) { - if (value == null) return; + if (value == null) { + return; + } elem.setAttributeNS(null, name, value); elem.setIdAttributeNS(null, name, true); } /** - * Returns the first child element of the specified node, or null if there + * Returns the first child element of the specified node, or null if there * is no such element. * * @param node the node - * @return the first child element of the specified node, or null if there + * @return the first child element of the specified node, or null if there * is no such element * @throws NullPointerException if node == null */ @@ -122,15 +128,15 @@ while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { child = child.getNextSibling(); } - return (Element) child; + return (Element)child; } /** - * Returns the last child element of the specified node, or null if there + * Returns the last child element of the specified node, or null if there * is no such element. * * @param node the node - * @return the last child element of the specified node, or null if there + * @return the last child element of the specified node, or null if there * is no such element * @throws NullPointerException if node == null */ @@ -139,15 +145,15 @@ while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { child = child.getPreviousSibling(); } - return (Element) child; + return (Element)child; } /** - * Returns the next sibling element of the specified node, or null if there + * Returns the next sibling element of the specified node, or null if there * is no such element. * * @param node the node - * @return the next sibling element of the specified node, or null if there + * @return the next sibling element of the specified node, or null if there * is no such element * @throws NullPointerException if node == null */ @@ -156,12 +162,12 @@ while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) { sibling = sibling.getNextSibling(); } - return (Element) sibling; + return (Element)sibling; } /** * Returns the attribute value for the attribute with the specified name. - * Returns null if there is no such attribute, or + * Returns null if there is no such attribute, or * the empty string if the attribute value is empty. * *

      This works around a limitation of the DOM @@ -179,31 +185,31 @@ } /** - * Returns a Set of Nodes, backed by the specified + * Returns a Set of Nodes, backed by the specified * NodeList. * * @param nl the NodeList * @return a Set of Nodes */ - public static Set nodeSet(NodeList nl) { + public static Set nodeSet(NodeList nl) { return new NodeSet(nl); } - static class NodeSet extends AbstractSet { + static class NodeSet extends AbstractSet { private NodeList nl; public NodeSet(NodeList nl) { this.nl = nl; } public int size() { return nl.getLength(); } - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { int index = 0; public void remove() { throw new UnsupportedOperationException(); } - public Object next() { + public Node next() { if (!hasNext()) { throw new NoSuchElementException(); } @@ -215,7 +221,7 @@ }; } } - + /** * Returns the prefix associated with the specified namespace URI * @@ -243,7 +249,7 @@ public static String getSignaturePrefix(XMLCryptoContext context) { return getNSPrefix(context, XMLSignature.XMLNS); } - + /** * Removes all children nodes from the specified node. * @@ -271,7 +277,7 @@ } /** - * Checks if child element has same owner document before + * Checks if child element has same owner document before * appending to the parent, and imports it to the parent's document * if necessary. */ @@ -291,39 +297,41 @@ } if (spec1 instanceof XPathFilter2ParameterSpec && spec2 instanceof XPathFilter2ParameterSpec) { - return paramsEqual((XPathFilter2ParameterSpec) spec1, - (XPathFilter2ParameterSpec) spec2); + return paramsEqual((XPathFilter2ParameterSpec)spec1, + (XPathFilter2ParameterSpec)spec2); } if (spec1 instanceof ExcC14NParameterSpec && spec2 instanceof ExcC14NParameterSpec) { return paramsEqual((ExcC14NParameterSpec) spec1, - (ExcC14NParameterSpec) spec2); + (ExcC14NParameterSpec)spec2); } if (spec1 instanceof XPathFilterParameterSpec && spec2 instanceof XPathFilterParameterSpec) { - return paramsEqual((XPathFilterParameterSpec) spec1, - (XPathFilterParameterSpec) spec2); + return paramsEqual((XPathFilterParameterSpec)spec1, + (XPathFilterParameterSpec)spec2); } if (spec1 instanceof XSLTTransformParameterSpec && spec2 instanceof XSLTTransformParameterSpec) { - return paramsEqual((XSLTTransformParameterSpec) spec1, - (XSLTTransformParameterSpec) spec2); + return paramsEqual((XSLTTransformParameterSpec)spec1, + (XSLTTransformParameterSpec)spec2); } return false; } private static boolean paramsEqual(XPathFilter2ParameterSpec spec1, - XPathFilter2ParameterSpec spec2) { - - List types = spec1.getXPathList(); - List otypes = spec2.getXPathList(); + XPathFilter2ParameterSpec spec2) + { + @SuppressWarnings("unchecked") + List types = spec1.getXPathList(); + @SuppressWarnings("unchecked") + List otypes = spec2.getXPathList(); int size = types.size(); if (size != otypes.size()) { return false; } for (int i = 0; i < size; i++) { - XPathType type = (XPathType) types.get(i); - XPathType otype = (XPathType) otypes.get(i); + XPathType type = types.get(i); + XPathType otype = otypes.get(i); if (!type.getExpression().equals(otype.getExpression()) || !type.getNamespaceMap().equals(otype.getNamespaceMap()) || type.getFilter() != otype.getFilter()) { @@ -334,18 +342,21 @@ } private static boolean paramsEqual(ExcC14NParameterSpec spec1, - ExcC14NParameterSpec spec2) { + ExcC14NParameterSpec spec2) + { return spec1.getPrefixList().equals(spec2.getPrefixList()); } private static boolean paramsEqual(XPathFilterParameterSpec spec1, - XPathFilterParameterSpec spec2) { - return (spec1.getXPath().equals(spec2.getXPath()) && - spec1.getNamespaceMap().equals(spec2.getNamespaceMap())); + XPathFilterParameterSpec spec2) + { + return (spec1.getXPath().equals(spec2.getXPath()) && + spec1.getNamespaceMap().equals(spec2.getNamespaceMap())); } private static boolean paramsEqual(XSLTTransformParameterSpec spec1, - XSLTTransformParameterSpec spec2) { + XSLTTransformParameterSpec spec2) + { XMLStructure ostylesheet = spec2.getStylesheet(); if (!(ostylesheet instanceof javax.xml.crypto.dom.DOMStructure)) { @@ -353,7 +364,7 @@ } Node ostylesheetElem = ((javax.xml.crypto.dom.DOMStructure) ostylesheet).getNode(); - XMLStructure stylesheet = spec1.getStylesheet(); + XMLStructure stylesheet = spec1.getStylesheet(); Node stylesheetElem = ((javax.xml.crypto.dom.DOMStructure) stylesheet).getNode(); return nodesEqual(stylesheetElem, ostylesheetElem); --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java 2013-06-28 11:35:01.979676674 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java 2013-06-28 11:35:01.807682027 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMX509Data.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -51,7 +53,7 @@ //@@@ check for illegal combinations of data violating MUSTs in W3c spec public final class DOMX509Data extends DOMStructure implements X509Data { - private final List content; + private final List content; private CertificateFactory cf; /** @@ -61,7 +63,7 @@ * {@link String} (subject names), byte[] (subject key ids), * {@link java.security.cert.X509Certificate}, {@link X509CRL}, * or {@link javax.xml.dsig.XMLStructure} ({@link X509IssuerSerial} - * objects or elements from an external namespace). The list is + * objects or elements from an external namespace). The list is * defensively copied to protect against subsequent modification. * @return a X509Data * @throws NullPointerException if content is null @@ -69,18 +71,18 @@ * @throws ClassCastException if content contains any entries * that are not of one of the valid types mentioned above */ - public DOMX509Data(List content) { + public DOMX509Data(List content) { if (content == null) { throw new NullPointerException("content cannot be null"); } - List contentCopy = new ArrayList(content); + List contentCopy = new ArrayList(content); if (contentCopy.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } for (int i = 0, size = contentCopy.size(); i < size; i++) { Object x509Type = contentCopy.get(i); if (x509Type instanceof String) { - new X500Principal((String) x509Type); + new X500Principal((String)x509Type); } else if (!(x509Type instanceof byte[]) && !(x509Type instanceof X509Certificate) && !(x509Type instanceof X509CRL) && @@ -102,7 +104,7 @@ // get all children nodes NodeList nl = xdElem.getChildNodes(); int length = nl.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nl.item(i); // ignore all non-Element nodes @@ -110,7 +112,7 @@ continue; } - Element childElem = (Element) child; + Element childElem = (Element)child; String localName = childElem.getLocalName(); if (localName.equals("X509Certificate")) { content.add(unmarshalX509Certificate(childElem)); @@ -138,89 +140,92 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element xdElem = DOMUtils.createElement - (ownerDoc, "X509Data", XMLSignature.XMLNS, dsPrefix); + Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data", + XMLSignature.XMLNS, dsPrefix); // append children and preserve order for (int i = 0, size = content.size(); i < size; i++) { Object object = content.get(i); if (object instanceof X509Certificate) { - marshalCert((X509Certificate) object,xdElem,ownerDoc,dsPrefix); + marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix); } else if (object instanceof XMLStructure) { if (object instanceof X509IssuerSerial) { - ((DOMX509IssuerSerial) object).marshal + ((DOMX509IssuerSerial)object).marshal (xdElem, dsPrefix, context); } else { javax.xml.crypto.dom.DOMStructure domContent = - (javax.xml.crypto.dom.DOMStructure) object; + (javax.xml.crypto.dom.DOMStructure)object; DOMUtils.appendChild(xdElem, domContent.getNode()); } } else if (object instanceof byte[]) { - marshalSKI((byte[]) object, xdElem, ownerDoc, dsPrefix); + marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix); } else if (object instanceof String) { - marshalSubjectName((String) object, xdElem, ownerDoc,dsPrefix); + marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix); } else if (object instanceof X509CRL) { - marshalCRL((X509CRL) object, xdElem, ownerDoc, dsPrefix); + marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix); } } parent.appendChild(xdElem); } - private void marshalSKI(byte[] skid, Node parent, Document doc, - String dsPrefix) { - - Element skidElem = DOMUtils.createElement - (doc, "X509SKI", XMLSignature.XMLNS, dsPrefix); + private void marshalSKI(byte[] skid, Node parent, Document doc, + String dsPrefix) + { + Element skidElem = DOMUtils.createElement(doc, "X509SKI", + XMLSignature.XMLNS, dsPrefix); skidElem.appendChild(doc.createTextNode(Base64.encode(skid))); parent.appendChild(skidElem); } private void marshalSubjectName(String name, Node parent, Document doc, - String dsPrefix) { - - Element snElem = DOMUtils.createElement - (doc, "X509SubjectName", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + { + Element snElem = DOMUtils.createElement(doc, "X509SubjectName", + XMLSignature.XMLNS, dsPrefix); snElem.appendChild(doc.createTextNode(name)); parent.appendChild(snElem); } private void marshalCert(X509Certificate cert, Node parent, Document doc, - String dsPrefix) throws MarshalException { - - Element certElem = DOMUtils.createElement - (doc, "X509Certificate", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + throws MarshalException + { + Element certElem = DOMUtils.createElement(doc, "X509Certificate", + XMLSignature.XMLNS, dsPrefix); try { certElem.appendChild(doc.createTextNode - (Base64.encode(cert.getEncoded()))); + (Base64.encode(cert.getEncoded()))); } catch (CertificateEncodingException e) { throw new MarshalException("Error encoding X509Certificate", e); } parent.appendChild(certElem); } - private void marshalCRL(X509CRL crl, Node parent, Document doc, - String dsPrefix) throws MarshalException { - - Element crlElem = DOMUtils.createElement - (doc, "X509CRL", XMLSignature.XMLNS, dsPrefix); + private void marshalCRL(X509CRL crl, Node parent, Document doc, + String dsPrefix) + throws MarshalException + { + Element crlElem = DOMUtils.createElement(doc, "X509CRL", + XMLSignature.XMLNS, dsPrefix); try { crlElem.appendChild(doc.createTextNode - (Base64.encode(crl.getEncoded()))); + (Base64.encode(crl.getEncoded()))); } catch (CRLException e) { throw new MarshalException("Error encoding X509CRL", e); } parent.appendChild(crlElem); } - private X509Certificate unmarshalX509Certificate(Element elem) - throws MarshalException { + private X509Certificate unmarshalX509Certificate(Element elem) + throws MarshalException + { try { ByteArrayInputStream bs = unmarshalBase64Binary(elem); - return (X509Certificate) cf.generateCertificate(bs); + return (X509Certificate)cf.generateCertificate(bs); } catch (CertificateException e) { throw new MarshalException("Cannot create X509Certificate", e); } @@ -229,13 +234,13 @@ private X509CRL unmarshalX509CRL(Element elem) throws MarshalException { try { ByteArrayInputStream bs = unmarshalBase64Binary(elem); - return (X509CRL) cf.generateCRL(bs); + return (X509CRL)cf.generateCRL(bs); } catch (CRLException e) { throw new MarshalException("Cannot create X509CRL", e); } } - private ByteArrayInputStream unmarshalBase64Binary(Element elem) + private ByteArrayInputStream unmarshalBase64Binary(Element elem) throws MarshalException { try { if (cf == null) { @@ -249,6 +254,7 @@ } } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -257,9 +263,9 @@ if (!(o instanceof X509Data)) { return false; } - X509Data oxd = (X509Data) o; + X509Data oxd = (X509Data)o; - List ocontent = oxd.getContent(); + @SuppressWarnings("unchecked") List ocontent = oxd.getContent(); int size = content.size(); if (size != ocontent.size()) { return false; @@ -269,10 +275,10 @@ Object x = content.get(i); Object ox = ocontent.get(i); if (x instanceof byte[]) { - if (!(ox instanceof byte[]) || - !Arrays.equals((byte[]) x, (byte[]) ox)) { + if (!(ox instanceof byte[]) || + !Arrays.equals((byte[])x, (byte[])ox)) { return false; - } + } } else { if (!(x.equals(ox))) { return false; @@ -282,4 +288,12 @@ return true; } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + content.hashCode(); + + return result; + } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java 2013-06-28 11:35:02.679654885 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java 2013-06-28 11:35:02.511660114 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMX509IssuerSerial.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMX509IssuerSerial.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -42,23 +44,23 @@ * * @author Sean Mullan */ -public final class DOMX509IssuerSerial extends DOMStructure +public final class DOMX509IssuerSerial extends DOMStructure implements X509IssuerSerial { private final String issuerName; private final BigInteger serialNumber; /** - * Creates a DOMX509IssuerSerial containing the specified + * Creates a DOMX509IssuerSerial containing the specified * issuer distinguished name/serial number pair. * - * @param issuerName the X.509 issuer distinguished name in RFC 2253 + * @param issuerName the X.509 issuer distinguished name in RFC 2253 * String format * @param serialNumber the serial number * @throws IllegalArgumentException if the format of issuerName * is not RFC 2253 compliant - * @throws NullPointerException if issuerName or - * serialNumber is null + * @throws NullPointerException if issuerName or + * serialNumber is null */ public DOMX509IssuerSerial(String issuerName, BigInteger serialNumber) { if (issuerName == null) { @@ -94,15 +96,16 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element isElem = DOMUtils.createElement - (ownerDoc, "X509IssuerSerial", XMLSignature.XMLNS, dsPrefix); - Element inElem = DOMUtils.createElement - (ownerDoc, "X509IssuerName", XMLSignature.XMLNS, dsPrefix); - Element snElem = DOMUtils.createElement - (ownerDoc, "X509SerialNumber", XMLSignature.XMLNS, dsPrefix); + Element isElem = DOMUtils.createElement(ownerDoc, "X509IssuerSerial", + XMLSignature.XMLNS, dsPrefix); + Element inElem = DOMUtils.createElement(ownerDoc, "X509IssuerName", + XMLSignature.XMLNS, dsPrefix); + Element snElem = DOMUtils.createElement(ownerDoc, "X509SerialNumber", + XMLSignature.XMLNS, dsPrefix); inElem.appendChild(ownerDoc.createTextNode(issuerName)); snElem.appendChild(ownerDoc.createTextNode(serialNumber.toString())); isElem.appendChild(inElem); @@ -110,6 +113,7 @@ parent.appendChild(isElem); } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -117,8 +121,17 @@ if (!(obj instanceof X509IssuerSerial)) { return false; } - X509IssuerSerial ois = (X509IssuerSerial) obj; + X509IssuerSerial ois = (X509IssuerSerial)obj; return (issuerName.equals(ois.getIssuerName()) && - serialNumber.equals(ois.getSerialNumber())); + serialNumber.equals(ois.getSerialNumber())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + issuerName.hashCode(); + result = 31 * result + serialNumber.hashCode(); + + return result; } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java 2013-06-28 11:35:03.347634092 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java 2013-06-28 11:35:03.175639446 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXMLObject.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLObject.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -32,6 +34,7 @@ import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -44,11 +47,12 @@ * @author Sean Mullan */ public final class DOMXMLObject extends DOMStructure implements XMLObject { - + private final String id; private final String mimeType; private final String encoding; - private final List content; + private final List content; + private Element objectElem; /** * Creates an XMLObject from the specified parameters. @@ -63,19 +67,20 @@ * @throws ClassCastException if content contains any * entries that are not of type {@link XMLStructure} */ - public DOMXMLObject(List content, String id, String mimeType, - String encoding) { + public DOMXMLObject(List content, String id, + String mimeType, String encoding) + { if (content == null || content.isEmpty()) { - this.content = Collections.EMPTY_LIST; + this.content = Collections.emptyList(); } else { - List contentCopy = new ArrayList(content); - for (int i = 0, size = contentCopy.size(); i < size; i++) { - if (!(contentCopy.get(i) instanceof XMLStructure)) { + this.content = Collections.unmodifiableList( + new ArrayList(content)); + for (int i = 0, size = this.content.size(); i < size; i++) { + if (!(this.content.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid type"); } } - this.content = Collections.unmodifiableList(contentCopy); } this.id = id; this.mimeType = mimeType; @@ -89,10 +94,12 @@ * @throws MarshalException if there is an error when unmarshalling */ public DOMXMLObject(Element objElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // unmarshal attributes this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding"); - + Attr attr = objElem.getAttributeNodeNS(null, "Id"); if (attr != null) { this.id = attr.getValue(); @@ -104,17 +111,17 @@ NodeList nodes = objElem.getChildNodes(); int length = nodes.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element) child; + Element childElem = (Element)child; String tag = childElem.getLocalName(); if (tag.equals("Manifest")) { content.add(new DOMManifest(childElem, context, provider)); continue; } else if (tag.equals("SignatureProperties")) { - content.add(new DOMSignatureProperties(childElem)); + content.add(new DOMSignatureProperties(childElem, context)); continue; } else if (tag.equals("X509Data")) { content.add(new DOMX509Data(childElem)); @@ -125,10 +132,11 @@ content.add(new javax.xml.crypto.dom.DOMStructure(child)); } if (content.isEmpty()) { - this.content = Collections.EMPTY_LIST; + this.content = Collections.emptyList(); } else { this.content = Collections.unmodifiableList(content); } + this.objectElem = objElem; } public List getContent() { @@ -151,29 +159,32 @@ throws MarshalException { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element objElem = DOMUtils.createElement - (ownerDoc, "Object", XMLSignature.XMLNS, dsPrefix); - - // set attributes - DOMUtils.setAttributeID(objElem, "Id", id); - DOMUtils.setAttribute(objElem, "MimeType", mimeType); - DOMUtils.setAttribute(objElem, "Encoding", encoding); - - // create and append any elements and mixed content, if necessary - for (int i = 0, size = content.size(); i < size; i++) { - XMLStructure object = (XMLStructure) content.get(i); - if (object instanceof DOMStructure) { - ((DOMStructure) object).marshal(objElem, dsPrefix, context); - } else { - javax.xml.crypto.dom.DOMStructure domObject = - (javax.xml.crypto.dom.DOMStructure) object; - DOMUtils.appendChild(objElem, domObject.getNode()); + Element objElem = objectElem != null ? objectElem : null; + if (objElem == null) { + objElem = DOMUtils.createElement(ownerDoc, "Object", + XMLSignature.XMLNS, dsPrefix); + + // set attributes + DOMUtils.setAttributeID(objElem, "Id", id); + DOMUtils.setAttribute(objElem, "MimeType", mimeType); + DOMUtils.setAttribute(objElem, "Encoding", encoding); + + // create and append any elements and mixed content, if necessary + for (XMLStructure object : content) { + if (object instanceof DOMStructure) { + ((DOMStructure)object).marshal(objElem, dsPrefix, context); + } else { + javax.xml.crypto.dom.DOMStructure domObject = + (javax.xml.crypto.dom.DOMStructure)object; + DOMUtils.appendChild(objElem, domObject.getNode()); + } } } - + parent.appendChild(objElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -182,34 +193,53 @@ if (!(o instanceof XMLObject)) { return false; } - XMLObject oxo = (XMLObject) o; + XMLObject oxo = (XMLObject)o; - boolean idsEqual = (id == null ? oxo.getId() == null : - id.equals(oxo.getId())); - boolean encodingsEqual = (encoding == null ? oxo.getEncoding() == null : - encoding.equals(oxo.getEncoding())); - boolean mimeTypesEqual = (mimeType == null ? oxo.getMimeType() == null : - mimeType.equals(oxo.getMimeType())); + boolean idsEqual = (id == null ? oxo.getId() == null + : id.equals(oxo.getId())); + boolean encodingsEqual = + (encoding == null ? oxo.getEncoding() == null + : encoding.equals(oxo.getEncoding())); + boolean mimeTypesEqual = + (mimeType == null ? oxo.getMimeType() == null + : mimeType.equals(oxo.getMimeType())); + + @SuppressWarnings("unchecked") + List oxoContent = oxo.getContent(); + return (idsEqual && encodingsEqual && mimeTypesEqual && + equalsContent(oxoContent)); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (encoding != null) { + result = 31 * result + encoding.hashCode(); + } + if (mimeType != null) { + result = 31 * result + mimeType.hashCode(); + } + result = 31 * result + content.hashCode(); - return (idsEqual && encodingsEqual && mimeTypesEqual && - equalsContent(oxo.getContent())); + return result; } - private boolean equalsContent(List otherContent) { + private boolean equalsContent(List otherContent) { if (content.size() != otherContent.size()) { return false; } for (int i = 0, osize = otherContent.size(); i < osize; i++) { - XMLStructure oxs = (XMLStructure) otherContent.get(i); - XMLStructure xs = (XMLStructure) content.get(i); + XMLStructure oxs = otherContent.get(i); + XMLStructure xs = content.get(i); if (oxs instanceof javax.xml.crypto.dom.DOMStructure) { if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) { return false; } - Node onode = - ((javax.xml.crypto.dom.DOMStructure) oxs).getNode(); - Node node = - ((javax.xml.crypto.dom.DOMStructure) xs).getNode(); + Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode(); + Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode(); if (!DOMUtils.nodesEqual(node, onode)) { return false; } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java 2013-06-28 11:35:04.007613549 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java 2013-06-28 11:35:03.835618903 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMXMLSignature.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLSignature.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -40,7 +42,6 @@ import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; -import java.io.*; import java.security.InvalidKeyException; import java.security.Key; import java.security.Provider; @@ -48,8 +49,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -64,14 +64,15 @@ * @author Sean Mullan * @author Joyce Leung */ -public final class DOMXMLSignature extends DOMStructure +public final class DOMXMLSignature extends DOMStructure implements XMLSignature { - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private String id; private SignatureValue sv; private KeyInfo ki; - private List objects; + private List objects; private SignedInfo si; private Document ownerDoc = null; private Element localSigElem = null; @@ -79,12 +80,12 @@ private boolean validationStatus; private boolean validated = false; private KeySelectorResult ksr; - private HashMap signatureIdMap; + private HashMap signatureIdMap; static { com.sun.org.apache.xml.internal.security.Init.init(); } - + /** * Creates a DOMXMLSignature from the specified components. * @@ -98,8 +99,9 @@ * omit) * @throws NullPointerException if si is null */ - public DOMXMLSignature(SignedInfo si, KeyInfo ki, List objs, String id, - String signatureValueId) + public DOMXMLSignature(SignedInfo si, KeyInfo ki, + List objs, + String id, String signatureValueId) { if (si == null) { throw new NullPointerException("signedInfo cannot be null"); @@ -108,16 +110,16 @@ this.id = id; this.sv = new DOMSignatureValue(signatureValueId); if (objs == null) { - this.objects = Collections.EMPTY_LIST; + this.objects = Collections.emptyList(); } else { - List objsCopy = new ArrayList(objs); - for (int i = 0, size = objsCopy.size(); i < size; i++) { - if (!(objsCopy.get(i) instanceof XMLObject)) { + this.objects = + Collections.unmodifiableList(new ArrayList(objs)); + for (int i = 0, size = this.objects.size(); i < size; i++) { + if (!(this.objects.get(i) instanceof XMLObject)) { throw new ClassCastException ("objs["+i+"] is not an XMLObject"); } } - this.objects = Collections.unmodifiableList(objsCopy); } this.ki = ki; } @@ -129,7 +131,9 @@ * @throws MarshalException if XMLSignature cannot be unmarshalled */ public DOMXMLSignature(Element sigElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { localSigElem = sigElem; ownerDoc = localSigElem.getOwnerDocument(); @@ -140,9 +144,9 @@ Element siElem = DOMUtils.getFirstChildElement(localSigElem); si = new DOMSignedInfo(siElem, context, provider); - // unmarshal SignatureValue + // unmarshal SignatureValue Element sigValElem = DOMUtils.getNextSiblingElement(siElem); - sv = new DOMSignatureValue(sigValElem); + sv = new DOMSignatureValue(sigValElem, context); // unmarshal KeyInfo, if specified Element nextSibling = DOMUtils.getNextSiblingElement(sigValElem); @@ -153,15 +157,15 @@ // unmarshal Objects, if specified if (nextSibling == null) { - objects = Collections.EMPTY_LIST; + objects = Collections.emptyList(); } else { - List tempObjects = new ArrayList(); + List tempObjects = new ArrayList(); while (nextSibling != null) { - tempObjects.add - (new DOMXMLObject(nextSibling, context, provider)); + tempObjects.add(new DOMXMLObject(nextSibling, + context, provider)); nextSibling = DOMUtils.getNextSiblingElement(nextSibling); } - objects = Collections.unmodifiableList(tempObjects); + objects = Collections.unmodifiableList(tempObjects); } } @@ -190,52 +194,53 @@ } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { marshal(parent, null, dsPrefix, context); } public void marshal(Node parent, Node nextSibling, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { ownerDoc = DOMUtils.getOwnerDocument(parent); - - sigElem = DOMUtils.createElement - (ownerDoc, "Signature", XMLSignature.XMLNS, dsPrefix); + sigElem = DOMUtils.createElement(ownerDoc, "Signature", + XMLSignature.XMLNS, dsPrefix); // append xmlns attribute if (dsPrefix == null || dsPrefix.length() == 0) { - sigElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); + sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", + XMLSignature.XMLNS); } else { - sigElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, - XMLSignature.XMLNS); + sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + dsPrefix, XMLSignature.XMLNS); } // create and append SignedInfo element - ((DOMSignedInfo) si).marshal(sigElem, dsPrefix, context); + ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context); // create and append SignatureValue element - ((DOMSignatureValue) sv).marshal(sigElem, dsPrefix, context); + ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context); // create and append KeyInfo element if necessary if (ki != null) { - ((DOMKeyInfo) ki).marshal(sigElem, null, dsPrefix, context); + ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context); } // create and append Object elements if necessary for (int i = 0, size = objects.size(); i < size; i++) { - ((DOMXMLObject) objects.get(i)).marshal(sigElem, dsPrefix, context); + ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context); } // append Id attribute DOMUtils.setAttributeID(sigElem, "Id", id); - + parent.insertBefore(sigElem, nextSibling); } - public boolean validate(XMLValidateContext vc) - throws XMLSignatureException { - + public boolean validate(XMLValidateContext vc) + throws XMLSignatureException + { if (vc == null) { throw new NullPointerException("validateContext is null"); } @@ -258,20 +263,20 @@ } // validate all References - List refs = this.si.getReferences(); + @SuppressWarnings("unchecked") + List refs = this.si.getReferences(); boolean validateRefs = true; for (int i = 0, size = refs.size(); validateRefs && i < size; i++) { - Reference ref = (Reference) refs.get(i); + Reference ref = refs.get(i); boolean refValid = ref.validate(vc); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference[" + ref.getURI() + "] is valid: " - + refValid); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference[" + ref.getURI() + "] is valid: " + refValid); } validateRefs &= refValid; } if (!validateRefs) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Couldn't validate the References"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Couldn't validate the References"); } validationStatus = false; validated = true; @@ -281,27 +286,30 @@ // validate Manifests, if property set boolean validateMans = true; if (Boolean.TRUE.equals(vc.getProperty - ("org.jcp.xml.dsig.validateManifests"))) { - + ("org.jcp.xml.dsig.validateManifests"))) + { for (int i=0, size=objects.size(); validateMans && i < size; i++) { - XMLObject xo = (XMLObject) objects.get(i); - List content = xo.getContent(); + XMLObject xo = objects.get(i); + @SuppressWarnings("unchecked") + List content = xo.getContent(); int csize = content.size(); for (int j = 0; validateMans && j < csize; j++) { - XMLStructure xs = (XMLStructure) content.get(j); + XMLStructure xs = content.get(j); if (xs instanceof Manifest) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "validating manifest"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "validating manifest"); } - Manifest man = (Manifest) xs; - List manRefs = man.getReferences(); + Manifest man = (Manifest)xs; + @SuppressWarnings("unchecked") + List manRefs = man.getReferences(); int rsize = manRefs.size(); for (int k = 0; validateMans && k < rsize; k++) { - Reference ref = (Reference) manRefs.get(k); + Reference ref = manRefs.get(k); boolean refValid = ref.validate(vc); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Manifest ref[" - + ref.getURI() + "] is valid: " + refValid); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Manifest ref[" + ref.getURI() + "] is valid: " + refValid + ); } validateMans &= refValid; } @@ -315,42 +323,40 @@ return validationStatus; } - public void sign(XMLSignContext signContext) - throws MarshalException, XMLSignatureException { + public void sign(XMLSignContext signContext) + throws MarshalException, XMLSignatureException + { if (signContext == null) { throw new NullPointerException("signContext cannot be null"); } - DOMSignContext context = (DOMSignContext) signContext; - if (context != null) { - marshal(context.getParent(), context.getNextSibling(), + DOMSignContext context = (DOMSignContext)signContext; + marshal(context.getParent(), context.getNextSibling(), DOMUtils.getSignaturePrefix(context), context); - } // generate references and signature value - List allReferences = new ArrayList(); + List allReferences = new ArrayList(); // traverse the Signature and register all objects with IDs that // may contain References - signatureIdMap = new HashMap(); + signatureIdMap = new HashMap(); signatureIdMap.put(id, this); signatureIdMap.put(si.getId(), si); - List refs = si.getReferences(); - for (int i = 0, size = refs.size(); i < size; i++) { - Reference ref = (Reference) refs.get(i); + @SuppressWarnings("unchecked") + List refs = si.getReferences(); + for (Reference ref : refs) { signatureIdMap.put(ref.getId(), ref); } - for (int i = 0, size = objects.size(); i < size; i++) { - XMLObject obj = (XMLObject) objects.get(i); + for (XMLObject obj : objects) { signatureIdMap.put(obj.getId(), obj); - List content = obj.getContent(); - for (int j = 0, csize = content.size(); j < csize; j++) { - XMLStructure xs = (XMLStructure) content.get(j); + @SuppressWarnings("unchecked") + List content = obj.getContent(); + for (XMLStructure xs : content) { if (xs instanceof Manifest) { - Manifest man = (Manifest) xs; + Manifest man = (Manifest)xs; signatureIdMap.put(man.getId(), man); - List manRefs = man.getReferences(); - for (int k = 0, msize = manRefs.size(); k < msize; k++) { - Reference ref = (Reference) manRefs.get(k); + @SuppressWarnings("unchecked") + List manRefs = man.getReferences(); + for (Reference ref : manRefs) { allReferences.add(ref); signatureIdMap.put(ref.getId(), ref); } @@ -359,56 +365,51 @@ } // always add SignedInfo references after Manifest references so // that Manifest reference are digested first - allReferences.addAll(si.getReferences()); + allReferences.addAll(refs); // generate/digest each reference - for (int i = 0, size = allReferences.size(); i < size; i++) { - DOMReference ref = (DOMReference) allReferences.get(i); - digestReference(ref, signContext); + for (Reference ref : allReferences) { + digestReference((DOMReference)ref, signContext); } // do final sweep to digest any references that were skipped or missed - for (int i = 0, size = allReferences.size(); i < size; i++) { - DOMReference ref = (DOMReference) allReferences.get(i); - if (ref.isDigested()) { + for (Reference ref : allReferences) { + if (((DOMReference)ref).isDigested()) { continue; } - ref.digest(signContext); + ((DOMReference)ref).digest(signContext); } Key signingKey = null; KeySelectorResult ksr = null; try { - ksr = signContext.getKeySelector().select - (ki, KeySelector.Purpose.SIGN, - si.getSignatureMethod(), signContext); + ksr = signContext.getKeySelector().select(ki, + KeySelector.Purpose.SIGN, + si.getSignatureMethod(), + signContext); signingKey = ksr.getKey(); if (signingKey == null) { throw new XMLSignatureException("the keySelector did not " + - "find a signing key"); + "find a signing key"); } } catch (KeySelectorException kse) { throw new XMLSignatureException("cannot find signing key", kse); } // calculate signature value - byte[] val = null; try { - val = ((DOMSignatureMethod) si.getSignatureMethod()).sign - (signingKey, (DOMSignedInfo) si, signContext); + byte[] val = ((AbstractDOMSignatureMethod) + si.getSignatureMethod()).sign(signingKey, si, signContext); + ((DOMSignatureValue)sv).setValue(val); } catch (InvalidKeyException ike) { throw new XMLSignatureException(ike); } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "SignatureValue = " + val); - } - ((DOMSignatureValue) sv).setValue(val); - - this.localSigElem = sigElem; + this.localSigElem = sigElem; this.ksr = ksr; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -417,22 +418,39 @@ if (!(o instanceof XMLSignature)) { return false; } - XMLSignature osig = (XMLSignature) o; + XMLSignature osig = (XMLSignature)o; boolean idEqual = (id == null ? osig.getId() == null : id.equals(osig.getId())); boolean keyInfoEqual = - (ki == null ? osig.getKeyInfo() == null : - ki.equals(osig.getKeyInfo())); + (ki == null ? osig.getKeyInfo() == null + : ki.equals(osig.getKeyInfo())); return (idEqual && keyInfoEqual && - sv.equals(osig.getSignatureValue()) && - si.equals(osig.getSignedInfo()) && - objects.equals(osig.getObjects())); + sv.equals(osig.getSignatureValue()) && + si.equals(osig.getSignedInfo()) && + objects.equals(osig.getObjects())); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (ki != null) { + result = 31 * result + ki.hashCode(); + } + result = 31 * result + sv.hashCode(); + result = 31 * result + si.hashCode(); + result = 31 * result + objects.hashCode(); + + return result; } private void digestReference(DOMReference ref, XMLSignContext signContext) - throws XMLSignatureException { + throws XMLSignatureException + { if (ref.isDigested()) { return; } @@ -441,15 +459,15 @@ if (Utils.sameDocumentURI(uri)) { String id = Utils.parseIdFromSameDocumentURI(uri); if (id != null && signatureIdMap.containsKey(id)) { - Object obj = signatureIdMap.get(id); - if (obj instanceof DOMReference) { - digestReference((DOMReference) obj, signContext); - } else if (obj instanceof Manifest) { - Manifest man = (Manifest) obj; + XMLStructure xs = signatureIdMap.get(id); + if (xs instanceof DOMReference) { + digestReference((DOMReference)xs, signContext); + } else if (xs instanceof Manifest) { + Manifest man = (Manifest)xs; List manRefs = man.getReferences(); for (int i = 0, size = manRefs.size(); i < size; i++) { - digestReference - ((DOMReference) manRefs.get(i), signContext); + digestReference((DOMReference)manRefs.get(i), + signContext); } } } @@ -457,9 +475,9 @@ // reference dependencies in the XPath Transform - so be on // the safe side, and skip and do at end in the final sweep if (uri.length() == 0) { - List transforms = ref.getTransforms(); - for (int i = 0, size = transforms.size(); i < size; i++) { - Transform transform = (Transform) transforms.get(i); + @SuppressWarnings("unchecked") + List transforms = ref.getTransforms(); + for (Transform transform : transforms) { String transformAlg = transform.getAlgorithm(); if (transformAlg.equals(Transform.XPATH) || transformAlg.equals(Transform.XPATH2)) { @@ -471,9 +489,9 @@ ref.digest(signContext); } - public class DOMSignatureValue extends DOMStructure - implements SignatureValue { - + public class DOMSignatureValue extends DOMStructure + implements SignatureValue + { private String id; private byte[] value; private String valueBase64; @@ -485,7 +503,9 @@ this.id = id; } - DOMSignatureValue(Element sigValueElem) throws MarshalException { + DOMSignatureValue(Element sigValueElem, XMLCryptoContext context) + throws MarshalException + { try { // base64 decode signatureValue value = Base64.decode(sigValueElem); @@ -508,12 +528,12 @@ } public byte[] getValue() { - return (value == null) ? null : (byte[]) value.clone(); + return (value == null) ? null : (byte[])value.clone(); } - public boolean validate(XMLValidateContext validateContext) - throws XMLSignatureException { - + public boolean validate(XMLValidateContext validateContext) + throws XMLSignatureException + { if (validateContext == null) { throw new NullPointerException("context cannot be null"); } @@ -531,18 +551,18 @@ (ki, KeySelector.Purpose.VERIFY, sm, validateContext); validationKey = ksResult.getKey(); if (validationKey == null) { - throw new XMLSignatureException("the keyselector did " + - "not find a validation key"); + throw new XMLSignatureException("the keyselector did not " + + "find a validation key"); } } catch (KeySelectorException kse) { throw new XMLSignatureException("cannot find validation " + - "key", kse); + "key", kse); } // canonicalize SignedInfo and verify signature try { - validationStatus = ((DOMSignatureMethod) sm).verify - (validationKey, (DOMSignedInfo) si, value, validateContext); + validationStatus = ((AbstractDOMSignatureMethod)sm).verify + (validationKey, si, value, validateContext); } catch (Exception e) { throw new XMLSignatureException(e); } @@ -552,6 +572,7 @@ return validationStatus; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -560,7 +581,7 @@ if (!(o instanceof SignatureValue)) { return false; } - SignatureValue osv = (SignatureValue) o; + SignatureValue osv = (SignatureValue)o; boolean idEqual = (id == null ? osv.getId() == null : id.equals(osv.getId())); @@ -568,13 +589,24 @@ //XXX compare signature values? return idEqual; } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } - public void marshal(Node parent, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + return result; + } + public void marshal(Node parent, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { // create SignatureValue element - sigValueElem = DOMUtils.createElement - (ownerDoc, "SignatureValue", XMLSignature.XMLNS, dsPrefix); + sigValueElem = DOMUtils.createElement(ownerDoc, "SignatureValue", + XMLSignature.XMLNS, dsPrefix); if (valueBase64 != null) { sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64)); } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java 2013-06-28 11:35:04.703591885 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java 2013-06-28 11:35:04.527597363 -0400 @@ -2,31 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXMLSignatureFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; +import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.*; @@ -34,7 +37,6 @@ import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; -import java.security.spec.AlgorithmParameterSpec; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -56,6 +58,7 @@ return new DOMXMLSignature(si, ki, null, null, null); } + @SuppressWarnings("unchecked") public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki, List objects, String id, String signatureValueId) { return new DOMXMLSignature(si, ki, objects, id, signatureValueId); @@ -65,13 +68,15 @@ return newReference(uri, dm, null, null, null); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id) { return new DOMReference(uri, type, dm, transforms, id, getProvider()); } - public Reference newReference(String uri, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String type, + @SuppressWarnings("unchecked") + public Reference newReference(String uri, DigestMethod dm, + List appliedTransforms, Data result, List transforms, String type, String id) { if (appliedTransforms == null) { throw new NullPointerException("appliedTransforms cannot be null"); @@ -86,6 +91,7 @@ (uri, type, dm, appliedTransforms, result, transforms, id, getProvider()); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id, byte[] digestValue) { if (digestValue == null) { @@ -95,34 +101,41 @@ (uri, type, dm, null, null, transforms, id, digestValue, getProvider()); } + @SuppressWarnings("unchecked") public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references) { return newSignedInfo(cm, sm, references, null); } + @SuppressWarnings("unchecked") public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references, String id) { return new DOMSignedInfo(cm, sm, references, id); } // Object factory methods + @SuppressWarnings("unchecked") public XMLObject newXMLObject(List content, String id, String mimeType, String encoding) { return new DOMXMLObject(content, id, mimeType, encoding); } + @SuppressWarnings("unchecked") public Manifest newManifest(List references) { return newManifest(references, null); } + @SuppressWarnings("unchecked") public Manifest newManifest(List references, String id) { return new DOMManifest(references, id); } + @SuppressWarnings("unchecked") public SignatureProperties newSignatureProperties(List props, String id) { return new DOMSignatureProperties(props, id); } + @SuppressWarnings("unchecked") public SignatureProperty newSignatureProperty (List info, String target, String id) { return new DOMSignatureProperty(info, target, id); @@ -143,16 +156,23 @@ if (xmlStructure == null) { throw new NullPointerException("xmlStructure cannot be null"); } + if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("xmlStructure must be of type DOMStructure"); + } return unmarshal - (((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(), - null); + (((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(), + new UnmarshalContext()); + } + + private static class UnmarshalContext extends DOMCryptoContext { + UnmarshalContext() {} } - private XMLSignature unmarshal(Node node, XMLValidateContext context) + private XMLSignature unmarshal(Node node, XMLCryptoContext context) throws MarshalException { node.normalize(); - + Element element = null; if (node.getNodeType() == Node.DOCUMENT_NODE) { element = ((Document) node).getDocumentElement(); @@ -221,12 +241,20 @@ return new DOMSignatureMethod.SHA1withDSA(params); } else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA256)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA384)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA512)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA1)) { + return new DOMSignatureMethod.SHA1withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA256)) { + return new DOMSignatureMethod.SHA256withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA384)) { + return new DOMSignatureMethod.SHA384withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA512)) { + return new DOMSignatureMethod.SHA512withECDSA(params); } else { throw new NoSuchAlgorithmException("unsupported algorithm"); } @@ -235,12 +263,18 @@ public Transform newTransform(String algorithm, TransformParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { + TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + spi.init(params); return new DOMTransform(spi); } @@ -249,11 +283,16 @@ XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + if (params == null) { spi.init(null); } else { @@ -266,11 +305,16 @@ C14NMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + spi.init(params); return new DOMCanonicalizationMethod(spi); } @@ -278,17 +322,22 @@ public CanonicalizationMethod newCanonicalizationMethod(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { - TransformService spi; - try { + TransformService spi; + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } if (params == null) { spi.init(null); } else { spi.init(params, null); } + return new DOMCanonicalizationMethod(spi); } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java 2013-06-28 11:35:05.391570470 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java 2013-06-28 11:35:05.207576197 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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. */ /* * =========================================================================== @@ -29,7 +31,7 @@ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXPathFilter2Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXPathFilter2Transform.java 1203789 2011-11-18 18:46:07Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -40,10 +42,10 @@ import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; import java.security.InvalidAlgorithmParameterException; import java.util.ArrayList; -import java.util.Iterator; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; +import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -57,7 +59,8 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { @@ -68,43 +71,44 @@ } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - + throws InvalidAlgorithmParameterException + { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { - throw (InvalidAlgorithmParameterException) - new InvalidAlgorithmParameterException().initCause(me); + throw new InvalidAlgorithmParameterException(me); } } - private void unmarshalParams(Element curXPathElem) throws MarshalException { - List list = new ArrayList(); + private void unmarshalParams(Element curXPathElem) throws MarshalException + { + List list = new ArrayList(); while (curXPathElem != null) { String xPath = curXPathElem.getFirstChild().getNodeValue(); - String filterVal = - DOMUtils.getAttributeValue(curXPathElem, "Filter"); + String filterVal = DOMUtils.getAttributeValue(curXPathElem, + "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } XPathType.Filter filter = null; if (filterVal.equals("intersect")) { filter = XPathType.Filter.INTERSECT; - } else if (filterVal.equals("subtract")) { + } else if (filterVal.equals("subtract")) { filter = XPathType.Filter.SUBTRACT; } else if (filterVal.equals("union")) { filter = XPathType.Filter.UNION; } else { - throw new MarshalException("Unknown XPathType filter type" - + filterVal); + throw new MarshalException("Unknown XPathType filter type" + + filterVal); } NamedNodeMap attributes = curXPathElem.getAttributes(); if (attributes != null) { int length = attributes.getLength(); - Map namespaceMap = new HashMap(length); + Map namespaceMap = + new HashMap(length); for (int i = 0; i < length; i++) { - Attr attr = (Attr) attributes.item(i); + Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && prefix.equals("xmlns")) { namespaceMap.put(attr.getLocalName(), attr.getValue()); @@ -121,32 +125,34 @@ } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); - XPathFilter2ParameterSpec xp = - (XPathFilter2ParameterSpec) getParameterSpec(); + XPathFilter2ParameterSpec xp = + (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); - String qname = (prefix == null || prefix.length() == 0) + String qname = (prefix == null || prefix.length() == 0) ? "xmlns" : "xmlns:" + prefix; - List list = xp.getXPathList(); - for (int i = 0, size = list.size(); i < size; i++) { - XPathType xpathType = (XPathType) list.get(i); - Element elem = DOMUtils.createElement - (ownerDoc, "XPath", Transform.XPATH2, prefix); + @SuppressWarnings("unchecked") + List xpathList = xp.getXPathList(); + for (XPathType xpathType : xpathList) { + Element elem = DOMUtils.createElement(ownerDoc, "XPath", + Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); - DOMUtils.setAttribute - (elem, "Filter", xpathType.getFilter().toString()); + DOMUtils.setAttribute(elem, "Filter", + xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, - Transform.XPATH2); + Transform.XPATH2); // add namespace attributes, if necessary - Iterator it = xpathType.getNamespaceMap().entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" - + (String) entry.getKey(), (String) entry.getValue()); + @SuppressWarnings("unchecked") + Set> entries = + xpathType.getNamespaceMap().entrySet(); + for (Map.Entry entry : entries) { + elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + entry.getKey(), + entry.getValue()); } transformElem.appendChild(elem); --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java 2013-06-28 11:35:06.083548930 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java 2013-06-28 11:35:05.903554533 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXPathTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXPathTransform.java 1203789 2011-11-18 18:46:07Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,9 +33,9 @@ import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec; import java.security.InvalidAlgorithmParameterException; -import java.util.Iterator; -import java.util.Map; import java.util.HashMap; +import java.util.Map; +import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -45,9 +47,10 @@ * @author Sean Mullan */ public final class DOMXPathTransform extends ApacheTransform { - + public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilterParameterSpec)) { @@ -58,8 +61,8 @@ } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - + throws InvalidAlgorithmParameterException + { super.init(parent, context); unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } @@ -70,9 +73,10 @@ NamedNodeMap attributes = paramsElem.getAttributes(); if (attributes != null) { int length = attributes.getLength(); - Map namespaceMap = new HashMap(length); + Map namespaceMap = + new HashMap(length); for (int i = 0; i < length; i++) { - Attr attr = (Attr) attributes.item(i); + Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && prefix.equals("xmlns")) { namespaceMap.put(attr.getLocalName(), attr.getValue()); @@ -85,24 +89,25 @@ } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); - XPathFilterParameterSpec xp = - (XPathFilterParameterSpec) getParameterSpec(); - Element xpathElem = DOMUtils.createElement - (ownerDoc, "XPath", XMLSignature.XMLNS, - DOMUtils.getSignaturePrefix(context)); + XPathFilterParameterSpec xp = + (XPathFilterParameterSpec)getParameterSpec(); + Element xpathElem = DOMUtils.createElement(ownerDoc, "XPath", + XMLSignature.XMLNS, DOMUtils.getSignaturePrefix(context)); xpathElem.appendChild(ownerDoc.createTextNode(xp.getXPath())); // add namespace attributes, if necessary - Iterator i = xp.getNamespaceMap().entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" - + (String) entry.getKey(), (String) entry.getValue()); + @SuppressWarnings("unchecked") + Set> entries = + xp.getNamespaceMap().entrySet(); + for (Map.Entry entry : entries) { + xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + entry.getKey(), + entry.getValue()); } - + transformElem.appendChild(xpathElem); } } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java 2013-06-28 11:35:06.759527889 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java 2013-06-28 11:35:06.583533367 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXSLTTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXSLTTransform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,7 +33,6 @@ import org.w3c.dom.Node; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec; @@ -42,7 +43,7 @@ * @author Sean Mullan */ public final class DOMXSLTTransform extends ApacheTransform { - + public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { if (params == null) { @@ -69,9 +70,9 @@ public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { super.marshalParams(parent, context); - XSLTTransformParameterSpec xp = + XSLTTransformParameterSpec xp = (XSLTTransformParameterSpec) getParameterSpec(); - Node xsltElem = + Node xsltElem = ((javax.xml.crypto.dom.DOMStructure) xp.getStylesheet()).getNode(); DOMUtils.appendChild(transformElem, xsltElem); } --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java 2013-06-28 11:35:07.383508466 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java 2013-06-28 11:35:07.199514193 -0400 @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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 +/** + * 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 * - * 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. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: Utils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: Utils.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -44,7 +46,8 @@ private Utils() {} public static byte[] readBytesFromStream(InputStream is) - throws IOException { + throws IOException + { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; while (true) { @@ -67,10 +70,10 @@ * @param i the Iterator * @return the Set of Nodes */ - static Set toNodeSet(Iterator i) { - Set nodeSet = new HashSet(); + static Set toNodeSet(Iterator i) { + Set nodeSet = new HashSet(); while (i.hasNext()) { - Node n = (Node) i.next(); + Node n = i.next(); nodeSet.add(n); // insert attributes nodes to comply with XPath if (n.getNodeType() == Node.ELEMENT_NODE) { --- old/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java 2013-06-28 11:35:08.063487300 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java 2013-06-28 11:35:07.891492653 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. - * - * Licensed 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. - * +/** + * 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. */ /* * =========================================================================== @@ -29,7 +31,7 @@ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: XMLDSigRI.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -53,13 +55,15 @@ static final long serialVersionUID = -5049765099299494554L; private static final String INFO = "XMLDSig " + - "(DOM XMLSignatureFactory; DOM KeyInfoFactory)"; + "(DOM XMLSignatureFactory; DOM KeyInfoFactory; " + + "C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " + + "XPath2, XSLT TransformServices)"; public XMLDSigRI() { /* We are the XMLDSig provider */ - super("XMLDSig", 1.0, INFO); - - final Map map = new HashMap(); + super("XMLDSig", 1.8, INFO); + + final Map map = new HashMap(); map.put("XMLSignatureFactory.DOM", "org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory"); map.put("KeyInfoFactory.DOM", @@ -67,94 +71,89 @@ // Inclusive C14N - map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE, + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE, "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod"); map.put("Alg.Alias.TransformService.INCLUSIVE", CanonicalizationMethod.INCLUSIVE); - map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE + " MechanismType", "DOM"); // InclusiveWithComments C14N - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod"); map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS", CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS); - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS + " MechanismType", "DOM"); // Inclusive C14N 1.1 - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11", + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11", "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method"); - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11" + + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11" + " MechanismType", "DOM"); - // InclusiveWithComments C14N 1.1 - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11#WithComments", + // InclusiveWithComments C14N 1.1 + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments", "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method"); - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11#WithComments" + + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments" + " MechanismType", "DOM"); // Exclusive C14N - map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE, + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE, "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod"); map.put("Alg.Alias.TransformService.EXCLUSIVE", CanonicalizationMethod.EXCLUSIVE); - map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE + " MechanismType", "DOM"); // ExclusiveWithComments C14N - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod"); map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS", CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS); - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS + " MechanismType", "DOM"); // Base64 Transform - map.put((String) "TransformService." + Transform.BASE64, + map.put("TransformService." + Transform.BASE64, "org.jcp.xml.dsig.internal.dom.DOMBase64Transform"); map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64); - map.put((String) "TransformService." + Transform.BASE64 + + map.put("TransformService." + Transform.BASE64 + " MechanismType", "DOM"); // Enveloped Transform - map.put((String) "TransformService." + Transform.ENVELOPED, + map.put("TransformService." + Transform.ENVELOPED, "org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform"); map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED); - map.put((String) "TransformService." + Transform.ENVELOPED + + map.put("TransformService." + Transform.ENVELOPED + " MechanismType", "DOM"); // XPath2 Transform - map.put((String) "TransformService." + Transform.XPATH2, + map.put("TransformService." + Transform.XPATH2, "org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform"); map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2); - map.put((String) "TransformService." + Transform.XPATH2 + + map.put("TransformService." + Transform.XPATH2 + " MechanismType", "DOM"); // XPath Transform - map.put((String) "TransformService." + Transform.XPATH, + map.put("TransformService." + Transform.XPATH, "org.jcp.xml.dsig.internal.dom.DOMXPathTransform"); map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH); - map.put((String) "TransformService." + Transform.XPATH + + map.put("TransformService." + Transform.XPATH + " MechanismType", "DOM"); // XSLT Transform - map.put((String) "TransformService." + Transform.XSLT, + map.put("TransformService." + Transform.XSLT, "org.jcp.xml.dsig.internal.dom.DOMXSLTTransform"); map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT); - map.put((String) "TransformService." + Transform.XSLT + - " MechanismType", "DOM"); + map.put("TransformService." + Transform.XSLT + " MechanismType", "DOM"); - AccessController.doPrivileged(new java.security.PrivilegedAction() { - public Object run() { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { putAll(map); return null; } --- old/test/closed/com/sun/org/apache/xml/internal/security/ClassLoaderUtils.java 2013-06-28 11:35:08.611470242 -0400 +++ new/test/closed/com/sun/org/apache/xml/internal/security/ClassLoaderUtils.java 2013-06-28 11:35:08.495473853 -0400 @@ -17,18 +17,14 @@ public class ClassLoaderUtils { public static void main(String[] args) throws Exception { - String removedClass = - "com.sun.org.apache.xml.internal.security.utils.ClassLoaderUtils"; + + String xmlsec = "com.sun.org.apache.xml.internal.security."; String[] classes = { - "com.sun.org.apache.xml.internal.security.algorithms.ClassLoaderUtils", - "com.sun.org.apache.xml.internal.security.transforms.ClassLoaderUtils" + xmlsec + "algorithms.ClassLoaderUtils", + xmlsec + "transforms.ClassLoaderUtils", + xmlsec + "utils.ClassLoaderUtils" }; - try { - Class.forName(removedClass); - throw new Exception(removedClass + " was found"); - } catch (ClassNotFoundException e) {} - for (String cl : classes) { Class c = Class.forName(cl); if (Modifier.isPublic(c.getModifiers())) { --- old/test/closed/javax/xml/crypto/dsig/Transform/ReplaceTransform.java 2013-06-28 11:35:08.975458912 -0400 +++ new/test/closed/javax/xml/crypto/dsig/Transform/ReplaceTransform.java 2013-06-28 11:35:08.855462647 -0400 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java 2013-06-28 11:35:09.255450197 -0400 @@ -0,0 +1,184 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.c14n.implementations; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Iterator; +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.signature.XMLSignatureInput; +import org.w3c.dom.Attr; +import org.w3c.dom.Comment; +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 + * present in the subtree are emitted. The attributes are sorted within an element, + * with the namespace declarations appearing before the regular attributes. + * This algorithm is not a true canonicalization since equivalent subtrees + * may produce different output. It is therefore unsuitable for digital signatures. + * This same property makes it ideal for XML Encryption Syntax and Processing, + * because the decrypted XML content will share the same physical representation + * as the original XML content that was encrypted. + */ +public class CanonicalizerPhysical extends CanonicalizerBase { + + private final SortedSet result = new TreeSet(COMPARE); + + /** + * Constructor Canonicalizer20010315 + */ + public CanonicalizerPhysical() { + super(true); + } + + /** + * Always throws a CanonicalizationException. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Always throws a CanonicalizationException. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Returns the Attr[]s to be output for the given element. + *
      + * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes()) { + return null; + } + + // result will contain all the attrs declared directly on that element + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + result.add(attribute); + } + } + + return result.iterator(); + } + + /** + * Returns the Attr[]s to be output for the given element. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + // nothing to do + } + + @Override + protected void handleParent(Element e, NameSpaceSymbTable ns) { + // nothing to do + } + + /** @inheritDoc */ + public final String engineGetURI() { + 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 { + // Processing Instructions before or after the document element are not treated specially + super.outputPItoWriter(currentPI, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT); + } + + @Override + protected void outputCommentToWriter(Comment currentComment, + OutputStream writer, int position) throws IOException { + // Comments before or after the document element are not treated specially + super.outputCommentToWriter(currentComment, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT); + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java 2013-06-28 11:35:09.695436501 -0400 @@ -0,0 +1,249 @@ +/* + * 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.encryption; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Converts Strings into Nodes and visa versa. + * + * An abstract class for common Serializer functionality + */ +public abstract class AbstractSerializer implements Serializer { + + protected Canonicalizer canon; + + public void setCanonicalizer(Canonicalizer canon) { + this.canon = canon; + } + + /** + * Returns a String representation of the specified + * Element. + *

      + * Refer also to comments about setup of format. + * + * @param element the Element to serialize. + * @return the String representation of the serilaized + * Element. + * @throws Exception + */ + public String serialize(Element element) throws Exception { + return canonSerialize(element); + } + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + public byte[] serializeToByteArray(Element element) throws Exception { + return canonSerializeToByteArray(element); + } + + /** + * Returns a String representation of the specified + * NodeList. + *

      + * This is a special case because the NodeList may represent a + * DocumentFragment. A document fragment may be a + * non-valid XML document (refer to appropriate description of + * W3C) because it my start with a non-element node, e.g. a text + * node. + *

      + * The methods first converts the node list into a document fragment. + * Special care is taken to not destroy the current document, thus + * the method clones the nodes (deep cloning) before it appends + * them to the document fragment. + *

      + * Refer also to comments about setup of format. + * + * @param content the NodeList to serialize. + * @return the String representation of the serialized + * NodeList. + * @throws Exception + */ + public String serialize(NodeList content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + for (int i = 0; i < content.getLength(); i++) { + canon.canonicalizeSubtree(content.item(i)); + } + String ret = baos.toString("UTF-8"); + baos.reset(); + return ret; + } + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @throws Exception + */ + public byte[] serializeToByteArray(NodeList content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + for (int i = 0; i < content.getLength(); i++) { + canon.canonicalizeSubtree(content.item(i)); + } + return baos.toByteArray(); + } + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the canonicalization of the node + * @throws Exception + */ + public String canonSerialize(Node node) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + canon.canonicalizeSubtree(node); + String ret = baos.toString("UTF-8"); + baos.reset(); + return ret; + } + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the (byte[]) canonicalization of the node + * @throws Exception + */ + public byte[] canonSerializeToByteArray(Node node) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + canon.canonicalizeSubtree(node); + return baos.toByteArray(); + } + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; + + protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException { + // Create the context to parse the document against + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + try { + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8"); + outputStreamWriter.write(" storedNamespaces = new HashMap(); + Node wk = ctx; + while (wk != null) { + NamedNodeMap atts = wk.getAttributes(); + if (atts != null) { + for (int i = 0; i < atts.getLength(); ++i) { + Node att = atts.item(i); + String nodeName = att.getNodeName(); + if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:")) + && !storedNamespaces.containsKey(att.getNodeName())) { + outputStreamWriter.write(" "); + outputStreamWriter.write(nodeName); + outputStreamWriter.write("=\""); + outputStreamWriter.write(att.getNodeValue()); + outputStreamWriter.write("\""); + storedNamespaces.put(nodeName, att.getNodeValue()); + } + } + } + wk = wk.getParentNode(); + } + outputStreamWriter.write(">"); + outputStreamWriter.flush(); + byteArrayOutputStream.write(source); + + outputStreamWriter.write(""); + outputStreamWriter.close(); + + return byteArrayOutputStream.toByteArray(); + } catch (UnsupportedEncodingException e) { + throw new XMLEncryptionException("empty", e); + } catch (IOException e) { + throw new XMLEncryptionException("empty", e); + } + } + + protected static String createContext(String source, Node ctx) { + // Create the context to parse the document against + StringBuilder sb = new StringBuilder(); + sb.append(" storedNamespaces = new HashMap(); + Node wk = ctx; + while (wk != null) { + NamedNodeMap atts = wk.getAttributes(); + if (atts != null) { + for (int i = 0; i < atts.getLength(); ++i) { + Node att = atts.item(i); + String nodeName = att.getNodeName(); + if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:")) + && !storedNamespaces.containsKey(att.getNodeName())) { + sb.append(" " + nodeName + "=\"" + att.getNodeValue() + "\""); + storedNamespaces.put(nodeName, att.getNodeValue()); + } + } + } + wk = wk.getParentNode(); + } + sb.append(">" + source + ""); + return sb.toString(); + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java 2013-06-28 11:35:10.107423677 -0400 @@ -0,0 +1,114 @@ +/* + * 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.encryption; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Converts Strings into Nodes and visa versa. + */ +public class DocumentSerializer extends AbstractSerializer { + + protected DocumentBuilderFactory dbf; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException { + byte[] fragment = createContext(source, ctx); + return deserialize(ctx, new InputSource(new ByteArrayInputStream(fragment))); + } + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public Node deserialize(String source, Node ctx) throws XMLEncryptionException { + String fragment = createContext(source, ctx); + return deserialize(ctx, new InputSource(new StringReader(fragment))); + } + + /** + * @param ctx + * @param inputSource + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException { + try { + if (dbf == null) { + dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); + dbf.setValidating(false); + } + DocumentBuilder db = dbf.newDocumentBuilder(); + Document d = db.parse(inputSource); + + Document contextDocument = null; + if (Node.DOCUMENT_NODE == ctx.getNodeType()) { + contextDocument = (Document)ctx; + } else { + contextDocument = ctx.getOwnerDocument(); + } + + Element fragElt = + (Element) contextDocument.importNode(d.getDocumentElement(), true); + DocumentFragment result = contextDocument.createDocumentFragment(); + Node child = fragElt.getFirstChild(); + while (child != null) { + fragElt.removeChild(child); + result.appendChild(child); + child = fragElt.getFirstChild(); + } + return result; + } catch (SAXException se) { + throw new XMLEncryptionException("empty", se); + } catch (ParserConfigurationException pce) { + throw new XMLEncryptionException("empty", pce); + } catch (IOException ioe) { + throw new XMLEncryptionException("empty", ioe); + } + } + +} \ No newline at end of file --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java 2013-06-28 11:35:10.523410728 -0400 @@ -0,0 +1,77 @@ +/* + * 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.encryption; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Converts Strings into Nodes and visa versa. + */ +public interface Serializer { + + /** + * Set the Canonicalizer object to use. + */ + void setCanonicalizer(Canonicalizer canon); + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + byte[] serializeToByteArray(Element element) throws Exception; + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @throws Exception + */ + byte[] serializeToByteArray(NodeList content) throws Exception; + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the (byte[]) canonicalization of the node + * @throws Exception + */ + byte[] canonSerializeToByteArray(Node node) throws Exception; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java 2013-06-28 11:35:10.903398900 -0400 @@ -0,0 +1,158 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.keys.content; + +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:DEREncodedKeyvalue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent { + + /** JCA algorithm key types supported by this implementation. */ + public static final String supportedKeyTypes[] = { "RSA", "DSA", "EC"}; + + /** + * Constructor DEREncodedKeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public DEREncodedKeyValue(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor DEREncodedKeyValue + * + * @param doc + * @param publicKey + * @throws XMLSecurityException + */ + public DEREncodedKeyValue(Document doc, PublicKey publicKey) throws XMLSecurityException { + super(doc); + + this.addBase64Text(getEncodedDER(publicKey)); + } + + /** + * Constructor DEREncodedKeyValue + * + * @param doc + * @param base64EncodedKey + */ + public DEREncodedKeyValue(Document doc, byte[] encodedKey) { + super(doc); + + this.addBase64Text(encodedKey); + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } else { + this.constructionElement.removeAttributeNS(null, Constants._ATT_ID); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DERENCODEDKEYVALUE; + } + + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + byte[] encodedKey = getBytesFromTextChild(); + + // Iterate over the supported key types until one produces a public key. + for (String keyType : supportedKeyTypes) { + try { + KeyFactory keyFactory = KeyFactory.getInstance(keyType); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey); + PublicKey publicKey = keyFactory.generatePublic(keySpec); + if (publicKey != null) { + return publicKey; + } + } catch (NoSuchAlgorithmException e) { + // Do nothing, try the next type + } catch (InvalidKeySpecException e) { + // Do nothing, try the next type + } + } + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedEncodedKey"); + } + + /** + * Method getEncodedDER + * + * @return the public key + * @throws XMLSecurityException + */ + protected byte[] getEncodedDER(PublicKey publicKey) throws XMLSecurityException { + try { + KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm()); + X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class); + return keySpec.getEncoded(); + } catch (NoSuchAlgorithmException e) { + Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() }; + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e); + } catch (InvalidKeySpecException e) { + Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() }; + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e); + } + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java 2013-06-28 11:35:11.311386200 -0400 @@ -0,0 +1,107 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.keys.content; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent { + + /** + * Constructor RetrievalMethod + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } + + /** + * Constructor RetrievalMethod + * + * @param doc + * @param URI + */ + public KeyInfoReference(Document doc, String URI) { + super(doc); + + this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); + } + + /** + * Method getURIAttr + * + * @return the URI attribute + */ + public Attr getURIAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); + } + + /** + * Method getURI + * + * @return URI string + */ + public String getURI() { + return this.getURIAttr().getNodeValue(); + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } else { + this.constructionElement.removeAttributeNS(null, Constants._ATT_ID); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFOREFERENCE; + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java 2013-06-28 11:35:11.715373625 -0400 @@ -0,0 +1,139 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.keys.content.x509; + +import java.security.MessageDigest; +import java.security.cert.X509Certificate; + +import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent { + + /** + * Constructor XMLX509Digest + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509Digest(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor XMLX509Digest + * + * @param doc + * @param digestBytes + * @param algorithmURI + */ + public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) { + super(doc); + this.addBase64Text(digestBytes); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + } + + /** + * Constructor XMLX509Digest + * + * @param doc + * @param x509certificate + * @param algorithmURI + * @throws XMLSecurityException + */ + public XMLX509Digest(Document doc, X509Certificate x509certificate, String algorithmURI) throws XMLSecurityException { + super(doc); + this.addBase64Text(getDigestBytesFromCert(x509certificate, algorithmURI)); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + } + + /** + * Method getAlgorithmAttr + * + * @return the Algorithm attribute + */ + public Attr getAlgorithmAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_ALGORITHM); + } + + /** + * Method getAlgorithm + * + * @return Algorithm string + */ + public String getAlgorithm() { + return this.getAlgorithmAttr().getNodeValue(); + } + + /** + * Method getDigestBytes + * + * @return the digestbytes + * @throws XMLSecurityException + */ + public byte[] getDigestBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } + + /** + * Method getDigestBytesFromCert + * + * @param cert + * @param algorithmURI + * @return digest bytes from the given certificate + * + * @throws XMLSecurityException + */ + public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException { + String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI); + if (jcaDigestAlgorithm == null) { + Object exArgs[] = { algorithmURI }; + throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs); + } + + try { + MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm); + return md.digest(cert.getEncoded()); + } catch (Exception e) { + Object exArgs[] = { jcaDigestAlgorithm }; + throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs); + } + + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DIGEST; + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java 2013-06-28 11:35:12.123360926 -0400 @@ -0,0 +1,83 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys from a + * dsig11:DEREncodedKeyValue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValueResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName()); + + /** {@inheritDoc}. */ + public 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) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI); + return derKeyValue.getPublicKey(); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java 2013-06-28 11:35:12.535348101 -0400 @@ -0,0 +1,290 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.KeyInfo; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** + * KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a + * dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReferenceResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName()); + + /** {@inheritDoc}. */ + public 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) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPublicKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getX509Certificate(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getSecretKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPrivateKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** + * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance. + * + * @param element + * @param baseURI + * @param storage + * @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 { + KeyInfoReference reference = new KeyInfoReference(element, baseURI); + Attr uriAttr = reference.getURIAttr(); + + XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation); + + Element referentElement = null; + try { + referentElement = obtainReferenceElement(resource); + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + return null; + } + + if (referentElement == null) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue()); + return null; + } + + validateReference(referentElement); + + KeyInfo referent = new KeyInfo(referentElement, baseURI); + referent.addStorageResolver(storage); + return referent; + } + + /** + * Validate the Element referred to by the KeyInfoReference. + * + * @param referentElement + * + * @throws XMLSecurityException + */ + private void validateReference(Element referentElement) throws XMLSecurityException { + if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) { + Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) }; + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs); + } + + KeyInfo referent = new KeyInfo(referentElement, ""); + if (referent.containsKeyInfoReference()) { + if (secureValidation) { + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure"); + } else { + // Don't support chains of references at this time. If do support in the future, this is where the code + // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic + // to implement, and/or very expensive given remote URI references. + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure"); + } + } + + } + + /** + * Resolve the XML signature input represented by the specified URI. + * + * @param uri + * @param baseURI + * @param secureValidation + * @return + * @throws XMLSecurityException + */ + private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation) + throws XMLSecurityException { + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + return resource; + } + + /** + * Resolve the Element effectively represented by the XML signature input source. + * + * @param resource + * @return + * @throws CanonicalizationException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws KeyResolverException + */ + private Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet"); + return null; + } else { + // Retrieved resource is a byte stream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + } + return e; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java 2013-06-28 11:35:12.951335153 -0400 @@ -0,0 +1,353 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Enumeration; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a PrivateKey within a KeyStore based on the KeyInfo hints. + * For X509Data hints, the certificate associated with the private key entry must match. + * For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore. + */ +public class PrivateKeyResolver extends KeyResolverSpi { + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(PrivateKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public PrivateKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + 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; + } + + /** + * 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 + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) 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 + ) 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 + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + PrivateKey privKey = resolveX509Data(element, baseURI); + if (privKey != null) { + return privKey; + } + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?"); + String keyName = element.getFirstChild().getNodeValue(); + + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + private PrivateKey resolveX509Data(Element element, String baseURI) { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?"); + + try { + X509Data x509Data = new X509Data(element, baseURI); + + int len = x509Data.lengthSKI(); + for (int i = 0; i < len; i++) { + XMLX509SKI x509SKI = x509Data.itemSKI(i); + PrivateKey privKey = resolveX509SKI(x509SKI); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthIssuerSerial(); + for (int i = 0; i < len; i++) { + XMLX509IssuerSerial x509Serial = x509Data.itemIssuerSerial(i); + PrivateKey privKey = resolveX509IssuerSerial(x509Serial); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthSubjectName(); + for (int i = 0; i < len; i++) { + XMLX509SubjectName x509SubjectName = x509Data.itemSubjectName(i); + PrivateKey privKey = resolveX509SubjectName(x509SubjectName); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthCertificate(); + for (int i = 0; i < len; i++) { + XMLX509Certificate x509Cert = x509Data.itemCertificate(i); + PrivateKey privKey = resolveX509Certificate(x509Cert); + if (privKey != null) { + return privKey; + } + } + } catch (XMLSecurityException e) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } catch (KeyStoreException e) { + log.log(java.util.logging.Level.FINE, "KeyStoreException", e); + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Key Identifier + */ + private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert); + + if (certSKI.equals(x509SKI)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair. + */ + private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509IssuerSerial certSerial = + new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert); + + if (certSerial.equals(x509Serial)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Name. + */ + private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SubjectName certSN = + new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert); + + if (certSN.equals(x509SubjectName)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Certificate. + */ + private PrivateKey resolveX509Certificate( + XMLX509Certificate x509Cert + ) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?"); + byte[] x509CertBytes = x509Cert.getCertificateBytes(); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + byte[] certBytes = null; + + try { + certBytes = cert.getEncoded(); + } catch (CertificateEncodingException e1) { + } + + if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } + catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java 2013-06-28 11:35:13.371322080 -0400 @@ -0,0 +1,129 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a SecretKey within a KeyStore based on the KeyName. + * The KeyName is the key entry alias within the KeyStore. + */ +public class SecretKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public SecretKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + 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) { + 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 + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) 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 + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String keyName = element.getFirstChild().getNodeValue(); + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof SecretKey) { + return (SecretKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "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 + ) throws KeyResolverException { + return null; + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java 2013-06-28 11:35:13.759310003 -0400 @@ -0,0 +1,172 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a single Key based on the KeyName. + */ +public class SingleKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SingleKeyResolver.class.getName()); + + private String keyName; + private PublicKey publicKey; + private PrivateKey privateKey; + private SecretKey secretKey; + + /** + * Constructor. + * @param keyName + * @param publicKey + */ + public SingleKeyResolver(String keyName, PublicKey publicKey) { + this.keyName = keyName; + this.publicKey = publicKey; + } + + /** + * Constructor. + * @param keyName + * @param privateKey + */ + public SingleKeyResolver(String keyName, PrivateKey privateKey) { + this.keyName = keyName; + this.privateKey = privateKey; + } + + /** + * Constructor. + * @param keyName + * @param secretKey + */ + public SingleKeyResolver(String keyName, SecretKey secretKey) { + this.keyName = keyName; + this.secretKey = secretKey; + } + + /** + * 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) { + 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 + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (publicKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return publicKey; + } + } + + log.log(java.util.logging.Level.FINE, "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 + ) 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 + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (secretKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return secretKey; + } + } + + log.log(java.util.logging.Level.FINE, "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 + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (privateKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return privateKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java 2013-06-28 11:35:14.171297179 -0400 @@ -0,0 +1,164 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Iterator; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys and X.509 certificates from a + * dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class X509DigestResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509DigestResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + try { + X509Data x509Data = new X509Data(element, baseURI); + return x509Data.containsDigest(); + } catch (XMLSecurityException e) { + return false; + } + } else { + return false; + } + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + X509Certificate cert = this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + return resolveCertificate(element, baseURI, storage); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** + * Resolves from the storage resolver the actual certificate represented by the digest. + * + * @param element + * @param baseURI + * @param storage + * @return + * @throws XMLSecurityException + */ + private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage) + throws XMLSecurityException { + + XMLX509Digest x509Digests[] = null; + + Element x509childNodes[] = XMLUtils.selectDs11Nodes(element.getFirstChild(), Constants._TAG_X509DIGEST); + + if (x509childNodes == null || x509childNodes.length <= 0) { + return null; + } + + try { + checkStorage(storage); + + x509Digests = new XMLX509Digest[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509Digests[i] = new XMLX509Digest(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate) storageIterator.next(); + + for (int i = 0; i < x509Digests.length; i++) { + XMLX509Digest keyInfoDigest = x509Digests[i]; + byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm()); + + if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found certificate with: " + cert.getSubjectX500Principal().getName()); + } + return cert; + } + + } + } + + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method checkSrorage + * + * @param storage + * @throws KeyResolverException + */ + private void checkStorage(StorageResolver storage) throws KeyResolverException { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509DIGEST }; + KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; + } + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java 2013-06-28 11:35:14.571284728 -0400 @@ -0,0 +1,34 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +/** + * An abstract representation of the result of dereferencing a ds:Reference URI. + */ +public interface ReferenceData { } --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java 2013-06-28 11:35:14.955272776 -0400 @@ -0,0 +1,53 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.Iterator; + +import org.w3c.dom.Node; + +/** + * An abstract representation of a ReferenceData type containing a node-set. + */ +public interface ReferenceNodeSetData extends ReferenceData { + + /** + * Returns a read-only iterator over the nodes contained in this + * NodeSetData in + * + * document order. Attempts to modify the returned iterator + * via the remove method throw + * UnsupportedOperationException. + * + * @return an Iterator over the nodes in this + * NodeSetData in document order + */ + Iterator iterator(); + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java 2013-06-28 11:35:15.347260574 -0400 @@ -0,0 +1,105 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.io.InputStream; + +/** + * A representation of a ReferenceData type containing an OctetStream. + */ +public class ReferenceOctetStreamData implements ReferenceData { + private InputStream octetStream; + private String uri; + private String mimeType; + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + } + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @param uri the URI String identifying the data object (may be + * null) + * @param mimeType the MIME type associated with the data object (may be + * null) + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream, String uri, + String mimeType) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + this.uri = uri; + this.mimeType = mimeType; + } + + /** + * Returns the input stream of this ReferenceOctetStreamData. + * + * @return the input stream of this ReferenceOctetStreamData. + */ + public InputStream getOctetStream() { + return octetStream; + } + + /** + * Returns the URI String identifying the data object represented by this + * ReferenceOctetStreamData. + * + * @return the URI String or null if not applicable + */ + public String getURI() { + return uri; + } + + /** + * Returns the MIME type associated with the data object represented by this + * ReferenceOctetStreamData. + * + * @return the MIME type or null if not applicable + */ + public String getMimeType() { + return mimeType; + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java 2013-06-28 11:35:15.771247376 -0400 @@ -0,0 +1,181 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * A representation of a ReferenceNodeSetData type containing a node-set. + * This is a subtype of NodeSetData that represents a dereferenced + * same-document URI as the root of a subdocument. The main reason is + * for efficiency and performance, as some transforms can operate + * directly on the subdocument and there is no need to convert it + * first to an XPath node-set. + */ +public class ReferenceSubTreeData implements ReferenceNodeSetData { + + private boolean excludeComments; + private Node root; + + public ReferenceSubTreeData(Node root, boolean excludeComments) { + this.root = root; + this.excludeComments = excludeComments; + } + + public Iterator iterator() { + return new DelayedNodeIterator(root, excludeComments); + } + + public Node getRoot() { + return root; + } + + public boolean excludeComments() { + return excludeComments; + } + + /** + * This is an Iterator that contains a backing node-set that is + * not populated until the caller first attempts to advance the iterator. + */ + static class DelayedNodeIterator implements Iterator { + private Node root; + private List nodeSet; + private ListIterator li; + private boolean withComments; + + DelayedNodeIterator(Node root, boolean excludeComments) { + this.root = root; + this.withComments = !excludeComments; + } + + public boolean hasNext() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + return li.hasNext(); + } + + public Node next() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + if (li.hasNext()) { + return li.next(); + } else { + throw new NoSuchElementException(); + } + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Dereferences a same-document URI fragment. + * + * @param node the node (document or element) referenced by the + * URI fragment. If null, returns an empty set. + * @return a set of nodes (minus any comment nodes) + */ + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); + if (node != null) { + nodeSetMinusCommentNodes(node, nodeSet, null); + } + return nodeSet; + } + + /** + * Recursively traverses the subtree, and returns an XPath-equivalent + * node-set of all nodes traversed, excluding any comment nodes, + * if specified. + * + * @param node the node to traverse + * @param nodeSet the set of nodes traversed so far + * @param the previous sibling node + */ + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + nodeSet.add(node); + NamedNodeMap attrs = node.getAttributes(); + if (attrs != null) { + for (int i = 0, len = attrs.getLength(); i < len; i++) { + nodeSet.add(attrs.item(i)); + } + } + Node pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.DOCUMENT_NODE : + pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE: + // emulate XPath which only returns the first node in + // contiguous text/cdata nodes + if (prevSibling != null && + (prevSibling.getNodeType() == Node.TEXT_NODE || + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; + } + nodeSet.add(node); + break; + case Node.PROCESSING_INSTRUCTION_NODE : + nodeSet.add(node); + break; + case Node.COMMENT_NODE: + if (withComments) { + nodeSet.add(node); + } + } + } + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java 2013-06-28 11:35:16.191234303 -0400 @@ -0,0 +1,277 @@ +/* + * 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.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +/** + * This class is extremely useful for loading resources and classes in a fault + * tolerant manner that works across different applications servers. Do not + * touch this unless you're a grizzled classloading guru veteran who is going to + * verify any change on 6 different application servers. + */ +final class ClassLoaderUtils { + + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName()); + + private ClassLoaderUtils() { + } + + /** + * Load a given resource.

      This method will try to load the resource + * using the following methods (in order): + *

        + *
      • From Thread.currentThread().getContextClassLoader() + *
      • From ClassLoaderUtil.class.getClassLoader() + *
      • callingClass.getClassLoader() + *
      + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static URL getResource(String resourceName, Class callingClass) { + URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = + Thread.currentThread().getContextClassLoader().getResource( + resourceName.substring(1) + ); + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (url == null) { + url = cluClassloader.getResource(resourceName); + } + if (url == null && resourceName.startsWith("/")) { + //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 != 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): + *

        + *
      • From Thread.currentThread().getContextClassLoader() + *
      • From ClassLoaderUtil.class.getClassLoader() + *
      • callingClass.getClassLoader() + *
      + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + 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) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = + Thread.currentThread().getContextClassLoader().getResources( + resourceName.substring(1) + ); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (!urls.hasMoreElements()) { + try { + urls = cluClassloader.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = cluClassloader.getResources(resourceName.substring(1)); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + if (!urls.hasMoreElements()) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + try { + urls = cl.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, 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 + */ + static InputStream getResourceAsStream(String resourceName, Class callingClass) { + URL url = getResource(resourceName, callingClass); + + try { + return (url != null) ? url.openStream() : null; + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + return null; + } + } + + /** + * Load a class with a given name.

      It will try to load the class in the + * following order: + *

        + *
      • From Thread.currentThread().getContextClassLoader() + *
      • Using the basic Class.forName() + *
      • From ClassLoaderUtil.class.getClassLoader() + *
      • From the callingClass.getClassLoader() + *
      + * + * @param className The name of the class to load + * @param callingClass The Class object of the calling object + * @throws ClassNotFoundException If the class cannot be found anywhere. + */ + static Class loadClass(String className, Class callingClass) + throws ClassNotFoundException { + try { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + + if (cl != null) { + return cl.loadClass(className); + } + } catch (ClassNotFoundException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + return loadClass2(className, callingClass); + } + + private static Class loadClass2(String className, Class callingClass) + throws ClassNotFoundException { + try { + return Class.forName(className); + } catch (ClassNotFoundException ex) { + try { + if (ClassLoaderUtils.class.getClassLoader() != null) { + return ClassLoaderUtils.class.getClassLoader().loadClass(className); + } + } catch (ClassNotFoundException exc) { + if (callingClass != null && callingClass.getClassLoader() != null) { + return callingClass.getClassLoader().loadClass(className); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + throw ex; + } + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java 2013-06-28 11:35:16.599221603 -0400 @@ -0,0 +1,79 @@ +/* + * 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.utils; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + */ +public class DOMNamespaceContext implements NamespaceContext { + + private Map namespaceMap = new HashMap(); + + public DOMNamespaceContext(Node contextNode) { + addNamespaces(contextNode); + } + + public String getNamespaceURI(String arg0) { + return namespaceMap.get(arg0); + } + + public String getPrefix(String arg0) { + for (String key : namespaceMap.keySet()) { + String value = namespaceMap.get(key); + if (value.equals(arg0)) { + return key; + } + } + return null; + } + + public Iterator getPrefixes(String arg0) { + return namespaceMap.keySet().iterator(); + } + + private void addNamespaces(Node element) { + if (element.getParentNode() != null) { + addNamespaces(element.getParentNode()); + } + if (element instanceof Element) { + Element el = (Element)element; + NamedNodeMap map = el.getAttributes(); + for (int x = 0; x < map.getLength(); x++) { + Attr attr = (Attr)map.item(x); + if ("xmlns".equals(attr.getPrefix())) { + namespaceMap.put(attr.getLocalName(), attr.getValue()); + } + } + } + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java 2013-06-28 11:35:17.011208780 -0400 @@ -0,0 +1,132 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.XMLConstants; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import javax.xml.xpath.XPathFactoryConfigurationException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation for XPath evaluation that uses the JDK API. + */ +public class JDKXPathAPI implements XPathAPI { + + private XPathFactory xpf; + + private String xpathStr; + + private XPathExpression xpathExpression; + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN); + return result.booleanValue(); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpathExpression = null; + xpf = null; + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java 2013-06-28 11:35:17.415196204 -0400 @@ -0,0 +1,37 @@ +/* + * 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.utils; + + +/** + * A Factory to return a JDKXPathAPI instance. + */ +public class JDKXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new JDKXPathAPI(); + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java 2013-06-28 11:35:17.827183380 -0400 @@ -0,0 +1,70 @@ +/* + * 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.utils; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Class SignatureElementProxy + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public abstract class Signature11ElementProxy extends ElementProxy { + + protected Signature11ElementProxy() { + }; + + /** + * Constructor Signature11ElementProxy + * + * @param doc + */ + public Signature11ElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignature11Space(this.doc, this.getBaseLocalName()); + } + + /** + * Constructor Signature11ElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Signature11ElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpec11NS; + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java 2013-06-28 11:35:18.239170556 -0400 @@ -0,0 +1,66 @@ +/* + * 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.utils; + +import javax.xml.transform.TransformerException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An interface to abstract XPath evaluation + */ +public interface XPathAPI { + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException; + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException; + + /** + * Clear any context information from this object + */ + void clear(); + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java 2013-06-28 11:35:18.643157981 -0400 @@ -0,0 +1,71 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return an XPathAPI instance. If Xalan is available it returns XalanXPathAPI. If not, then + * it returns JDKXPathAPI. + */ +public abstract class XPathFactory { + + private static boolean xalanInstalled; + + static { + try { + Class funcTableClass = + ClassLoaderUtils.loadClass("com.sun.org.apache.xpath.internal.compiler.FunctionTable", XPathFactory.class); + if (funcTableClass != null) { + xalanInstalled = true; + } + } catch (Exception e) { + //ignore + } + } + + protected synchronized static boolean isXalanInstalled() { + return xalanInstalled; + } + + /** + * Get a new XPathFactory instance + */ + public static XPathFactory newInstance() { + if (!isXalanInstalled()) { + return new JDKXPathFactory(); + } + // Xalan is available + if (XalanXPathAPI.isInstalled()) { + return new XalanXPathFactory(); + } + // Some problem was encountered in fixing up the Xalan FunctionTable so fall back to the + // JDK implementation + return new JDKXPathFactory(); + } + + /** + * Get a new XPathAPI instance + */ + public abstract XPathAPI newXPathAPI(); + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java 2013-06-28 11:35:19.055145157 -0400 @@ -0,0 +1,210 @@ +/* + * 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.utils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.SourceLocator; +import javax.xml.transform.TransformerException; + +import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; +import com.sun.org.apache.xml.internal.utils.PrefixResolver; +import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; +import com.sun.org.apache.xpath.internal.Expression; +import com.sun.org.apache.xpath.internal.XPath; +import com.sun.org.apache.xpath.internal.XPathContext; +import com.sun.org.apache.xpath.internal.compiler.FunctionTable; +import com.sun.org.apache.xpath.internal.objects.XObject; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation of XPathAPI using Xalan. This supports the "here()" function defined in the digital + * signature spec. + */ +public class XalanXPathAPI implements XPathAPI { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName()); + + private String xpathStr = null; + + private XPath xpath = null; + + private static FunctionTable funcTable = null; + + private static boolean installed; + + private XPathContext context; + + static { + fixupFunctionTable(); + } + + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + + // Execute the XPath, and have it return the result + XObject list = eval(contextNode, xpathnode, str, namespaceNode); + + // Return a NodeList. + return list.nodelist(); + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + XObject object = eval(contextNode, xpathnode, str, namespaceNode); + return object.bool(); + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpath = null; + context = null; + } + + public synchronized static boolean isInstalled() { + return installed; + } + + private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (context == null) { + context = new XPathContext(xpathnode); + context.setSecureProcessing(true); + } + + // Create an object to resolve namespace prefixes. + // XPath namespaces are resolved from the input context node's document element + // if it is a root node, or else the current context node (for lack of a better + // resolution space, given the simplicity of this sample code). + Node resolverNode = + (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) + ? ((Document) namespaceNode).getDocumentElement() : namespaceNode; + PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode); + + if (!str.equals(xpathStr)) { + if (str.indexOf("here()") > 0) { + context.reset(); + } + xpath = createXPath(str, prefixResolver); + xpathStr = str; + } + + // Execute the XPath, and have it return the result + int ctxtNode = context.getDTMHandleFromNode(contextNode); + + return xpath.execute(context, ctxtNode, prefixResolver); + } + + private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { + XPath xpath = null; + Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, + ErrorListener.class, FunctionTable.class}; + Object[] objects = + new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable}; + try { + Constructor constructor = XPath.class.getConstructor(classes); + xpath = (XPath) constructor.newInstance(objects); + } catch (Exception ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + if (xpath == null) { + xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); + } + return xpath; + } + + private synchronized static void fixupFunctionTable() { + installed = false; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Registering Here function"); + } + /** + * Try to register our here() implementation as internal function. + */ + try { + Class[] args = {String.class, Expression.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { + Object[] params = {"here", new FuncHere()}; + installFunction.invoke(null, params); + installed = true; + } + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + if (!installed) { + try { + funcTable = new FunctionTable(); + Class[] args = {String.class, Class.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + Object[] params = {"here", FuncHere.class}; + installFunction.invoke(funcTable, params); + installed = true; + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + if (installed) { + log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } else { + log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } + } + } + +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java 2013-06-28 11:35:19.491131586 -0400 @@ -0,0 +1,37 @@ +/* + * 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.utils; + + +/** + * A Factory to return a XalanXPathAPI instance. + */ +public class XalanXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new XalanXPathAPI(); + } +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java 2013-06-28 11:35:19.915118388 -0400 @@ -0,0 +1,43 @@ +/* + * 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.utils.resolver; + +import org.w3c.dom.Attr; + +public class ResourceResolverContext { + + public ResourceResolverContext(Attr attr, String baseUri, boolean secureValidation) { + this.attr = attr; + this.baseUri = baseUri; + this.secureValidation = secureValidation; + this.uriToResolve = attr != null ? attr.getValue() : null; + } + + public final String uriToResolve; + + public final boolean secureValidation; + + public final String baseUri; + + public final Attr attr; +} --- /dev/null 2013-06-17 12:00:06.077797872 -0400 +++ new/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java 2013-06-28 11:35:20.311106062 -0400 @@ -0,0 +1,218 @@ +/* + * 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 org.jcp.xml.dsig.internal.dom; + +import java.security.Key; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMCryptoContext; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.SignedInfo; +import javax.xml.crypto.dsig.XMLSignature; +import javax.xml.crypto.dsig.XMLSignatureException; +import javax.xml.crypto.dsig.XMLSignContext; +import javax.xml.crypto.dsig.XMLValidateContext; +import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * An abstract class representing a SignatureMethod. Subclasses implement + * a specific XML DSig signature algorithm. + */ +abstract class AbstractDOMSignatureMethod extends DOMStructure + implements SignatureMethod { + + // denotes the type of signature algorithm + enum Type { DSA, RSA, ECDSA, HMAC } + + /** + * Verifies the passed-in signature with the specified key, using the + * underlying Signature or Mac algorithm. + * + * @param key the verification key + * @param si the SignedInfo + * @param sig the signature bytes to be verified + * @param context the XMLValidateContext + * @return true if the signature verified successfully, + * false if not + * @throws NullPointerException if key, si or + * sig are null + * @throws InvalidKeyException if the key is improperly encoded, of + * the wrong type, or parameters are missing, etc + * @throws SignatureException if an unexpected error occurs, such + * as the passed in signature is improperly encoded + * @throws XMLSignatureException if an unexpected error occurs + */ + abstract boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException; + + /** + * Signs the bytes with the specified key, using the underlying + * Signature or Mac algorithm. + * + * @param key the signing key + * @param si the SignedInfo + * @param context the XMLSignContext + * @return the signature + * @throws NullPointerException if key or + * si are null + * @throws InvalidKeyException if the key is improperly encoded, of + * the wrong type, or parameters are missing, etc + * @throws XMLSignatureException if an unexpected error occurs + */ + abstract byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException; + + /** + * Returns the java.security.Signature or javax.crypto.Mac standard + * algorithm name. + */ + abstract String getJCAAlgorithm(); + + /** + * Returns the type of signature algorithm. + */ + abstract Type getAlgorithmType(); + + /** + * This method invokes the {@link #marshalParams marshalParams} + * method to marshal any algorithm-specific parameters. + */ + public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) + throws MarshalException + { + Document ownerDoc = DOMUtils.getOwnerDocument(parent); + + Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod", + XMLSignature.XMLNS, dsPrefix); + DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm()); + + if (getParameterSpec() != null) { + marshalParams(smElem, dsPrefix); + } + + parent.appendChild(smElem); + } + + /** + * Marshals the algorithm-specific parameters to an Element and + * appends it to the specified parent element. By default, this method + * throws an exception since most SignatureMethod algorithms do not have + * parameters. Subclasses should override it if they have parameters. + * + * @param parent the parent element to append the parameters to + * @param paramsPrefix the algorithm parameters prefix to use + * @throws MarshalException if the parameters cannot be marshalled + */ + void marshalParams(Element parent, String paramsPrefix) + throws MarshalException + { + throw new MarshalException("no parameters should " + + "be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + + /** + * Unmarshals SignatureMethodParameterSpec from the specified + * Element. By default, this method throws an exception since + * most SignatureMethod algorithms do not have parameters. Subclasses should + * override it if they have parameters. + * + * @param paramsElem the Element holding the input params + * @return the algorithm-specific SignatureMethodParameterSpec + * @throws MarshalException if the parameters cannot be unmarshalled + */ + SignatureMethodParameterSpec unmarshalParams(Element paramsElem) + throws MarshalException + { + throw new MarshalException("no parameters should " + + "be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + + /** + * Checks if the specified parameters are valid for this algorithm. By + * default, this method throws an exception if parameters are specified + * since most SignatureMethod algorithms do not have parameters. Subclasses + * should override it if they have parameters. + * + * @param params the algorithm-specific params (may be null) + * @throws InvalidAlgorithmParameterException if the parameters are not + * appropriate for this signature method + */ + void checkParams(SignatureMethodParameterSpec params) + throws InvalidAlgorithmParameterException + { + if (params != null) { + throw new InvalidAlgorithmParameterException("no parameters " + + "should be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + } + + @Override + public boolean equals(Object o) + { + if (this == o) { + return true; + } + + if (!(o instanceof SignatureMethod)) { + return false; + } + SignatureMethod osm = (SignatureMethod)o; + + return (getAlgorithm().equals(osm.getAlgorithm()) && + paramsEqual(osm.getParameterSpec())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + + /** + * Returns true if parameters are equal; false otherwise. + * + * Subclasses should override this method to compare algorithm-specific + * parameters. + */ + boolean paramsEqual(AlgorithmParameterSpec spec) + { + return (getParameterSpec() == spec); + } +} --- old/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties 2013-06-28 11:35:20.891088008 -0400 +++ /dev/null 2013-06-17 12:00:06.077797872 -0400 @@ -1,36 +0,0 @@ -# ------------------------------------------------------------------------ -# -# Logging Configuration -# -# ------------------------------------------------------------------------ -# -log4j.rootLogger=DEBUG, LOGTXT - -######################################################################## -# -# Logging based on packages -# -######################################################################## -log4j.logger.com.sun.org.apache.xml.internal.security=DEBUG, LOGTXT -log4j.logger.com.sun.org.apache.xml.internal.security.test.AllTests=DEBUG, LOGTXT - -######################################################################## -# -# Logfile definitions -# -######################################################################## -#Console Log -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.Threshold=DEBUG -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%-5p %C{1}:%L - %m\n -log4j.appender.Console.Target=System.err - -#LOGTXT Log -log4j.appender.LOGTXT=org.apache.log4j.FileAppender -log4j.appender.LOGTXT.File=log.txt -log4j.appender.LOGTXT.Append=true -log4j.appender.LOGTXT.Threshold=DEBUG -log4j.appender.LOGTXT.layout=org.apache.log4j.PatternLayout -log4j.appender.LOGTXT.layout.ConversionPattern=%-5p %C{1}:%L - %m\n - --- old/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java 2013-06-28 11:35:21.167079417 -0400 +++ /dev/null 2013-06-17 12:00:06.077797872 -0400 @@ -1,143 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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.transforms.implementations; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.XPathContext; -import org.w3c.dom.Node; - - -/** - * {@link FuncHereContext} extends {@link XPathContext} for supplying context - * for the here() function. The here() function needs to know - * where in an XML instance the XPath text string appeared. This can be - * in {@link org.w3c.dom.Text}, {@link org.w3c.dom.Attr}ibutes and {@ProcessingInstrinction} nodes. The - * correct node must be supplied to the constructor of {@link FuncHereContext}. - * The supplied Node MUST contain the XPath which is to be executed. - * - *
      - * From: Scott_Boag\@lotus.com
      - * To: Christian Geuer-Pollmann 
      - * CC: xalan-dev@xml.apache.org
      - * Subject: Re: Cleanup of XPathContext & definition of XSLTContext
      - * Date: Tue, 21 Aug 2001 18:36:24 -0400
      - *
      - * > My point is to say to get this baby to run, the XPath must have a
      - * > possibility to retrieve the information where itself occured in a
      - * > document.
      - *
      - * It sounds to me like you have to derive an XMLSigContext from the
      - * XPathContext?
      - *
      - * > and supplied the Node which contains the xpath string as "owner". Question:
      - * > Is this the correct use of the owner object? It works, but I don't know
      - * > whether this is correct from the xalan-philosophy...
      - *
      - * Philosophically it's fine.  The owner is the TransformerImpl if XPath is
      - * running under XSLT.  If it is not running under XSLT, it can be whatever
      - * you want.
      - *
      - * -scott
      - * 
      - * - * @author $Author: mullan $ - * @see com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere - * @see com.sun.org.apache.xml.internal.security.utils.XPathFuncHereAPI - * @see XML Signature - The here() function - */ -public class FuncHereContext extends XPathContext { - - /** - * This constuctor is disabled because if we use the here() function we - * always need to know in which node the XPath occured. - */ - private FuncHereContext() {} - - /** - * Constructor FuncHereContext - * - * @param owner - */ - public FuncHereContext(Node owner) { - super(owner); - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param xpathContext - */ - public FuncHereContext(Node owner, XPathContext xpathContext) { - - super(owner); - - try { - super.m_dtmManager = xpathContext.getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param previouslyUsed - */ - public FuncHereContext(Node owner, CachedXPathAPI previouslyUsed) { - - super(owner); - - try { - super.m_dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param dtmManager - */ - public FuncHereContext(Node owner, DTMManager dtmManager) { - - super(owner); - - try { - super.m_dtmManager = dtmManager; - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } -} --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java 2013-06-28 11:35:21.507068834 -0400 +++ /dev/null 2013-06-17 12:00:06.077797872 -0400 @@ -1,65 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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.utils; - -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import org.w3c.dom.Document; - -/** - * @author Raul Benito - */ -public class CachedXPathAPIHolder { - - static ThreadLocal local=new ThreadLocal(); - static ThreadLocal localDoc=new ThreadLocal(); - - /** - * Sets the doc for the xpath transformation. Resets the cache if needed - * @param doc - */ - public static void setDoc(Document doc) { - if (localDoc.get()!=doc) { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(doc); - return; - } - //Different docs reset. - cx.getXPathContext().reset(); - localDoc.set(doc); - } - } - - /** - * @return the cachexpathapi for this thread - */ - public static CachedXPathAPI getCachedXPathAPI() { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(null); - } - return cx; - } -} --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java 2013-06-28 11:35:21.855058003 -0400 +++ /dev/null 2013-06-17 12:00:06.077797872 -0400 @@ -1,466 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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.utils; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.Expression; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.XPathContext; -import com.sun.org.apache.xpath.internal.compiler.FunctionTable; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.*; -import org.w3c.dom.traversal.NodeIterator; - -import javax.xml.transform.ErrorListener; -import javax.xml.transform.SourceLocator; -import javax.xml.transform.TransformerException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * - * @author $Author: mullan $ - */ -public class CachedXPathFuncHereAPI { - - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(CachedXPathFuncHereAPI.class.getName()); - /** - * XPathContext, and thus DTMManager and DTMs, persists through multiple - * calls to this object. - */ - FuncHereContext _funcHereContext = null; - - /** Field _dtmManager */ - DTMManager _dtmManager = null; - - XPathContext _context = null; - - String xpathStr=null; - - XPath xpath=null; - - static FunctionTable _funcTable = null; - - static { - fixupFunctionTable(); - } - - /** - * Method getFuncHereContext - * @return the context for this object - * - */ - public FuncHereContext getFuncHereContext() { - return this._funcHereContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - */ - private CachedXPathFuncHereAPI() {} - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param existingXPathContext - */ - public CachedXPathFuncHereAPI(XPathContext existingXPathContext) { - this._dtmManager = existingXPathContext.getDTMManager(); - this._context=existingXPathContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param previouslyUsed - */ - public CachedXPathFuncHereAPI(CachedXPathAPI previouslyUsed) { - this._dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - this._context=previouslyUsed.getXPathContext(); - } - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeIterator selectNodeIterator(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, getStrFromNode(xpathnode), namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, getStrFromNode(xpathnode), contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeList selectNodeList( - Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, str, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, getStrFromNode(xpathnode),contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - xpath = createXPath(str, prefixResolver); - xpathStr=str; - } - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval( - Node contextNode, Node xpathnode, String str, PrefixResolver prefixResolver) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - try { - xpath = createXPath(str, prefixResolver); - } catch (TransformerException ex) { - //Try to see if it is a problem with the classloader. - Throwable th= ex.getCause(); - if (th instanceof ClassNotFoundException) { - if (th.getMessage().indexOf("FuncHere")>0) { - throw new RuntimeException(I18n.translate("endorsed.jdk1.4.0")/*,*/+ex); - } - } - throw ex; - } - xpathStr=str; - } - - // Execute the XPath, and have it return the result - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { - XPath xpath = null; - Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, - ErrorListener.class, FunctionTable.class}; - Object[] objects = new Object[]{str, null, prefixResolver, new Integer(XPath.SELECT), null, _funcTable}; - try { - Constructor constructor = XPath.class.getConstructor(classes); - xpath = constructor.newInstance(objects); - } catch (Throwable t) { - } - if (xpath == null) { - xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - } - return xpath; - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string for the node. - */ - public static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - - // we iterate over all siblings of the context node because eventually, - // the text is "polluted" with pi's or comments - StringBuffer sb = new StringBuffer(); - - for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); - currentSibling != null; - currentSibling = currentSibling.getNextSibling()) { - if (currentSibling.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) currentSibling).getData()); - } - } - - return sb.toString(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return null; - } - - private static void fixupFunctionTable() { - boolean installed = false; - log.log(java.util.logging.Level.INFO, "Registering Here function"); - /** - * Try to register our here() implementation as internal function. - */ - try { - Class []args = {String.class, Expression.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { - Object []params = {"here", new FuncHere()}; - installFunction.invoke(null, params); - installed = true; - } - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - if(!installed) { - try { - _funcTable = new FunctionTable(); - Class []args = {String.class, Class.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - Object []params = {"here", FuncHere.class}; - installFunction.invoke(_funcTable, params); - installed = true; - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - if (installed) { - log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } else { - log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } - } - } -} --- old/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java 2013-06-28 11:35:22.139049163 -0400 +++ /dev/null 2013-06-17 12:00:06.077797872 -0400 @@ -1,306 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed 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.utils; - - - -import javax.xml.transform.TransformerException; - -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.traversal.NodeIterator; - - - - -/** - * This class does the same as {@link com.sun.org.apache.xpath.internal.XPathAPI} except that the XPath strings - * are not supplied as Strings but as {@link Text}, {@link Attr}ibute or - * {ProcessingInstruction} nodes which contain the XPath string. This enables - * us to use the here() function. - *
      - * The methods in this class are convenience methods into the low-level XPath API. - * These functions tend to be a little slow, since a number of objects must be - * created for each evaluation. A faster way is to precompile the - * XPaths using the low-level API, and then just use the XPaths - * over and over. - * - * @author $Author: mullan $ - * @see XPath Specification - */ -public class XPathFuncHereAPI { - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode) throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - String str = getStrFromNode(xpathnode); - - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, PrefixResolver prefixResolver) - throws TransformerException { - - String str = getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string from the node - */ - private static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - return ((Text) xpathnode).getData(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return ""; - } -}