OpenJDK / bsd-port / jdk9 / jdk
changeset 7636:028ef97797c1
8011547: Update XML Signature implementation to Apache Santuario 1.5.4
Reviewed-by: xuelei
line wrap: on
line diff
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,82 +2,78 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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) { + /** + * + * @param doc + * @param algorithmURI is the URI of the algorithm as String + */ + public Algorithm(Document doc, String algorithmURI) { + super(doc); - super(doc); + this.setAlgorithmURI(algorithmURI); + } - this.setAlgorithmURI(algorithmURI); - } + /** + * Constructor Algorithm + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Algorithm(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * 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); + } - /** - * 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); - } - } + /** + * 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 + ); + } + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Fri Jul 05 15:54:42 2013 -0400 @@ -115,6 +115,18 @@ 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") ); @@ -155,6 +167,18 @@ new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256) ); algorithmsMap.put( + 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") ); @@ -163,6 +187,10 @@ new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") ); algorithmsMap.put( + XMLCipher.RSA_OAEP_11, + new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport") + ); + algorithmsMap.put( XMLCipher.DIFFIE_HELLMAN, new Algorithm("", "", "KeyAgreement") );
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,265 +2,254 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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. * * <pre> * MessageDigestAlgorithm.getInstance() * </pre> - * */ 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"; + 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; + /** 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 messageDigest - * @param algorithmURI - */ - private MessageDigestAlgorithm(Document doc, MessageDigest messageDigest, - String algorithmURI) { + /** + * 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); - super(doc, algorithmURI); + algorithm = getDigestInstance(algorithmURI); + } - this.algorithm = messageDigest; - } + /** + * 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); + } - static ThreadLocal<Map<String, MessageDigest>> instances=new - ThreadLocal<Map<String, MessageDigest>>() { - protected Map<String, MessageDigest> initialValue() { - return new HashMap<String, MessageDigest>(); - }; - }; + private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { + String algorithmID = JCEMapper.translateURItoJCEID(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 { - MessageDigest md = getDigestInstance(algorithmURI); - return new MessageDigestAlgorithm(doc, md, algorithmURI); - } + if (algorithmID == null) { + Object[] exArgs = { algorithmURI }; + throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); + } -private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { - MessageDigest result= instances.get().get(algorithmURI); - if (result!=null) - return result; - String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); + 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() }; - if (algorithmID == null) { - Object[] exArgs = { algorithmURI }; - throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); - } + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - 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); + } - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; + return md; + } - 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 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; + } } - - /** - * 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; - } -}
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Fri Jul 05 15:54:42 2013 -0400 @@ -74,7 +74,7 @@ this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -92,10 +92,10 @@ 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); } /** @@ -136,7 +136,7 @@ } signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -310,7 +310,7 @@ * @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); } /** @@ -380,9 +380,7 @@ * 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 ); @@ -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(
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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 <code>Transformation algorithm</code> - * - * @return the URI representation of <code>Transformation algorithm</code> - */ - protected abstract String engineGetURI(); + /** + * Returns the URI representation of <code>Transformation algorithm</code> + * + * @return the URI representation of <code>Transformation algorithm</code> + */ + 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(); + /** + * 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(); + /** + * 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[])} - * 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#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)} + * 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 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 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; + /** + * 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; + /** + * 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#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; + /** + * 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 engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + } - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - * @throws XMLSignatureException - */ - protected abstract void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException; + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + * @throws XMLSignatureException + */ + protected abstract void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException; public void reset() { - } + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IntegrityHmac.class.getName()); - /** - * Method engineGetURI - * - *@inheritDoc - */ - public abstract String engineGetURI(); + /** Field macAlgorithm */ + private Mac macAlgorithm = null; - /** - * Returns the output length of the hash/digest. - */ - abstract int getDigestLength(); + /** Field HMACOutputLength */ + private int HMACOutputLength = 0; + private boolean HMACOutputLengthSet = false; - /** Field _macAlgorithm */ - private Mac _macAlgorithm = null; - private boolean _HMACOutputLengthSet = false; + /** + * Method engineGetURI + * + *@inheritDoc + */ + public abstract String engineGetURI(); - /** Field _HMACOutputLength */ - int _HMACOutputLength = 0; + /** + * Returns the output length of the hash/digest. + */ + abstract int getDigestLength(); - /** - * Method IntegrityHmacSHA1das - * - * @throws XMLSignatureException - */ - public IntegrityHmac() throws XMLSignatureException { + /** + * 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); + } - 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() }; - try { - this._macAlgorithm = Mac.getInstance(algorithmID); - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } - 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"); + } - /** - * 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(); + } - 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()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + byte[] completeResult = this.macAlgorithm.doFinal(); + return MessageDigestAlgorithm.isEqual(completeResult, signature); + } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * 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 { + /** + * 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 }; - 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()); - } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - byte[] completeResult = this._macAlgorithm.doFinal(); - return MessageDigestAlgorithm.isEqual(completeResult, signature); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - /** - * 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) { + 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 { + /** + * 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(); + } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - 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()); - } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - return this._macAlgorithm.doFinal(); - } - } 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 }; - /** - * Method reduceBitLength - * - * @param completeResult - * @return the reduced bits. - * @param length - * - */ - private static byte[] reduceBitLength(byte completeResult[], int length) { + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - int bytes = length / 8; - int abits = length % 8; - byte[] strippedResult = new byte[bytes + ((abits == 0) - ? 0 - : 1)]; + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - System.arraycopy(completeResult, 0, strippedResult, 0, bytes); + /** + * 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 }; - if (abits > 0) { - byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, - (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE }; + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]); - } + try { + this.macAlgorithm.init(secretKey, algorithmParameterSpec); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } - return strippedResult; - } + /** + * Method engineInitSign + * + * @param secretKey + * @param secureRandom + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey, SecureRandom secureRandom) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); + } - /** - * Method engineInitSign - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey) 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 void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this.macAlgorithm.update(input); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * 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); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * 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); + } + } - try { - this._macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Method engineGetJCEAlgorithmString + * @inheritDoc + * + */ + protected String engineGetJCEAlgorithmString() { + return this.macAlgorithm.getAlgorithm(); + } - /** - * Method engineInitSign - * - * @param secretKey - * @param algorithmParameterSpec - * @throws XMLSignatureException - */ - protected void engineInitSign( - Key secretKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { + /** + * Method engineGetJCEAlgorithmString + * + * @inheritDoc + */ + protected String engineGetJCEProviderName() { + return this.macAlgorithm.getProvider().getName(); + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + */ + protected void engineSetHMACOutputLength(int HMACOutputLength) { + this.HMACOutputLength = HMACOutputLength; + this.HMACOutputLengthSet = true; + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + super.engineGetContextFromElement(element); - try { - this._macAlgorithm.init(secretKey, algorithmParameterSpec); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (element == null) { + throw new IllegalArgumentException("element null"); + } - /** - * Method engineInitSign - * - * @param secretKey - * @param secureRandom - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey, SecureRandom secureRandom) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); - } + Text hmaclength = + XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); - /** - * 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 { + if (hmaclength != null) { + this.HMACOutputLength = Integer.parseInt(hmaclength.getData()); + this.HMACOutputLengthSet = true; + } + } - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Method engineAddContextToElement + * + * @param element + */ + public void engineAddContextToElement(Element element) { + if (element == null) { + throw new IllegalArgumentException("null element"); + } - /** - * 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 { + if (this.HMACOutputLengthSet) { + Document doc = element.getOwnerDocument(); + Element HMElem = + XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); + Text HMText = + doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + HMElem.appendChild(HMText); + XMLUtils.addReturnToElement(element); + element.appendChild(HMElem); + XMLUtils.addReturnToElement(element); + } + } - /** - * 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 { + /** + * Class IntegrityHmacSHA1 + */ + public static class IntegrityHmacSHA1 extends IntegrityHmac { - try { - this._macAlgorithm.update(buf, offset, len); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Constructor IntegrityHmacSHA1 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA1() throws XMLSignatureException { + super(); + } - /** - * Method engineGetJCEAlgorithmString - * @inheritDoc - * - */ - protected String engineGetJCEAlgorithmString() { + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; + } - log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); + int getDigestLength() { + return 160; + } + } - return this._macAlgorithm.getAlgorithm(); - } + /** + * Class IntegrityHmacSHA256 + */ + public static class IntegrityHmacSHA256 extends IntegrityHmac { - /** - * Method engineGetJCEAlgorithmString - * - * @inheritDoc - */ - protected String engineGetJCEProviderName() { - return this._macAlgorithm.getProvider().getName(); - } + /** + * Constructor IntegrityHmacSHA256 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA256() throws XMLSignatureException { + super(); + } - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - */ - protected void engineSetHMACOutputLength(int HMACOutputLength) { - this._HMACOutputLength = HMACOutputLength; - this._HMACOutputLengthSet = true; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; + } - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { + int getDigestLength() { + return 256; + } + } - super.engineGetContextFromElement(element); + /** + * Class IntegrityHmacSHA384 + */ + public static class IntegrityHmacSHA384 extends IntegrityHmac { - if (element == null) { - throw new IllegalArgumentException("element null"); - } + /** + * Constructor IntegrityHmacSHA384 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA384() throws XMLSignatureException { + super(); + } - Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), - Constants._TAG_HMACOUTPUTLENGTH,0); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; + } - if (hmaclength != null) { - this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); - this._HMACOutputLengthSet = true; - } + int getDigestLength() { + return 384; + } + } - } + /** + * Class IntegrityHmacSHA512 + */ + public static class IntegrityHmacSHA512 extends IntegrityHmac { - /** - * Method engineAddContextToElement - * - * @param element - */ - public void engineAddContextToElement(Element element) { + /** + * Constructor IntegrityHmacSHA512 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA512() throws XMLSignatureException { + super(); + } - if (element == null) { - throw new IllegalArgumentException("null element"); - } + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; + } - if (this._HMACOutputLengthSet) { - Document doc = element.getOwnerDocument(); - Element HMElem = XMLUtils.createElementInSignatureSpace(doc, - Constants._TAG_HMACOUTPUTLENGTH); - Text HMText = - doc.createTextNode(new Integer(this._HMACOutputLength).toString()); + int getDigestLength() { + return 512; + } + } - HMElem.appendChild(HMText); - XMLUtils.addReturnToElement(element); - element.appendChild(HMElem); - XMLUtils.addReturnToElement(element); - } - } + /** + * Class IntegrityHmacRIPEMD160 + */ + public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - /** - * Class IntegrityHmacSHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA1 extends IntegrityHmac { + /** + * Constructor IntegrityHmacRIPEMD160 + * + * @throws XMLSignatureException + */ + public IntegrityHmacRIPEMD160() throws XMLSignatureException { + super(); + } - /** - * Constructor IntegrityHmacSHA1 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA1() throws XMLSignatureException { - super(); - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; + } - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; - } + int getDigestLength() { + return 160; + } + } - int getDigestLength() { - return 160; - } - } + /** + * Class IntegrityHmacMD5 + */ + public static class IntegrityHmacMD5 extends IntegrityHmac { - /** - * Class IntegrityHmacSHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA256 extends IntegrityHmac { + /** + * Constructor IntegrityHmacMD5 + * + * @throws XMLSignatureException + */ + public IntegrityHmacMD5() throws XMLSignatureException { + super(); + } - /** - * Constructor IntegrityHmacSHA256 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA256() throws XMLSignatureException { - super(); - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; + } - /** - * 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; - } - } + int getDigestLength() { + return 128; + } + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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,32 +100,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); } @@ -140,7 +131,7 @@ /** @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 {
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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 <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { + private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { byte rLength = asn1Bytes[3]; int i; @@ -294,19 +280,18 @@ 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; } @@ -323,8 +308,7 @@ * @throws IOException * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> */ - 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"); } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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; + /** 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 <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> - * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A> - */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { + /** + * 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 <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> + * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A> + */ + public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { - byte rLength = asn1Bytes[3]; - int i; + 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"); + } - for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); + byte rLength = asn1Bytes[offset + 1]; + int i; - byte sLength = asn1Bytes[5 + rLength]; - int j; + for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--); - for (j = sLength; - (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); + byte sLength = asn1Bytes[offset + 2 + rLength + 1]; + int 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]; + for (j = sLength; + (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--); - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, - i); - System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 48 - j, j); + int rawLen = Math.max(i, j); - return xmldsigBytes; - } + 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]; - /** - * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. - * - * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param xmldsigBytes - * @return the encoded ASN.1 bytes - * - * @throws IOException - * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> - * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A> - */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { + 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); - if (xmldsigBytes.length != 48) { - throw new IOException("Invalid XMLDSIG format of ECDSA signature"); - } + return xmldsigBytes; + } - int i; + /** + * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * + * @throws IOException + * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A> + * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A> + */ + public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { - for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); + int rawLen = xmldsigBytes.length/2; - int j = i; + int i; - if (xmldsigBytes[24 - i] < 0) { - j += 1; - } + for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--); - int k; + int j = i; - for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); + if (xmldsigBytes[rawLen - i] < 0) { + j += 1; + } - int l = k; + int k; - if (xmldsigBytes[48 - k] < 0) { - l += 1; - } + for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--); - byte asn1Bytes[] = new byte[6 + j + l]; + int l = k; - asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); - asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; + if (xmldsigBytes[2*rawLen - k] < 0) { + l += 1; + } - System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i); + 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; - asn1Bytes[4 + j] = 2; - asn1Bytes[5 + j] = (byte) l; + System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i); - System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); + offset += j; - return asn1Bytes; - } + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) l; - /** - * Constructor SignatureRSA - * - * @throws XMLSignatureException - */ - public SignatureECDSA() throws XMLSignatureException { + System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k); - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + return asn1Bytes; + } - 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() }; + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureECDSA() throws XMLSignatureException { - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + 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() }; - /** @inheritDoc */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } - /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + try { + this.signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } - try { - byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + /** @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)); + 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); - } - } + 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 { + /** @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 }; + 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); - } catch (InvalidKeyException ex) { + 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 { + /** @inheritDoc */ + protected byte[] engineSign() throws XMLSignatureException { + try { + byte jcebytes[] = this.signatureAlgorithm.sign(); - 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); + } + } - 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 }; - /** @inheritDoc */ - protected void engineInitSign(Key privateKey, SecureRandom secureRandom) - throws XMLSignatureException { + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** @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 }; - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey, - secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { + try { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** @inheritDoc */ + protected void engineUpdate(byte[] input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** @inheritDoc */ + protected void engineUpdate(byte input) throws XMLSignatureException { + try { + this.signatureAlgorithm.update(input); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } + } - try { - this._signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException 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 void engineUpdate(byte[] input) throws XMLSignatureException { + /** @inheritDoc */ + protected String engineGetJCEAlgorithmString() { + return this.signatureAlgorithm.getAlgorithm(); + } - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected String engineGetJCEProviderName() { + return this.signatureAlgorithm.getProvider().getName(); + } - /** @inheritDoc */ - protected void engineUpdate(byte input) throws XMLSignatureException { + /** @inheritDoc */ + protected void engineSetHMACOutputLength(int HMACOutputLength) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); + } - try { - this._signatureAlgorithm.update(input); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + protected void engineInitSign( + Key signingKey, AlgorithmParameterSpec algorithmParameterSpec + ) throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA"); + } - /** @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + /** + * Class SignatureRSASHA1 + * + * @author $Author: marcx $ + */ + public static class SignatureECDSASHA1 extends SignatureECDSA { + /** + * Constructor SignatureRSASHA1 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA1() throws XMLSignatureException { + super(); + } - try { - this._signatureAlgorithm.update(buf, offset, len); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; + } + } - /** @inheritDoc */ - protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); - } + /** + * Class SignatureRSASHA256 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA256 extends SignatureECDSA { - /** @inheritDoc */ - protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); - } + /** + * Constructor SignatureRSASHA256 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA256() throws XMLSignatureException { + super(); + } - /** @inheritDoc */ - protected void engineSetHMACOutputLength(int HMACOutputLength) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256; + } + } - /** @inheritDoc */ - protected void engineInitSign( - Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { - throw new XMLSignatureException( - "algorithms.CannotUseAlgorithmParameterSpecOnRSA"); - } + /** + * Class SignatureRSASHA384 + * + * @author Alex Dupre + */ + public static class SignatureECDSASHA384 extends SignatureECDSA { - /** - * Class SignatureRSASHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.2 $ - */ - public static class SignatureECDSASHA1 extends SignatureECDSA { + /** + * Constructor SignatureRSASHA384 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA384() throws XMLSignatureException { + super(); + } - /** - * Constructor SignatureRSASHA1 - * - * @throws XMLSignatureException - */ - public SignatureECDSASHA1() throws XMLSignatureException { - super(); - } + /** @inheritDoc */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384; + } + } - /** @inheritDoc */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; - } - } + /** + * 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; + } + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - 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; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor CanonicalizationException - * - */ - public CanonicalizationException() { - super(); - } + /** + * Constructor CanonicalizationException + * + */ + public CanonicalizationException() { + super(); + } - /** - * Constructor CanonicalizationException - * - * @param _msgID - */ - public CanonicalizationException(String _msgID) { - super(_msgID); - } + /** + * 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 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 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); - } + /** + * Constructor CanonicalizationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public CanonicalizationException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java Fri Jul 05 15:54:42 2013 -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; @@ -91,6 +92,11 @@ */ public static final String ALGO_ID_C14N11_WITH_COMMENTS = ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; + /** + * Non-standard algorithm to serialize the physical representation for XML Encryption + */ + public static final String ALGO_ID_C14N_PHYSICAL = + "http://santuario.apache.org/c14n/physical"; private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash = new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>(); @@ -202,6 +208,10 @@ Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer11_WithComments.class ); + canonicalizerHash.put( + Canonicalizer.ALGO_ID_C14N_PHYSICAL, + CanonicalizerPhysical.class + ); } /**
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - 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 { + /** Reset the writer after a c14n */ + protected boolean reset = false; - java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes); - InputSource in = new InputSource(bais); - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + /** + * 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 { - // needs to validate for ID attribute nomalization - dfactory.setNamespaceAware(true); + java.io.InputStream bais = new ByteArrayInputStream(inputBytes); + InputSource in = new InputSource(bais); + DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - DocumentBuilder db = dfactory.newDocumentBuilder(); + // needs to validate for ID attribute normalization + dfactory.setNamespaceAware(true); - /* - * 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. - * - */ + DocumentBuilder db = dfactory.newDocumentBuilder(); - // ErrorHandler eh = new C14NErrorHandler(); - // db.setErrorHandler(eh); - Document document = db.parse(in); - byte result[] = this.engineCanonicalizeSubTree(document); - return result; - } + 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 { + /** + * Method engineCanonicalizeXPathNodeSet + * + * @param xpathNodeSet + * @return the c14n bytes + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet) + throws CanonicalizationException { + return this.engineCanonicalizeXPathNodeSet( + XMLUtils.convertNodelistToSet(xpathNodeSet) + ); + } - 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 + ); + } - /** - * Method engineCanonicalizeXPathNodeSet - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { + /** + * Returns the URI of this engine. + * @return the URI + */ + public abstract String engineGetURI(); - return this - .engineCanonicalizeXPathNodeSet(XMLUtils - .convertNodelistToSet(xpathNodeSet), inclusiveNamespaces); - } + /** + * Returns true if comments are included + * @return true if comments are included + */ + public abstract boolean engineGetIncludeComments(); - //J- - /** Returns the URI of this engine. - * @return the URI - */ - public abstract String engineGetURI(); + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet) + throws CanonicalizationException; - /** Returns the URI if include comments - * @return true if include. - */ - public abstract boolean engineGetIncludeComments(); + /** + * C14n a nodeset + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeXPathNodeSet( + Set<Node> xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException; - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet) - throws CanonicalizationException; + /** + * C14n a node tree. + * + * @param rootNode + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException; - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces) - 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; - /** - * C14n a node tree. - * - * @param rootNode - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException; + /** + * Sets the writer where the canonicalization ends. ByteArrayOutputStream if + * none is set. + * @param os + */ + public abstract void setWriter(OutputStream os); - /** - * 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+ }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,87 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - 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; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidCanonicalizerException - * - */ - public InvalidCanonicalizerException() { - super(); - } + /** + * Constructor InvalidCanonicalizerException + * + */ + public InvalidCanonicalizerException() { + super(); + } - /** - * Constructor InvalidCanonicalizerException - * - * @param _msgID - */ - public InvalidCanonicalizerException(String _msgID) { - super(_msgID); - } + /** + * 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 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 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); - } + /** + * Constructor InvalidCanonicalizerException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidCanonicalizerException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.helper; @@ -43,10 +45,10 @@ */ public class AttrCompare implements Comparator<Attr>, 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. @@ -69,12 +71,11 @@ * */ public int compare(Attr attr0, Attr attr1) { - 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,9 +95,7 @@ } // 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; } @@ -109,9 +108,7 @@ return name0.compareTo(name1); } return ATTR0_BEFORE_ATTR1; - } - - if (namespaceURI1 == null) { + } else if (namespaceURI1 == null) { return ATTR1_BEFORE_ATTR0; }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,33 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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() { + /** + * Constructor C14nHelper + * + */ + private C14nHelper() { + // don't allow instantiation + } - // 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 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 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 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; + } - /** - * Method namespaceIsAbsolute - * - * @param namespaceValue - * @return true if the given namespace is absolute. - */ - public static boolean namespaceIsAbsolute(String namespaceValue) { + /** + * 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; + } - // assume empty namespaces are absolute - if (namespaceValue.length() == 0) { - return true; - } - return namespaceValue.indexOf(':')>0; - } + String nodeAttrName = attr.getNodeName(); + boolean definesDefaultNS = nodeAttrName.equals("xmlns"); + boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:"); - /** - * 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); - } - } - } + "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 { + /** + * 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() }; - if (!document.isSupported("Traversal", "2.0")) { - Object exArgs[] = { - document.getImplementation().getClass().getName() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.TraversalNotSupported", exArgs + ); + } + } - 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(); - /** - * 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"); - } - } + for (int i = 0; i < attributes.getLength(); i++) { + C14nHelper.assertNotRelativeNS((Attr) attributes.item(i)); + } + } else { + throw new CanonicalizationException("Called checkForRelativeNamespace() on null"); + } + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java Fri Jul 05 15:54:42 2013 -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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.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; @@ -57,40 +55,46 @@ * * @author Sean Mullan * @author Raul Benito - * @version $Revision: 1.2 $ */ public abstract class Canonicalizer11 extends CanonicalizerBase { - boolean firstCall = true; - final SortedSet<Attr> result = new TreeSet<Attr>(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<Attr> result = new TreeSet<Attr>(COMPARE); - static class XmlAttrStack { - int currentLevel = 0; - int lastlevel = 0; - XmlsStackElement cur; + private boolean firstCall = true; + + private static class XmlAttrStack { static class XmlsStackElement { int level; boolean rendered = false; List<Attr> nodes = new ArrayList<Attr>(); }; + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>(); + 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; } - 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<Attr> 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); @@ -126,7 +132,7 @@ Map<String, Attr> loa = new HashMap<String, Attr>(); List<Attr> baseAttrs = new ArrayList<Attr>(); 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<Attr> 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<Attr> it = cur.nodes.iterator(); + Iterator<Attr> 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,7 +185,8 @@ col.addAll(loa.values()); } }; - XmlAttrStack xmlattrStack = new XmlAttrStack(); + + private XmlAttrStack xmlattrStack = new XmlAttrStack(); /** * Constructor Canonicalizer11 @@ -190,194 +198,6 @@ } /** - * Returns the Attr[]s to be outputted for the given element. - * <br> - * 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<Attr> 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<Attr> 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(result); - // output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(getSortedSetAsCollection(result)); - firstCall = false; - } - - return result.iterator(); - } - - - - /** - * Returns the Attr[]s to be outputted for the given element. - * <br> - * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a - * DOM which has been prepared using - * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator<Attr> handleAttributes(Element E, 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<Attr> 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); - } - } 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); - } - } - } 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); - Node n = null; - if (xmlns == null) { - // No xmlns def just get the already defined. - n = ns.getMapping(XMLNS); - } else if (!isVisible(xmlns)) { - // There is a defn but the xmlns is not selected by the xpath. - // then xmlns="" - 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. addXmlAttributes(E,result); - xmlattrStack.getXmlnsAttr(result); - ns.getUnrenderedNodes(result); - } - - return result.iterator(); - } - - /** * Always throws a CanonicalizationException because this is inclusive c14n. * * @param xpathNodeSet @@ -385,10 +205,10 @@ * @return none it always fails * @throws CanonicalizationException always */ - public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); + public byte[] engineCanonicalizeXPathNodeSet( + Set<Node> xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } /** @@ -399,17 +219,189 @@ * @return none it always fails * @throws CanonicalizationException */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } - void circumventBugIfNeeded(XMLSignatureInput input) + /** + * Returns the Attr[]s to be output for the given element. + * <br> + * 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<Attr> 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<Attr> 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(); + } + + /** + * Returns the Attr[]s to be output for the given element. + * <br> + * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a + * DOM which has been prepared using + * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator<Attr> 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<Attr> 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)) { + 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 { + if (isRealVisible && !XMLNS.equals(NName)) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, attribute); + } + } + } + } + } + + if (isRealVisible) { + //The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + Node n = null; + if (xmlns == null) { + //No xmlns def just get the already defined. + n = ns.getMapping(XMLNS); + } else if (!isVisible(xmlns)) { + //There is a definition but the xmlns is not selected by the xpath. + //then xmlns="" + n = ns.addMappingAndRender(XMLNS, "", 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); + } + + return result.iterator(); + } + + 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); + 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); } - continue; + } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); } - - String NName = N.getLocalName(); - String NValue = N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; + } + 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; } @@ -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('/');
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java Fri Jul 05 15:54:42 2013 -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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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;
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java Fri Jul 05 15:54:42 2013 -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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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;
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - 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 <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical * XML Version 1.0</A>, a W3C Recommendation from 15 March 2001. * * @author Christian Geuer-Pollmann <geuerp@apache.org> - * @version $Revision: 1.5 $ */ public abstract class Canonicalizer20010315 extends CanonicalizerBase { - boolean firstCall=true; - final SortedSet<Attr> result= new TreeSet<Attr>(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; + 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<Attr> result = new TreeSet<Attr>(COMPARE); + + private static class XmlAttrStack { + static class XmlsStackElement { + int level; + boolean rendered = false; + List<Attr> nodes = new ArrayList<Attr>(); + }; + + int currentLevel = 0; + int lastlevel = 0; XmlsStackElement cur; - static class XmlsStackElement { - int level; - boolean rendered=false; - List<Attr> nodes=new ArrayList<Attr>(); - }; - List<XmlsStackElement> levels=new ArrayList<XmlsStackElement>(); + List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>(); + 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; + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + levels.add(cur); + lastlevel = currentLevel; + } + cur.nodes.add(n); + } + + void getXmlnsAttr(Collection<Attr> col) { + int size = levels.size() - 1; + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + lastlevel = currentLevel; + levels.add(cur); + } + boolean parentRendered = false; + XmlsStackElement e = null; + if (size == -1) { + parentRendered = true; + } else { + e = levels.get(size); + if (e.rendered && e.level + 1 == currentLevel) { + parentRendered = true; } - cur.nodes.add(n); - } - void getXmlnsAttr(Collection<Attr> col) { - int size=levels.size()-1; - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - lastlevel=currentLevel; - levels.add(cur); + } + if (parentRendered) { + col.addAll(cur.nodes); + cur.rendered = true; + return; + } + + Map<String, Attr> loa = new HashMap<String, Attr>(); + for (; size >= 0; size--) { + e = levels.get(size); + Iterator<Attr> it = e.nodes.iterator(); + while (it.hasNext()) { + Attr n = it.next(); + if (!loa.containsKey(n.getName())) { + loa.put(n.getName(), n); + } } - boolean parentRendered=false; - XmlsStackElement e=null; - if (size==-1) { - parentRendered=true; - } else { - e=levels.get(size); - if (e.rendered && e.level+1==currentLevel) - parentRendered=true; + } - } - if (parentRendered) { - col.addAll(cur.nodes); - cur.rendered=true; - return; - } - - Map<String,Attr> loa = new HashMap<String,Attr>(); - for (;size>=0;size--) { - e=levels.get(size); - Iterator<Attr> 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()); + cur.rendered = true; + col.addAll(loa.values()); } } - XmlAttrStack xmlattrStack=new XmlAttrStack(); + + private 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. - * <br> - * 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<Attr> 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<Attr> 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. - * <br> - * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has - * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator<Attr> 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(); + * Constructor Canonicalizer20010315 + * + * @param includeComments + */ + public Canonicalizer20010315(boolean includeComments) { + super(includeComments); } + /** + * 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<Node> xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { - SortedSet<Attr> 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(); + /** + * 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 { - 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; - } + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } - 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; + /** + * Returns the Attr[]s to be output for the given element. + * <br> + * 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<Attr> 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<Attr> 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 + ); + } + } } - //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 (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(); + } + + /** + * Returns the Attr[]s to be output for the given element. + * <br> + * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has + * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator<Attr> 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<Attr> 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)) { + //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. + 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); + } + + 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 { - if (isRealVisible && NName!=XMLNS) { - ns.removeMapping(NName); - } else { - ns.addMapping(NName,NValue,N); + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + } + + @Override + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { + return; + } + xmlattrStack.push(-1); + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); + + if (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); } } - if (isRealVisible) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - Node n=null; - if (xmlns == null) { - //No xmlns def just get the already defined. - n=ns.getMapping(XMLNS); - } else if ( !isVisible(xmlns)) { - //There is a definition but the xmlns is not selected by the xpath. - //then xmlns="" - n=ns.addMappingAndRender(XMLNS,"",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. - //addXmlAttributes(E,result); - xmlattrStack.getXmlnsAttr(result); - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); - - } - - 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<Node> 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); - } - } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java Fri Jul 05 15:54:42 2013 -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 " <A * HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML @@ -52,301 +54,279 @@ * <i>THIS </i> implementation is a complete rewrite of the algorithm. * * @author Christian Geuer-Pollmann <geuerp@apache.org> - * @version $Revision: 1.5 $ + * @version $Revision: 1147448 $ * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#"> * XML Canonicalization, Version 1.0</a> */ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { + + 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<String> _inclusiveNSSet = new TreeSet<String>(); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE); - /** - * Constructor Canonicalizer20010315Excl - * - * @param includeComments - */ - public Canonicalizer20010315Excl(boolean includeComments) { - super(includeComments); + private SortedSet<String> inclusiveNSSet; + + private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE); + + /** + * Constructor Canonicalizer20010315Excl + * + * @param includeComments + */ + public Canonicalizer20010315Excl(boolean includeComments) { + super(includeComments); + } + + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, "", null); + } + + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @param inclusiveNamespaces + * + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces + ) throws CanonicalizationException { + return 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{ + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeSubTree(rootNode, excl); + } + + /** + * + * @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<Node> xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } + + @Override + protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet<Attr> result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + SortedSet<String> visiblyUtilized = new TreeSet<String>(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); } - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, "",null); + 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 + ); + } + } } - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @param inclusiveNamespaces - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, inclusiveNamespaces,null); + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; } - /** - * 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); + visiblyUtilized.add(prefix); + + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } } - /** - * Method handleAttributesSubtree - * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - Iterator<Attr> 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<Attr> result = this.result; - result.clear(); - NamedNodeMap attrs=null; + return result.iterator(); + } - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); + /** + * @inheritDoc + * @param element + * @throws CanonicalizationException + */ + @Override + protected final Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet<Attr> result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + Set<String> visiblyUtilized = null; + // It's the output selected. + boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1; + if (isOutputElement) { + visiblyUtilized = new TreeSet<String>(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); + } } - //The prefix visibly utilized(in the attribute or in the name) in the element - SortedSet<String> visiblyUtilized = getNSSetClone(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); - 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 = 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); } - String NName=N.getLocalName(); - String NNodeValue=N.getNodeValue(); + // 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 definition 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 + ); + } } } - } - 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<String> 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<Node> xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { + 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); + } - 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; + } + visiblyUtilized.add(prefix); + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } } - @SuppressWarnings("unchecked") - private TreeSet<String> getInclusiveNameSpace(String inclusiveNameSpaces) { - return (TreeSet<String>)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces); + return result.iterator(); } - - @SuppressWarnings("unchecked") - private SortedSet<String> getNSSetClone() { - return (SortedSet<String>) this._inclusiveNSSet.clone(); + 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); } - - - /** - * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - final Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be outputted - SortedSet<Attr> 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 - Set<String> 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 (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 (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 (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<String> 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(); - } - 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()); - } - - XMLUtils.circumventBug2650(doc); - } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,48 +2,44 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; -/** - * - * - */ -public class Canonicalizer20010315ExclOmitComments - extends Canonicalizer20010315Excl { +public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl { - /** - * - */ - public Canonicalizer20010315ExclOmitComments() { - super(false); - } + /** + * + */ + public Canonicalizer20010315ExclOmitComments() { + super(false); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return false; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return false; + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,52 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** * Class Canonicalizer20010315ExclWithComments - * - * @version $Revision: 1.5 $ */ -public class Canonicalizer20010315ExclWithComments - extends Canonicalizer20010315Excl { +public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl { - /** - * Constructor Canonicalizer20010315ExclWithComments - * - */ - public Canonicalizer20010315ExclWithComments() { - super(true); - } + /** + * Constructor Canonicalizer20010315ExclWithComments + * + */ + public Canonicalizer20010315ExclWithComments() { + super(true); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return true; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,50 +2,48 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - 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); - } + /** + * Constructor Canonicalizer20010315WithXPathOmitComments + * + */ + public Canonicalizer20010315OmitComments() { + super(false); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return false; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return false; + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,47 +2,47 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; 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; + } }
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java Thu Jun 20 18:53:57 2013 +0100 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java Fri Jul 05 15:54:42 2013 -0400 @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 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 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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; - - 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 <geuerp@apache.org> - * @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); + 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); + } } - } - List<NodeFilter> nodeFilter; + private List<NodeFilter> nodeFilter; - boolean _includeComments; - Set<Node> _xpathNodeSet = null; - /** - * The node to be skiped/excluded from the DOM tree - * in subtree canonicalizations. - */ - Node _excludeNode =null; - OutputStream _writer = new UnsyncByteArrayOutputStream();//null; + private boolean includeComments; + private Set<Node> 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; - } + /** + * 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<Node> xpathNodeSet) - throws CanonicalizationException { - this._xpathNodeSet = xpathNodeSet; - return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet)); - } + /** + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, (Node)null); + } - /** - * 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 { + /** + * Method engineCanonicalizeXPathNodeSet + * @inheritDoc + * @param xpathNodeSet + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(Set<Node> 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); + if (input.getSubNode() != null) { + return engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); + } else { + return engineCanonicalizeXPathNodeSet(input.getNodeSet()); } - } - /** - * @param _writer The _writer to set. - */ - public void setWriter(OutputStream _writer) { - this._writer = _writer; + } + 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); + } } /** - * 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; + * @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 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; + } 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); - } - } + } 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<String, byte[]> cache=new HashMap<String, byte[]>(); + /** + * 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<String, byte[]> cache = new HashMap<String, byte[]>(); 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.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; - case Node.COMMENT_NODE : - if (includeComments) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - 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.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.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); + 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<Attr> 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; + Iterator<Attr> 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); + } } - 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; - } + 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; } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); + 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); + } + } - private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) - throws CanonicalizationException { + /** + * 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<String, byte[]> cache = new HashMap<String, byte[]>(); + do { + switch (currentNode.getNodeType()) { - 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(); + 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; + + 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<Attr> 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 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); - } - } + 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; + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); + } while(true); + } - /** - * 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) - 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<String, byte[]> cache=new HashMap<String,byte[]>(); - do { - switch (currentNode.getNodeType()) { + protected int isVisibleDO(Node currentNode, int level) { + if (nodeFilter != null) { + Iterator<NodeFilter> 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; + } - case Node.DOCUMENT_TYPE_NODE : - default : - break; + protected int isVisibleInt(Node currentNode) { + if (nodeFilter != null) { + Iterator<NodeFilter> 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; + } - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); + protected boolean isVisible(Node currentNode) { + if (nodeFilter != null) { + Iterator<NodeFilter> 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; + } - case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - //currentNode = currentNode.getFirstChild(); - sibling= currentNode.getFirstChild(); - break; + 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(); - case Node.COMMENT_NODE : - if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; + 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); + } + } - case Node.PROCESSING_INSTRUCTION_NODE : - if (isVisible(currentNode)) - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; + /** + * 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<Element> parents = new ArrayList<Element>(); + Node parent = n1; + while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) { + parents.add((Element)parent); + parent = parent.getParentNode(); + } + //Visit them in reverse order. + ListIterator<Element> it = parents.listIterator(parents.size()); + while (it.hasPrevious()) { + Element ele = it.previous(); + handleParent(ele, ns); + } + parents.clear(); + Attr nsprefix; + if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null) + && "".equals(nsprefix.getValue())) { + ns.addMappingAndRender(XMLNS, "", nullNode); + } + } - 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(); + /** + * 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<Attr> handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException; + + /** + * 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<Attr> handleAttributesSubtree(Element element, 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 + * <UL> + * <LI>all ampersands (&) with <CODE>&amp;</CODE></LI> + * <LI>all open angle brackets (<) with <CODE>&lt;</CODE></LI> + * <LI>all quotation mark characters with <CODE>&quot;</CODE></LI> + * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character + * references. The character references are written in uppercase + * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented + * by the character reference <CODE>&#xD;</CODE>)</LI> + * </UL> + * + * @param name + * @param value + * @param writer + * @throws IOException + */ + protected static final void outputAttrToWriter( + final String name, final String value, + final OutputStream writer, final Map<String, byte[]> cache + ) throws IOException { + writer.write(' '); + UtfHelpper.writeByte(name, writer, cache); + writer.write(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; } - - } - 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<Attr> 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(); - } while(true); - } - int isVisibleDO(Node currentNode,int level) { - if (nodeFilter!=null) { - Iterator<NodeFilter> 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<NodeFilter> 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; + writer.write(toWrite); } - boolean isVisible(Node currentNode) { - if (nodeFilter!=null) { - Iterator<NodeFilter> it=nodeFilter.iterator(); - while (it.hasNext()) { - if ((it.next()).isNodeInclude(currentNode)!=1) - return false; + writer.write('\"'); + } + + /** + * Outputs a PI to the internal Writer. + * + * @param currentPI + * @param writer where to write the things + * @throws IOException + */ + protected void outputPItoWriter( + ProcessingInstruction currentPI, OutputStream writer, int position + ) throws IOException { + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + writer.write('\n'); + } + writer.write(BEGIN_PI); + + 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); } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return false; - return true; + } } - void handleParent(Element e,NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { - return; + 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); } - 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<Element> parents=new ArrayList<Element>(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<Element> it=parents.listIterator(parents.size()); - while (it.hasPrevious()) { - Element ele=it.previous(); - handleParent(ele, ns); + writer.write(END_PI); + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + writer.write('\n'); } - 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<Attr> 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<Attr> 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 - * <UL> - * <LI>all ampersands (&) with <CODE>&amp;</CODE></LI> - * <LI>all open angle brackets (<) with <CODE>&lt;</CODE></LI> - * <LI>all quotation mark characters with <CODE>&quot;</CODE></LI> - * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character - * references. The character references are written in uppercase - * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented - * by the character reference <CODE>&#xD;</CODE>)</LI> - * </UL> - * - * @param name - * @param value - * @param writer - * @throws IOException - */ - static final void outputAttrToWriter(final String name, final String value, final OutputStream writer, - final Map<String, byte[]> cache) throws IOException { - writer.write(' '); - UtfHelpper.writeByte(name,writer,cache); - writer.write(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); - } - - 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); - } - } - } - - 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); - - 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); - } - } - - @SuppressWarnings("unchecked") - protected Collection<Attr> getSortedSetAsCollection(SortedSet<Attr> result) { - return (Collection<Attr>)(Collection)result; } + /** + * 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); + + 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 + */ + 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); + } + } }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java Fri Jul 05 15:54:42 2013 -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<Attr> result = new TreeSet<Attr>(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<Node> 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. + * <br> + * 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<Attr> 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<Attr> result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i <