diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java index 62fd0fe4964..6b661bb31f3 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * The Algorithm class which stores the Algorithm URI as a string. - * */ public abstract class Algorithm extends SignatureElementProxy { - /** - * - * @param doc - * @param algorithmURI is the URI of the algorithm as String - */ - public Algorithm(Document doc, String algorithmURI) { + /** + * + * @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 + ); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java index 9e736518936..ca7d42a869a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java @@ -114,6 +114,18 @@ public class JCEMapper { XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, new Algorithm("", "SHA1withECDSA", "Signature") ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, + new Algorithm("", "SHA256withECDSA", "Signature") + ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, + new Algorithm("", "SHA384withECDSA", "Signature") + ); + algorithmsMap.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, + new Algorithm("", "SHA512withECDSA", "Signature") + ); algorithmsMap.put( XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, new Algorithm("", "HmacMD5", "Mac") @@ -154,6 +166,18 @@ public class JCEMapper { XMLCipher.AES_256, 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") @@ -162,6 +186,10 @@ public class JCEMapper { XMLCipher.RSA_OAEP, 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") diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java index 63a808ba745..d10c88c78bd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms; import java.security.MessageDigest; import java.security.NoSuchProviderException; -import java.util.HashMap; -import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import org.w3c.dom.Document; - /** * Digest Message wrapper & selector class. * *
  * MessageDigestAlgorithm.getInstance()
  * 
- * */ public class MessageDigestAlgorithm extends Algorithm { /** Message Digest - NOT RECOMMENDED MD5*/ - public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5"; - /** Digest - Required SHA1*/ - public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; - /** Message Digest - RECOMMENDED SHA256*/ - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - /** Message Digest - OPTIONAL SHA384*/ - public static final String ALGO_ID_DIGEST_SHA384 = Constants.MoreAlgorithmsSpecNS + "sha384"; - /** Message Digest - OPTIONAL SHA512*/ - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - /** Message Digest - OPTIONAL RIPEMD-160*/ - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; + 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> instances=new - ThreadLocal>() { - protected Map initialValue() { - return new HashMap(); - }; - }; + 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); - } - -private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException { - MessageDigest result= instances.get().get(algorithmURI); - if (result!=null) - return result; - String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); - - if (algorithmID == null) { - Object[] exArgs = { algorithmURI }; - throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); - } - - MessageDigest md; - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { - md = MessageDigest.getInstance(algorithmID); - } else { - md = MessageDigest.getInstance(algorithmID,provider); - } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + if (algorithmID == null) { + Object[] exArgs = { algorithmURI }; + throw new XMLSignatureException("algorithms.NoSuchMap", exArgs); } - instances.get().put(algorithmURI, md); + + MessageDigest md; + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { + md = MessageDigest.getInstance(algorithmID); + } else { + md = MessageDigest.getInstance(algorithmID, provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + return md; -} - - /** - * Returns the actual {@link java.security.MessageDigest} algorithm object - * - * @return the actual {@link java.security.MessageDigest} algorithm object - */ - public java.security.MessageDigest getAlgorithm() { - return this.algorithm; - } - - /** - * Proxy method for {@link java.security.MessageDigest#isEqual} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param digesta - * @param digestb - * @return the result of the {@link java.security.MessageDigest#isEqual} method - */ - public static boolean isEqual(byte[] digesta, byte[] digestb) { - return java.security.MessageDigest.isEqual(digesta, digestb); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest()} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#digest()} method - */ - public byte[] digest() { - return this.algorithm.digest(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest(byte[])} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method - */ - public byte[] digest(byte input[]) { - return this.algorithm.digest(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param buf - * @param offset - * @param len - * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method - * @throws java.security.DigestException - */ - public int digest(byte buf[], int offset, int len) - throws java.security.DigestException { - return this.algorithm.digest(buf, offset, len); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getAlgorithm} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method - */ - public String getJCEAlgorithmString() { - return this.algorithm.getAlgorithm(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getProvider} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getProvider} method - */ - public java.security.Provider getJCEProvider() { - return this.algorithm.getProvider(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#getDigestLength} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @return the result of the {@link java.security.MessageDigest#getDigestLength} method - */ - public int getDigestLength() { - return this.algorithm.getDigestLength(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#reset} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - */ - public void reset() { - this.algorithm.reset(); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte[])} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - */ - public void update(byte[] input) { - this.algorithm.update(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param input - */ - public void update(byte input) { - this.algorithm.update(input); - } - - /** - * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)} - * which is executed on the internal {@link java.security.MessageDigest} object. - * - * @param buf - * @param offset - * @param len - */ - public void update(byte buf[], int offset, int len) { - this.algorithm.update(buf, offset, len); - } - - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DIGESTMETHOD; - } + } + + /** + * Returns the actual {@link java.security.MessageDigest} algorithm object + * + * @return the actual {@link java.security.MessageDigest} algorithm object + */ + public java.security.MessageDigest getAlgorithm() { + return algorithm; + } + + /** + * Proxy method for {@link java.security.MessageDigest#isEqual} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param digesta + * @param digestb + * @return the result of the {@link java.security.MessageDigest#isEqual} method + */ + public static boolean isEqual(byte[] digesta, byte[] digestb) { + return java.security.MessageDigest.isEqual(digesta, digestb); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest()} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#digest()} method + */ + public byte[] digest() { + return algorithm.digest(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest(byte[])} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + * @return the result of the {@link java.security.MessageDigest#digest(byte[])} method + */ + public byte[] digest(byte input[]) { + return algorithm.digest(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#digest(byte[], int, int)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param buf + * @param offset + * @param len + * @return the result of the {@link java.security.MessageDigest#digest(byte[], int, int)} method + * @throws java.security.DigestException + */ + public int digest(byte buf[], int offset, int len) throws java.security.DigestException { + return algorithm.digest(buf, offset, len); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getAlgorithm} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getAlgorithm} method + */ + public String getJCEAlgorithmString() { + return algorithm.getAlgorithm(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getProvider} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getProvider} method + */ + public java.security.Provider getJCEProvider() { + return algorithm.getProvider(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#getDigestLength} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @return the result of the {@link java.security.MessageDigest#getDigestLength} method + */ + public int getDigestLength() { + return algorithm.getDigestLength(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#reset} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + */ + public void reset() { + algorithm.reset(); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte[])} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + */ + public void update(byte[] input) { + algorithm.update(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param input + */ + public void update(byte input) { + algorithm.update(input); + } + + /** + * Proxy method for {@link java.security.MessageDigest#update(byte[], int, int)} + * which is executed on the internal {@link java.security.MessageDigest} object. + * + * @param buf + * @param offset + * @param len + */ + public void update(byte buf[], int offset, int len) { + algorithm.update(buf, offset, len); + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DIGESTMETHOD; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java index 5dbcf58e33b..4748a6bc882 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java @@ -74,7 +74,7 @@ public class SignatureAlgorithm extends Algorithm { this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -92,10 +92,10 @@ public class SignatureAlgorithm extends Algorithm { 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 @@ public class SignatureAlgorithm extends Algorithm { } signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this._constructionElement); + signatureAlgorithm.engineGetContextFromElement(this.constructionElement); } /** @@ -310,7 +310,7 @@ public class SignatureAlgorithm extends Algorithm { * @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 @@ public class SignatureAlgorithm extends Algorithm { * 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 ); @@ -409,6 +407,15 @@ public class SignatureAlgorithm extends Algorithm { algorithmHash.put( 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 ); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java index c47be7e2c0d..77bcfa7fd98 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms; @@ -27,157 +29,149 @@ import java.security.spec.AlgorithmParameterSpec; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public abstract class SignatureAlgorithmSpi { - /** - * Returns the URI representation of Transformation algorithm - * - * @return the URI representation of Transformation algorithm - */ - protected abstract String engineGetURI(); + /** + * Returns the URI representation of Transformation algorithm + * + * @return the URI representation of Transformation algorithm + */ + protected abstract String engineGetURI(); - /** - * Proxy method for {@link java.security.Signature#getAlgorithm} - * which is executed on the internal {@link java.security.Signature} object. - * - * @return the result of the {@link java.security.Signature#getAlgorithm} method - */ - protected abstract String engineGetJCEAlgorithmString(); + /** + * 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() { - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java index 7231b069a18..8935e389728 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; @@ -42,570 +42,498 @@ import org.w3c.dom.Document; 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()); + /** + * Proxy method for {@link java.security.Signature#verify(byte[])} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param signature + * @return true if the signature is correct + * @throws XMLSignatureException + */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { + try { + if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + byte[] completeResult = this.macAlgorithm.doFinal(); + return MessageDigestAlgorithm.isEqual(completeResult, signature); } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - byte[] completeResult = this._macAlgorithm.doFinal(); - return MessageDigestAlgorithm.isEqual(completeResult, signature); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)} - * which is executed on the internal {@link java.security.Signature} object. - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitVerify(Key secretKey) throws XMLSignatureException { + /** + * 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 }; - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - 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 { - - try { - if (this._HMACOutputLengthSet && this._HMACOutputLength < getDigestLength()) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, - "HMACOutputLength must not be less than " + getDigestLength()); + /** + * Proxy method for {@link java.security.Signature#sign()} + * which is executed on the internal {@link java.security.Signature} object. + * + * @return the result of the {@link java.security.Signature#sign()} method + * @throws XMLSignatureException + */ + protected byte[] engineSign() throws XMLSignatureException { + try { + if (this.HMACOutputLengthSet && this.HMACOutputLength < getDigestLength()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "HMACOutputLength must not be less than " + getDigestLength()); + } + Object[] exArgs = { String.valueOf(getDigestLength()) }; + throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); + } else { + return this.macAlgorithm.doFinal(); } - throw new XMLSignatureException("errorMessages.XMLSignatureException"); - } else { - return this._macAlgorithm.doFinal(); - } - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method reduceBitLength - * - * @param completeResult - * @return the reduced bits. - * @param length - * - */ - private static byte[] reduceBitLength(byte completeResult[], int length) { + /** + * 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 }; - int bytes = length / 8; - int abits = length % 8; - byte[] strippedResult = new byte[bytes + ((abits == 0) - ? 0 - : 1)]; + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - System.arraycopy(completeResult, 0, strippedResult, 0, bytes); + try { + this.macAlgorithm.init(secretKey); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (abits > 0) { - byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0, - (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE }; + /** + * 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 }; - strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]); - } + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } - return strippedResult; - } + try { + this.macAlgorithm.init(secretKey, algorithmParameterSpec); + } catch (InvalidKeyException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method engineInitSign - * - * @param secretKey - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey) throws XMLSignatureException { + /** + * Method engineInitSign + * + * @param secretKey + * @param secureRandom + * @throws XMLSignatureException + */ + protected void engineInitSign(Key secretKey, SecureRandom secureRandom) + throws XMLSignatureException { + throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); + } - 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)} + * 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); + } + } - try { - this._macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Proxy method for {@link java.security.Signature#update(byte[], int, int)} + * which is executed on the internal {@link java.security.Signature} object. + * + * @param buf + * @param offset + * @param len + * @throws XMLSignatureException + */ + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { + try { + this.macAlgorithm.update(buf, offset, len); + } catch (IllegalStateException ex) { + throw new XMLSignatureException("empty", ex); + } + } - /** - * Method engineInitSign - * - * @param secretKey - * @param algorithmParameterSpec - * @throws XMLSignatureException - */ - protected void engineInitSign( - Key secretKey, AlgorithmParameterSpec algorithmParameterSpec) - throws XMLSignatureException { + /** + * Method engineGetJCEAlgorithmString + * @inheritDoc + * + */ + protected String engineGetJCEAlgorithmString() { + return this.macAlgorithm.getAlgorithm(); + } - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; + /** + * Method engineGetJCEAlgorithmString + * + * @inheritDoc + */ + protected String engineGetJCEProviderName() { + return this.macAlgorithm.getProvider().getName(); + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Method engineSetHMACOutputLength + * + * @param HMACOutputLength + */ + protected void engineSetHMACOutputLength(int HMACOutputLength) { + this.HMACOutputLength = HMACOutputLength; + this.HMACOutputLengthSet = true; + } - try { - this._macAlgorithm.init(secretKey, algorithmParameterSpec); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Method engineGetContextFromElement + * + * @param element + */ + protected void engineGetContextFromElement(Element element) { + super.engineGetContextFromElement(element); - /** - * Method engineInitSign - * - * @param secretKey - * @param secureRandom - * @throws XMLSignatureException - */ - protected void engineInitSign(Key secretKey, SecureRandom secureRandom) - throws XMLSignatureException { - throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC"); - } + if (element == null) { + throw new IllegalArgumentException("element null"); + } - /** - * 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 { + Text hmaclength = + XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0); - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (hmaclength != null) { + this.HMACOutputLength = Integer.parseInt(hmaclength.getData()); + this.HMACOutputLengthSet = true; + } + } - /** - * 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 { + /** + * Method engineAddContextToElement + * + * @param element + */ + public void engineAddContextToElement(Element element) { + if (element == null) { + throw new IllegalArgumentException("null element"); + } - try { - this._macAlgorithm.update(input); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + if (this.HMACOutputLengthSet) { + Document doc = element.getOwnerDocument(); + Element HMElem = + XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); + Text HMText = + doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); - /** - * 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 { + HMElem.appendChild(HMText); + XMLUtils.addReturnToElement(element); + element.appendChild(HMElem); + XMLUtils.addReturnToElement(element); + } + } - try { - this._macAlgorithm.update(buf, offset, len); - } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Class IntegrityHmacSHA1 + */ + public static class IntegrityHmacSHA1 extends IntegrityHmac { - /** - * Method engineGetJCEAlgorithmString - * @inheritDoc - * - */ - protected String engineGetJCEAlgorithmString() { + /** + * Constructor IntegrityHmacSHA1 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA1() throws XMLSignatureException { + super(); + } - log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; + } - return this._macAlgorithm.getAlgorithm(); - } + int getDigestLength() { + return 160; + } + } - /** - * Method engineGetJCEAlgorithmString - * - * @inheritDoc - */ - protected String engineGetJCEProviderName() { - return this._macAlgorithm.getProvider().getName(); - } + /** + * Class IntegrityHmacSHA256 + */ + public static class IntegrityHmacSHA256 extends IntegrityHmac { - /** - * Method engineSetHMACOutputLength - * - * @param HMACOutputLength - */ - protected void engineSetHMACOutputLength(int HMACOutputLength) { - this._HMACOutputLength = HMACOutputLength; - this._HMACOutputLengthSet = true; - } + /** + * Constructor IntegrityHmacSHA256 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA256() throws XMLSignatureException { + super(); + } - /** - * Method engineGetContextFromElement - * - * @param element - */ - protected void engineGetContextFromElement(Element element) { + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; + } - super.engineGetContextFromElement(element); + int getDigestLength() { + return 256; + } + } - if (element == null) { - throw new IllegalArgumentException("element null"); - } + /** + * Class IntegrityHmacSHA384 + */ + public static class IntegrityHmacSHA384 extends IntegrityHmac { - Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(), - Constants._TAG_HMACOUTPUTLENGTH,0); + /** + * Constructor IntegrityHmacSHA384 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA384() throws XMLSignatureException { + super(); + } - if (hmaclength != null) { - this._HMACOutputLength = Integer.parseInt(hmaclength.getData()); - this._HMACOutputLengthSet = true; - } + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA384; + } - } + int getDigestLength() { + return 384; + } + } - /** - * Method engineAddContextToElement - * - * @param element - */ - public void engineAddContextToElement(Element element) { + /** + * Class IntegrityHmacSHA512 + */ + public static class IntegrityHmacSHA512 extends IntegrityHmac { - if (element == null) { - throw new IllegalArgumentException("null element"); - } + /** + * Constructor IntegrityHmacSHA512 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA512() throws XMLSignatureException { + super(); + } - if (this._HMACOutputLengthSet) { - Document doc = element.getOwnerDocument(); - Element HMElem = XMLUtils.createElementInSignatureSpace(doc, - Constants._TAG_HMACOUTPUTLENGTH); - Text HMText = - doc.createTextNode(new Integer(this._HMACOutputLength).toString()); + /** + * Method engineGetURI + * @inheritDoc + * + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA512; + } - HMElem.appendChild(HMText); - XMLUtils.addReturnToElement(element); - element.appendChild(HMElem); - XMLUtils.addReturnToElement(element); - } - } + int getDigestLength() { + return 512; + } + } - /** - * Class IntegrityHmacSHA1 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA1 extends IntegrityHmac { + /** + * Class IntegrityHmacRIPEMD160 + */ + public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { - /** - * Constructor IntegrityHmacSHA1 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA1() throws XMLSignatureException { - super(); - } + /** + * Constructor IntegrityHmacRIPEMD160 + * + * @throws XMLSignatureException + */ + public IntegrityHmacRIPEMD160() throws XMLSignatureException { + super(); + } - /** - * Method engineGetURI - * @inheritDoc - * - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA1; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; + } - int getDigestLength() { - return 160; - } - } + int getDigestLength() { + return 160; + } + } - /** - * Class IntegrityHmacSHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - public static class IntegrityHmacSHA256 extends IntegrityHmac { + /** + * Class IntegrityHmacMD5 + */ + public static class IntegrityHmacMD5 extends IntegrityHmac { - /** - * Constructor IntegrityHmacSHA256 - * - * @throws XMLSignatureException - */ - public IntegrityHmacSHA256() throws XMLSignatureException { - super(); - } + /** + * Constructor IntegrityHmacMD5 + * + * @throws XMLSignatureException + */ + public IntegrityHmacMD5() throws XMLSignatureException { + super(); + } - /** - * Method engineGetURI - * - * @inheritDoc - */ - public String engineGetURI() { - return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; + } - 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; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java index ccc01b01c58..7460f66ffd6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; @@ -36,22 +38,17 @@ import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi 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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { * @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** @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 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA256 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA256 extends SignatureBaseRSA { @@ -287,9 +264,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA384 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA384 extends SignatureBaseRSA { @@ -310,9 +284,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSASHA512 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSASHA512 extends SignatureBaseRSA { @@ -333,9 +304,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSARIPEMD160 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSARIPEMD160 extends SignatureBaseRSA { @@ -356,9 +324,6 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { /** * Class SignatureRSAMD5 - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public static class SignatureRSAMD5 extends SignatureBaseRSA { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java index 615aa436e46..0c6aca1361a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; @@ -37,21 +39,17 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetURI() { - return SignatureDSA._URI; + return SignatureDSA.URI; } /** @@ -68,17 +66,17 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { */ 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { /** * @inheritDoc */ - protected void engineUpdate(byte buf[], int offset, int len) - throws XMLSignatureException { + protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException { try { - this._signatureAlgorithm.update(buf, offset, len); + this.signatureAlgorithm.update(buf, offset, len); } catch (SignatureException ex) { throw new XMLSignatureException("empty", ex); } @@ -258,7 +245,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetJCEAlgorithmString() { - return this._signatureAlgorithm.getAlgorithm(); + return this.signatureAlgorithm.getAlgorithm(); } /** @@ -267,7 +254,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @inheritDoc */ protected String engineGetJCEProviderName() { - return this._signatureAlgorithm.getProvider().getName(); + return this.signatureAlgorithm.getProvider().getName(); } /** @@ -282,8 +269,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws IOException * @see 6.4.1 DSA */ - private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { + private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { byte rLength = asn1Bytes[3]; int i; @@ -294,19 +280,18 @@ public class SignatureDSA extends SignatureAlgorithmSpi { 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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @throws IOException * @see 6.4.1 DSA */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { + private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { if (xmldsigBytes.length != 40) { throw new IOException("Invalid XMLDSIG format of DSA signature"); @@ -337,7 +321,7 @@ public class SignatureDSA extends SignatureAlgorithmSpi { int j = i; if (xmldsigBytes[20 - i] < 0) { - j += 1; + j += 1; } int k; @@ -373,10 +357,8 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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 @@ public class SignatureDSA extends SignatureAlgorithmSpi { * @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"); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java index 18fdffe28fb..8da7a8c6e67 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.algorithms.implementations; - - import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; @@ -40,345 +40,417 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignature; 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 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - 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 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { - byte rLength = asn1Bytes[3]; - int i; - - for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--); - - byte sLength = asn1Bytes[5 + rLength]; - int j; - - for (j = sLength; - (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--); - - if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2) - || (asn1Bytes[2] != 2) || (i > 24) - || (asn1Bytes[4 + rLength] != 2) || (j > 24)) { - throw new IOException("Invalid ASN.1 format of ECDSA signature"); - } - byte xmldsigBytes[] = new byte[48]; - - System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i, - i); - System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes, - 48 - j, j); - - return xmldsigBytes; - } - - /** - * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. - * - * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value - * pairs; the XML Signature requires the core BigInteger values. - * - * @param xmldsigBytes - * @return the encoded ASN.1 bytes - * - * @throws IOException - * @see 6.4.1 DSA - * @see 3.3. ECDSA Signatures - */ - private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - - if (xmldsigBytes.length != 48) { - throw new IOException("Invalid XMLDSIG format of ECDSA signature"); - } - - int i; - - for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--); - - int j = i; - - if (xmldsigBytes[24 - i] < 0) { - j += 1; - } - - int k; - - for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--); - - int l = k; - - if (xmldsigBytes[48 - k] < 0) { - l += 1; - } - - byte asn1Bytes[] = new byte[6 + j + l]; - - asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); - asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; - - System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i); - - asn1Bytes[4 + j] = 2; - asn1Bytes[5 + j] = (byte) l; - - System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k); - - return asn1Bytes; - } - - /** - * Constructor SignatureRSA - * - * @throws XMLSignatureException - */ - public SignatureECDSA() throws XMLSignatureException { - - String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); - String provider=JCEMapper.getProviderId(); - try { - if (provider==null) { - this._signatureAlgorithm = Signature.getInstance(algorithmID); - } else { - this._signatureAlgorithm = Signature.getInstance(algorithmID,provider); - } - } catch (java.security.NoSuchAlgorithmException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); - } catch (NoSuchProviderException ex) { - Object[] exArgs = { algorithmID, - ex.getLocalizedMessage() }; - - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + 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"); } - } - /** @inheritDoc */ - protected void engineSetParameter(AlgorithmParameterSpec params) - throws XMLSignatureException { + byte rLength = asn1Bytes[offset + 1]; + int i; - try { - this._signatureAlgorithm.setParameter(params); - } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); - } - } + for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--); - /** @inheritDoc */ - protected boolean engineVerify(byte[] signature) - throws XMLSignatureException { + byte sLength = asn1Bytes[offset + 2 + rLength + 1]; + int j; - try { - byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + for (j = sLength; + (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + int rawLen = Math.max(i, j); - return this._signatureAlgorithm.verify(jcebytes); - } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } - } + 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]; - /** @inheritDoc */ - protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + 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 (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); - String needed = PublicKey.class.getName(); - Object exArgs[] = { supplied, needed }; + return xmldsigBytes; + } - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", - exArgs); - } + /** + * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { - try { - this._signatureAlgorithm.initVerify((PublicKey) publicKey); - } catch (InvalidKeyException ex) { + int rawLen = xmldsigBytes.length/2; + + int i; + + for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--); + + int j = i; + + if (xmldsigBytes[rawLen - i] < 0) { + j += 1; + } + + int k; + + for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--); + + int l = k; + + if (xmldsigBytes[2*rawLen - k] < 0) { + l += 1; + } + + int len = 2 + j + 2 + l; + if (len > 255) { + throw new IOException("Invalid XMLDSIG format of ECDSA signature"); + } + int offset; + byte asn1Bytes[]; + if (len < 128) { + asn1Bytes = new byte[2 + 2 + j + 2 + l]; + offset = 1; + } else { + asn1Bytes = new byte[3 + 2 + j + 2 + l]; + asn1Bytes[1] = (byte) 0x81; + offset = 2; + } + asn1Bytes[0] = 48; + asn1Bytes[offset++] = (byte) len; + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) j; + + System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i); + + offset += j; + + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) l; + + System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k); + + return asn1Bytes; + } + + /** + * Constructor SignatureRSA + * + * @throws XMLSignatureException + */ + public SignatureECDSA() throws XMLSignatureException { + + String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); + } + String provider = JCEMapper.getProviderId(); + try { + if (provider == null) { + this.signatureAlgorithm = Signature.getInstance(algorithmID); + } else { + this.signatureAlgorithm = Signature.getInstance(algorithmID,provider); + } + } catch (java.security.NoSuchAlgorithmException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } catch (NoSuchProviderException ex) { + Object[] exArgs = { algorithmID, ex.getLocalizedMessage() }; + + throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); + } + } + + /** @inheritDoc */ + protected void engineSetParameter(AlgorithmParameterSpec params) + throws XMLSignatureException { + try { + this.signatureAlgorithm.setParameter(params); + } catch (InvalidAlgorithmParameterException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected boolean engineVerify(byte[] signature) throws XMLSignatureException { + try { + byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + } + + return this.signatureAlgorithm.verify(jcebytes); + } catch (SignatureException ex) { + throw new XMLSignatureException("empty", ex); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } + } + + /** @inheritDoc */ + protected void engineInitVerify(Key publicKey) throws XMLSignatureException { + + if (!(publicKey instanceof PublicKey)) { + String supplied = publicKey.getClass().getName(); + String needed = PublicKey.class.getName(); + Object exArgs[] = { supplied, needed }; + + throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); + } + + try { + this.signatureAlgorithm.initVerify((PublicKey) publicKey); + } catch (InvalidKeyException ex) { // 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; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java index 36c98cfe790..aae62133dcc 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Class CanonicalizationException * @@ -32,57 +31,58 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; */ 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java index db1d4c261b7..2f0b31f5ed4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java @@ -39,6 +39,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicaliz 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 class Canonicalizer { */ public static final String ALGO_ID_C14N11_WITH_COMMENTS = ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments"; + /** + * Non-standard algorithm to serialize the physical representation for XML Encryption + */ + public static final String ALGO_ID_C14N_PHYSICAL = + "http://santuario.apache.org/c14n/physical"; private static Map> canonicalizerHash = new ConcurrentHashMap>(); @@ -202,6 +208,10 @@ public class Canonicalizer { Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS, Canonicalizer11_WithComments.class ); + canonicalizerHash.put( + Canonicalizer.ALGO_ID_C14N_PHYSICAL, + CanonicalizerPhysical.class + ); } /** diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java index 7e150e365b4..da5047d2052 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n; - - import java.io.ByteArrayInputStream; import java.io.OutputStream; import java.util.Set; @@ -29,7 +29,6 @@ import java.util.Set; 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.Node; 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 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 xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException; - /** - * C14n a nodeset - * - * @param xpathNodeSet - * @return the c14n bytes - * @throws CanonicalizationException - */ - public abstract byte[] engineCanonicalizeXPathNodeSet(Set 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 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+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java index 9fb1531b7e9..c0dee5e93f3 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * @author Christian Geuer-Pollmann - */ public class InvalidCanonicalizerException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java index 8675b673c72..f17a6b0d469 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.helper; @@ -43,10 +45,10 @@ import java.util.Comparator; */ public class AttrCompare implements Comparator, Serializable { - private final static long serialVersionUID = -7113259629930576230L; - private final static int ATTR0_BEFORE_ATTR1 = -1; - private final static int ATTR1_BEFORE_ATTR0 = 1; - private final static String XMLNS=Constants.NamespaceSpecNS; + private static final long serialVersionUID = -7113259629930576230L; + private static final int ATTR0_BEFORE_ATTR1 = -1; + private static final int ATTR1_BEFORE_ATTR0 = 1; + private static final String XMLNS = Constants.NamespaceSpecNS; /** * Compares two attributes based on the C14n specification. @@ -69,12 +71,11 @@ public class AttrCompare implements Comparator, Serializable { * */ 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 @@ public class AttrCompare implements Comparator, Serializable { 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 @@ public class AttrCompare implements Comparator, Serializable { } // 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 @@ public class AttrCompare implements Comparator, Serializable { return name0.compareTo(name1); } return ATTR0_BEFORE_ATTR1; - } - - if (namespaceURI1 == null) { + } else if (namespaceURI1 == null) { return ATTR1_BEFORE_ATTR0; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java index 0c720fd35f9..ecd0c52899c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.helper; - - import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; - /** * Temporary swapped static functions from the normalizer Section * @@ -36,129 +35,121 @@ import org.w3c.dom.NamedNodeMap; */ 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"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java index e0a46963ace..4d1fcbc0e6d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -25,7 +27,6 @@ import java.net.URI; 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.Set; 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.NamedNodeMap; 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 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; * * @author Sean Mullan * @author Raul Benito - * @version $Revision: 1.2 $ */ public abstract class Canonicalizer11 extends CanonicalizerBase { - boolean firstCall = true; - final SortedSet result = new TreeSet(COMPARE); - static final String XMLNS_URI = Constants.NamespaceSpecNS; - static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; - static Logger log = Logger.getLogger(Canonicalizer11.class.getName()); + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Canonicalizer11.class.getName()); + private final SortedSet result = new TreeSet(COMPARE); - 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 nodes = new ArrayList(); }; + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; List levels = new ArrayList(); + void push(int level) { currentLevel = level; - if (currentLevel == -1) + if (currentLevel == -1) { return; + } cur = null; while (lastlevel >= currentLevel) { levels.remove(levels.size() - 1); - if (levels.size() == 0) { + int newSize = levels.size(); + if (newSize == 0) { lastlevel = 0; return; } - 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } cur.nodes.add(n); } + void getXmlnsAttr(Collection col) { + int size = levels.size() - 1; if (cur == null) { cur = new XmlsStackElement(); cur.level = currentLevel; lastlevel = currentLevel; levels.add(cur); } - int size = levels.size() - 2; boolean parentRendered = false; XmlsStackElement e = null; if (size == -1) { parentRendered = true; } else { e = levels.get(size); - if (e.rendered && e.level+1 == currentLevel) + if (e.rendered && e.level + 1 == currentLevel) { parentRendered = true; + } } if (parentRendered) { col.addAll(cur.nodes); @@ -126,7 +132,7 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { Map loa = new HashMap(); List baseAttrs = new ArrayList(); boolean successiveOmitted = true; - for (;size>=0;size--) { + for (; size >= 0; size--) { e = levels.get(size); if (e.rendered) { successiveOmitted = false; @@ -134,16 +140,15 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { Iterator it = e.nodes.iterator(); while (it.hasNext() && successiveOmitted) { Attr n = it.next(); - if (n.getLocalName().equals("base")) { - if (!e.rendered) { - baseAttrs.add(n); - } - } else if (!loa.containsKey(n.getName())) + if (n.getLocalName().equals("base") && !e.rendered) { + baseAttrs.add(n); + } else if (!loa.containsKey(n.getName())) { loa.put(n.getName(), n); + } } } if (!baseAttrs.isEmpty()) { - Iterator it = cur.nodes.iterator(); + Iterator it = col.iterator(); String base = null; Attr baseAttr = null; while (it.hasNext()) { @@ -164,7 +169,9 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { col.addAll(loa.values()); } }; - XmlAttrStack xmlattrStack = new XmlAttrStack(); + + private XmlAttrStack xmlattrStack = new XmlAttrStack(); /** * Constructor Canonicalizer11 @@ -189,194 +197,6 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { super(includeComments); } - /** - * Returns the Attr[]s to be outputted for the given element. - *
- * The code of this method is a copy of {@link #handleAttributes(Element, - * NameSpaceSymbTable)}, - * whereas it takes into account that subtree-c14n is -- well -- - * subtree-based. - * So if the element in question isRoot of c14n, it's parent is not in the - * node set, as well as all other ancestors. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - if (!E.hasAttributes() && !firstCall) { - return null; - } - // result will contain the attrs which have to be outputted - final SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = E.getAttributes(); - int attrsLength = attrs.getLength(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri = N.getNamespaceURI(); - - if (XMLNS_URI != NUri) { - // It's not a namespace attr node. Add to the result and - // continue. - result.add(N); - continue; - } - - String NName = N.getLocalName(); - String NValue = N.getValue(); - if (XML.equals(NName) - && XML_LANG_URI.equals(NValue)) { - // The default mapping for xml must not be output. - continue; - } - - Node n = ns.addMappingAndRender(NName, NValue, N); - - if (n != null) { - // Render the ns definition - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()}; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - - if (firstCall) { - // It is the first node of the subtree - // Obtain all the namespaces defined in the parents, and added - // to the output. - ns.getUnrenderedNodes(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. - *
- * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a - * DOM which has been prepared using - * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be output - xmlattrStack.push(ns.getLevel()); - boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1; - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); - } - - SortedSet result = this.result; - 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. * @@ -385,10 +205,10 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { * @return none it always fails * @throws CanonicalizationException always */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); } /** @@ -399,17 +219,189 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { * @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. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- + * subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes() && !firstCall) { + return null; + } + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + // It's not a namespace attr node. Add to the result and continue. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) { + // The default mapping for xml must not be output. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + + if (n != null) { + // Render the ns definition + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()}; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } + } + + if (firstCall) { + // It is the first node of the subtree + // Obtain all the namespaces defined in the parents, and added to the output. + ns.getUnrenderedNodes(result); + // output the attributes in the xml namespace. + xmlattrStack.getXmlnsAttr(result); + firstCall = false; + } + + return result.iterator(); + } + + /** + * Returns the Attr[]s to be output for the given element. + *
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a + * DOM which has been prepared using + * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1; + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //A non namespace definition node. + if (XML_LANG_URI.equals(NUri)) { + 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { XMLUtils.circumventBug2650(doc); } - void handleParent(Element e, NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { return; } xmlattrStack.push(-1); NamedNodeMap attrs = e.getAttributes(); int attrsLength = attrs.getLength(); for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS != N.getNamespaceURI()) { - // Not a namespace definition, ignore. - if (XML_LANG_URI == N.getNamespaceURI()) { - xmlattrStack.addXmlnsAttr(N); - } - continue; - } + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); - String NName = N.getLocalName(); - String NValue = N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) { + if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { + ns.addMapping(NName, NValue, attribute); + } + } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) { + xmlattrStack.addXmlnsAttr(attribute); } - ns.addMapping(NName,NValue,N); + } + 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); } } - 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { bauthority = base.getAuthority(); bpath = base.getPath(); bquery = base.getQuery(); - bfragment = base.getFragment(); } URI r = new URI(relativeURI); @@ -472,9 +470,8 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } // 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { // 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } 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 @@ public abstract class Canonicalizer11 extends CanonicalizerBase { } } 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('/'); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java index 31903667f60..12a31f67d80 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java index ba650c10872..635e778b7a2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java index b0b2e0b729c..3af83dd11f1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import java.io.IOException; import java.util.ArrayList; import java.util.Collection; @@ -47,344 +47,348 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * Implements Canonical * XML Version 1.0, a W3C Recommendation from 15 March 2001. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class Canonicalizer20010315 extends CanonicalizerBase { - boolean firstCall=true; - final SortedSet result= new TreeSet(COMPARE); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS; - static class XmlAttrStack { - int currentLevel=0; - int lastlevel=0; - XmlsStackElement cur; + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + + private boolean firstCall = true; + private final SortedSet result = new TreeSet(COMPARE); + + private static class XmlAttrStack { static class XmlsStackElement { - int level; - boolean rendered=false; - List nodes=new ArrayList(); + int level; + boolean rendered = false; + List nodes = new ArrayList(); }; - List levels=new ArrayList(); + + int currentLevel = 0; + int lastlevel = 0; + XmlsStackElement cur; + List levels = new ArrayList(); + void push(int level) { - currentLevel=level; - if (currentLevel==-1) - return; - cur=null; - while (lastlevel>=currentLevel) { - levels.remove(levels.size()-1); - if (levels.size()==0) { - lastlevel=0; - return; - } - lastlevel=(levels.get(levels.size()-1)).level; + currentLevel = level; + if (currentLevel == -1) { + return; + } + cur = null; + while (lastlevel >= currentLevel) { + levels.remove(levels.size() - 1); + int newSize = levels.size(); + if (newSize == 0) { + lastlevel = 0; + return; } + lastlevel = (levels.get(newSize - 1)).level; + } } + void addXmlnsAttr(Attr n) { - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - levels.add(cur); - lastlevel=currentLevel; - } - cur.nodes.add(n); + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + levels.add(cur); + lastlevel = currentLevel; + } + cur.nodes.add(n); } + void getXmlnsAttr(Collection col) { - int size=levels.size()-1; - if (cur==null) { - cur=new XmlsStackElement(); - cur.level=currentLevel; - lastlevel=currentLevel; - levels.add(cur); + int size = levels.size() - 1; + if (cur == null) { + cur = new XmlsStackElement(); + cur.level = currentLevel; + lastlevel = currentLevel; + levels.add(cur); + } + boolean parentRendered = false; + XmlsStackElement e = null; + if (size == -1) { + parentRendered = true; + } else { + e = levels.get(size); + if (e.rendered && e.level + 1 == currentLevel) { + parentRendered = true; } - boolean parentRendered=false; - XmlsStackElement e=null; - if (size==-1) { - parentRendered=true; - } else { - e=levels.get(size); - if (e.rendered && e.level+1==currentLevel) - parentRendered=true; + } + if (parentRendered) { + col.addAll(cur.nodes); + cur.rendered = true; + return; + } + Map loa = new HashMap(); + for (; size >= 0; size--) { + e = levels.get(size); + Iterator it = e.nodes.iterator(); + while (it.hasNext()) { + Attr n = it.next(); + if (!loa.containsKey(n.getName())) { + loa.put(n.getName(), n); + } } - if (parentRendered) { - col.addAll(cur.nodes); - cur.rendered=true; - return; - } + } - Map loa = new HashMap(); - for (;size>=0;size--) { - e=levels.get(size); - Iterator it=e.nodes.iterator(); - while (it.hasNext()) { - Attr n=it.next(); - if (!loa.containsKey(n.getName())) - loa.put(n.getName(),n); - } - //if (e.rendered) - //break; - - }; - //cur.nodes.clear(); - //cur.nodes.addAll(loa.values()); - cur.rendered=true; - col.addAll(loa.values()); + 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. - *
- * The code of this method is a copy of {@link #handleAttributes(Element, - * NameSpaceSymbTable)}, - * whereas it takes into account that subtree-c14n is -- well -- subtree-based. - * So if the element in question isRoot of c14n, it's parent is not in the - * node set, as well as all other ancestors. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException { - if (!E.hasAttributes() && !firstCall) { - return null; - } - // result will contain the attrs which have to be outputted - final SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = E.getAttributes(); - int attrsLength = attrs.getLength(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri =N.getNamespaceURI(); - - if (XMLNS_URI!=NUri) { - //It's not a namespace attr node. Add to the result and continue. - result.add(N); - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getValue(); - if (XML.equals(NName) - && XML_LANG_URI.equals(NValue)) { - //The default mapping for xml must not be output. - continue; - } - - Node n=ns.addMappingAndRender(NName,NValue,N); - - if (n!=null) { - //Render the ns definition - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } - - if (firstCall) { - //It is the first node of the subtree - //Obtain all the namespaces defined in the parents, and added to the output. - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); - //output the attributes in the xml namespace. - xmlattrStack.getXmlnsAttr(result); - firstCall=false; - } - - return result.iterator(); - } - - /** - * Returns the Attr[]s to be outputted for the given element. - *
- * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has - * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( - * org.w3c.dom.Document)}. - * - * @param E - * @param ns - * @return the Attr[]s to be outputted - * @throws CanonicalizationException - */ - Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException { - // result will contain the attrs which have to be outputted - xmlattrStack.push(ns.getLevel()); - boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1; - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs=E.getAttributes(); - attrsLength= attrs.getLength(); + * 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 xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { - SortedSet result = this.result; - result.clear(); + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - String NUri =N.getNamespaceURI(); + /** + * 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; - } - //The xpath select this node output it if needed. - //Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); - Node n=ns.addMappingAndRender(NName,NValue,N); - if (n!=null) { - result.add((Attr)n); - if (C14nHelper.namespaceIsRelative(N)) { - Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; - throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); - } - } - } else { - if (isRealVisible && NName!=XMLNS) { - ns.removeMapping(NName); - } else { - ns.addMapping(NName,NValue,N); - } + /** + * Returns the Attr[]s to be output for the given element. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes() && !firstCall) { + return null; } + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //It's not a namespace attr node. Add to the result and continue. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) { + //The default mapping for xml must not be output. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + + if (n != null) { + //Render the ns definition + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } + } + + if (firstCall) { + //It is the first node of the subtree + //Obtain all the namespaces defined in the parents, and added to the output. + ns.getUnrenderedNodes(result); + //output the attributes in the xml namespace. + xmlattrStack.getXmlnsAttr(result); + firstCall = false; + } + + return result.iterator(); } - if (isRealVisible) { - //The element is visible, handle the xmlns definition - Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS); - Node n=null; - if (xmlns == null) { + + /** + * Returns the Attr[]s to be output for the given element. + *
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has + * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650( + * org.w3c.dom.Document)}. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + xmlattrStack.push(ns.getLevel()); + boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1; + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NUri = attribute.getNamespaceURI(); + String NName = attribute.getLocalName(); + String NValue = attribute.getValue(); + + if (!XMLNS_URI.equals(NUri)) { + //A non namespace definition node. + if (XML_LANG_URI.equals(NUri)) { + xmlattrStack.addXmlnsAttr(attribute); + } else if (isRealVisible) { + //The node is visible add the attribute to the list of output attributes. + result.add(attribute); + } + } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) { + /* except omit namespace node with local name xml, which defines + * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace. + */ + //add the prefix binding to the ns symb table. + if (isVisible(attribute)) { + if (isRealVisible || !ns.removeMappingIfRender(NName)) { + //The xpath select this node output it if needed. + Node n = ns.addMappingAndRender(NName, NValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } else { + if (isRealVisible && !XMLNS.equals(NName)) { + ns.removeMapping(NName); + } else { + ns.addMapping(NName, NValue, attribute); + } + } + } + } + } + if (isRealVisible) { + //The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + Node n = null; + if (xmlns == null) { //No xmlns def just get the already defined. - n=ns.getMapping(XMLNS); - } else if ( !isVisible(xmlns)) { + n = ns.getMapping(XMLNS); + } else if (!isVisible(xmlns)) { //There is a definition but the xmlns is not selected by the xpath. //then xmlns="" - n=ns.addMappingAndRender(XMLNS,"",nullNode); + n = ns.addMappingAndRender(XMLNS, "", nullNode); + } + //output the xmlns def if needed. + if (n != null) { + result.add((Attr)n); + } + //Float all xml:* attributes of the unselected parent elements to this one. + xmlattrStack.getXmlnsAttr(result); + ns.getUnrenderedNodes(result); } - //output the xmlns def if needed. - if (n!=null) { - result.add((Attr)n); - } - //Float all xml:* attributes of the unselected parent elements to this one. - //addXmlAttributes(E,result); - xmlattrStack.getXmlnsAttr(result); - ns.getUnrenderedNodes(getSortedSetAsCollection(result)); + return result.iterator(); } - return result.iterator(); - } - /** - * Always throws a CanonicalizationException because this is inclusive c14n. - * - * @param xpathNodeSet - * @param inclusiveNamespaces - * @return none it always fails - * @throws CanonicalizationException always - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) - throws CanonicalizationException { + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + if (!input.isNeedsToBeExpanded()) { + return; + } + Document doc = null; + if (input.getSubNode() != null) { + doc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + doc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } + XMLUtils.circumventBug2650(doc); + } - /** $todo$ well, should we throw UnsupportedOperationException ? */ - throw new CanonicalizationException( - "c14n.Canonicalizer.UnsupportedOperation"); - } + @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(); - /** - * 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); - } - } + 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); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java index 9dec09b4588..b8c869c83f7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java @@ -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.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; @@ -40,6 +41,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; + /** * Implements " Exclusive XML @@ -52,301 +54,279 @@ import org.xml.sax.SAXException; * THIS implementation is a complete rewrite of the algorithm. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ + * @version $Revision: 1147448 $ * @see * XML Canonicalization, Version 1.0 */ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { + + private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS; + private static final String XMLNS_URI = Constants.NamespaceSpecNS; + /** * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of * the inclusive namespaces. */ - TreeSet _inclusiveNSSet = new TreeSet(); - static final String XMLNS_URI=Constants.NamespaceSpecNS; - final SortedSet result = new TreeSet(COMPARE); - /** - * Constructor Canonicalizer20010315Excl - * - * @param includeComments - */ - public Canonicalizer20010315Excl(boolean includeComments) { - super(includeComments); - } + private SortedSet inclusiveNSSet; - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, "",null); - } - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @param inclusiveNamespaces - * - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode, - String inclusiveNamespaces) throws CanonicalizationException { - return this.engineCanonicalizeSubTree(rootNode, inclusiveNamespaces,null); - } - /** - * Method engineCanonicalizeSubTree - * @param rootNode + private final SortedSet result = new TreeSet(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 { - 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); - } - - /** - * Method handleAttributesSubtree - * @inheritDoc - * @param E - * @throws CanonicalizationException - */ - Iterator handleAttributesSubtree(Element E,NameSpaceSymbTable ns) - throws CanonicalizationException { - // System.out.println("During the traversal, I encountered " + - // XMLUtils.getXPath(E)); - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs=null; - - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); - } - //The prefix visibly utilized(in the attribute or in the name) in the element - SortedSet visiblyUtilized = getNSSetClone(); - - for (int i = 0; i < attrsLength; i++) { - Attr N = (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=N.getLocalName(); - String NNodeValue=N.getNodeValue(); - - 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); - } - } - } - String prefix; - if (E.getNamespaceURI() != null) { - prefix = E.getPrefix(); - if ((prefix == null) || (prefix.length() == 0)) { - prefix=XMLNS; - } - - } else { - prefix=XMLNS; - } - visiblyUtilized.add(prefix); - - //This can be optimezed by I don't have time - Iterator it=visiblyUtilized.iterator(); - while (it.hasNext()) { - String s=it.next(); - Attr key=ns.getMapping(s); - if (key==null) { - continue; - } - result.add(key); - } - - return result.iterator(); - } - - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @param inclusiveNamespaces - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, - String inclusiveNamespaces) throws CanonicalizationException { - - this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces); - return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); - - } - - @SuppressWarnings("unchecked") - private TreeSet getInclusiveNameSpace(String inclusiveNameSpaces) { - return (TreeSet)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces); + * @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); } - - @SuppressWarnings("unchecked") - private SortedSet getNSSetClone() { - return (SortedSet) this._inclusiveNSSet.clone(); + /** + * + * @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 E - * @throws CanonicalizationException - */ - final Iterator handleAttributes(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException { - // result will contain the attrs which have to be outputted - SortedSet result = this.result; - result.clear(); - NamedNodeMap attrs = null; - int attrsLength = 0; - if (E.hasAttributes()) { - attrs = E.getAttributes(); - attrsLength = attrs.getLength(); + * @param xpathNodeSet + * @param inclusiveNamespaces + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet( + Set xpathNodeSet, String inclusiveNamespaces + ) throws CanonicalizationException { + inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces); + return super.engineCanonicalizeXPathNodeSet(xpathNodeSet); + } + + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + SortedSet visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); } - //The prefix visibly utilized(in the attribute or in the name) in the element - Set visiblyUtilized =null; - //It's the output selected. - boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1; - if (isOutputElement) { - visiblyUtilized = getNSSetClone(); - } - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); + if (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!=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()}; + if (!XMLNS_URI.equals(attribute.getNamespaceURI())) { + // Not a namespace definition. + // The Element is output element, add the prefix (if used) to + // visiblyUtilized + String prefix = attribute.getPrefix(); + if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) { + visiblyUtilized.add(prefix); + } + // Add to the result. + result.add(attribute); + } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NNodeValue)) + && ns.addMapping(NName, NNodeValue, attribute) + && C14nHelper.namespaceIsRelative(NNodeValue)) { + // The default mapping for xml must not be output. + // New definition check if it is relative. + Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()}; throw new CanonicalizationException( - "c14n.Canonicalizer.RelativeNamespace", exArgs); + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); } } - } - - 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 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()); - } + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; + } + visiblyUtilized.add(prefix); - XMLUtils.circumventBug2650(doc); - } + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } + + return result.iterator(); + } + + /** + * @inheritDoc + * @param element + * @throws CanonicalizationException + */ + @Override + protected final Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + // result will contain the attrs which have to be output + final SortedSet result = this.result; + result.clear(); + + // The prefix visibly utilized (in the attribute or in the name) in + // the element + Set visiblyUtilized = null; + // It's the output selected. + boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1; + if (isOutputElement) { + visiblyUtilized = new TreeSet(); + if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) { + visiblyUtilized.addAll(inclusiveNSSet); + } + } + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + + String NName = attribute.getLocalName(); + String NNodeValue = attribute.getNodeValue(); + + if (!XMLNS_URI.equals(attribute.getNamespaceURI())) { + if (isVisible(attribute) && isOutputElement) { + // The Element is output element, add the prefix (if used) + // to visibyUtilized + String prefix = attribute.getPrefix(); + if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) { + visiblyUtilized.add(prefix); + } + // Add to the result. + result.add(attribute); + } + } else if (isOutputElement && !isVisible(attribute) && !XMLNS.equals(NName)) { + ns.removeMappingIfNotRender(NName); + } else { + if (!isOutputElement && isVisible(attribute) + && inclusiveNSSet.contains(NName) + && !ns.removeMappingIfRender(NName)) { + Node n = ns.addMappingAndRender(NName, NNodeValue, attribute); + if (n != null) { + result.add((Attr)n); + if (C14nHelper.namespaceIsRelative(attribute)) { + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + + if (ns.addMapping(NName, NNodeValue, attribute) + && C14nHelper.namespaceIsRelative(NNodeValue)) { + // New definition check if it is relative + Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() }; + throw new CanonicalizationException( + "c14n.Canonicalizer.RelativeNamespace", exArgs + ); + } + } + } + } + + if (isOutputElement) { + // The element is visible, handle the xmlns definition + Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS); + if (xmlns != null && !isVisible(xmlns)) { + // There is a definition but the xmlns is not selected by the + // xpath. then xmlns="" + ns.addMapping(XMLNS, "", nullNode); + } + + String prefix = null; + if (element.getNamespaceURI() != null + && !(element.getPrefix() == null || element.getPrefix().length() == 0)) { + prefix = element.getPrefix(); + } else { + prefix = XMLNS; + } + visiblyUtilized.add(prefix); + + for (String s : visiblyUtilized) { + Attr key = ns.getMapping(s); + if (key != null) { + result.add(key); + } + } + } + + return result.iterator(); + } + + 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); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java index 0910b980484..0fb402275a1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package com.sun.org.apache.xml.internal.security.c14n.implementations; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; -/** - * - * - */ -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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java index 37550124879..1ea477ac970 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** * Class Canonicalizer20010315ExclWithComments - * - * @version $Revision: 1.5 $ */ -public class Canonicalizer20010315ExclWithComments - extends Canonicalizer20010315Excl { +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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java index 481642e6bac..2e21cc0b2dd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; - /** - * * @author Christian Geuer-Pollmann */ public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 { - /** - * Constructor Canonicalizer20010315WithXPathOmitComments - * - */ - public Canonicalizer20010315OmitComments() { - super(false); - } + /** + * 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; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java index 4714e165bba..bf56bfb6950 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; /** - * * @author Christian Geuer-Pollmann */ public class Canonicalizer20010315WithComments extends Canonicalizer20010315 { - /** - * Constructor Canonicalizer20010315WithXPathWithComments - * - */ - public Canonicalizer20010315WithComments() { - super(true); - } + /** + * Constructor Canonicalizer20010315WithXPathWithComments + */ + public Canonicalizer20010315WithComments() { + super(true); + } - /** @inheritDoc */ - public final String engineGetURI() { - return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; - } + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + } - /** @inheritDoc */ - public final boolean engineGetIncludeComments() { - return true; - } + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java index 2f5f28904d2..4c9f277f65e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; - - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -33,12 +33,10 @@ import java.util.List; 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.Node; import org.w3c.dom.ProcessingInstruction; import org.xml.sax.SAXException; - /** * Abstract base class for canonicalization algorithms. * * @author Christian Geuer-Pollmann - * @version $Revision: 1.5 $ */ public abstract class CanonicalizerBase extends CanonicalizerSpi { - //Constants to be outputed, In char array form, so - //less garbage is generate when outputed. - private static final byte[] _END_PI = {'?','>'}; - private static final byte[] _BEGIN_PI = {'<','?'}; - private static final byte[] _END_COMM = {'-','-','>'}; - private static final byte[] _BEGIN_COMM = {'<','!','-','-'}; - private static final byte[] __XA_ = {'&','#','x','A',';'}; - private static final byte[] __X9_ = {'&','#','x','9',';'}; - private static final byte[] _QUOT_ = {'&','q','u','o','t',';'}; - private static final byte[] __XD_ = {'&','#','x','D',';'}; - private static final byte[] _GT_ = {'&','g','t',';'}; - private static final byte[] _LT_ = {'&','l','t',';'}; - private static final byte[] _END_TAG = {'<','/'}; - private static final byte[] _AMP_ = {'&','a','m','p',';'}; - final static AttrCompare COMPARE=new AttrCompare(); - final static String XML="xml"; - final static String XMLNS="xmlns"; - final static byte[] equalsStr= {'=','\"'}; - static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - //The null xmlns definiton. - protected static final Attr nullNode; - static { - try { - nullNode=DocumentBuilderFactory.newInstance(). - newDocumentBuilder().newDocument().createAttributeNS(Constants.NamespaceSpecNS,XMLNS); - nullNode.setValue(""); - } catch (Exception e) { - throw new RuntimeException("Unable to create nullNode"/*,*/+e); - } - } + public static final String XML = "xml"; + public static final String XMLNS = "xmlns"; - List nodeFilter; + protected static final AttrCompare COMPARE = new AttrCompare(); + protected static final Attr nullNode; - boolean _includeComments; - Set _xpathNodeSet = null; - /** - * The node to be skiped/excluded from the DOM tree - * in subtree canonicalizations. - */ - Node _excludeNode =null; - OutputStream _writer = new UnsyncByteArrayOutputStream();//null; + 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 = {'=','\"'}; - /** - * Constructor CanonicalizerBase - * - * @param includeComments - */ - public CanonicalizerBase(boolean includeComments) { - this._includeComments = includeComments; - } + 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; - /** - * Method engineCanonicalizeSubTree - * @inheritDoc - * @param rootNode - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeSubTree(Node rootNode) - throws CanonicalizationException { - return engineCanonicalizeSubTree(rootNode,(Node)null); - } - /** - * Method engineCanonicalizeXPathNodeSet - * @inheritDoc - * @param xpathNodeSet - * @throws CanonicalizationException - */ - public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) - throws CanonicalizationException { - this._xpathNodeSet = xpathNodeSet; - return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet)); - } - - /** - * Canonicalizes a Subtree node. - * @param input the root of the subtree to canicalize - * @return The canonicalize stream. - * @throws CanonicalizationException - */ - public byte[] engineCanonicalize(XMLSignatureInput input) - throws CanonicalizationException { + static { + // The null xmlns definition. 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(); + 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); + } + } - circumventBugIfNeeded(input); + private List nodeFilter; - if (input.getSubNode() != null) { - bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); - } else { - bytes = engineCanonicalizeXPathNodeSet(input.getNodeSet()); - } - return bytes; + private boolean includeComments; + private Set xpathNodeSet; + /** + * The node to be skipped/excluded from the DOM tree + * in subtree canonicalizations. + */ + private Node excludeNode; + private OutputStream writer = new ByteArrayOutputStream(); - } - return null; - } catch (CanonicalizationException ex) { - throw new CanonicalizationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } catch (SAXException ex) { - throw new CanonicalizationException("empty", ex); - } - } - /** - * @param _writer The _writer to set. - */ - public void setWriter(OutputStream _writer) { - this._writer = _writer; + /** + * Constructor CanonicalizerBase + * + * @param includeComments + */ + public CanonicalizerBase(boolean includeComments) { + this.includeComments = includeComments; } /** - * 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; + * Method engineCanonicalizeSubTree + * @inheritDoc + * @param rootNode + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode) + throws CanonicalizationException { + return engineCanonicalizeSubTree(rootNode, (Node)null); + } + + /** + * Method engineCanonicalizeXPathNodeSet + * @inheritDoc + * @param xpathNodeSet + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet) + throws CanonicalizationException { + this.xpathNodeSet = xpathNodeSet; + return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet)); + } + + /** + * Canonicalizes a Subtree node. + * @param input the root of the subtree to canicalize + * @return The canonicalize stream. + * @throws CanonicalizationException + */ + public byte[] engineCanonicalize(XMLSignatureInput input) throws CanonicalizationException { try { - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) { - //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(); + 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) { + return engineCanonicalizeXPathNodeSetInternal(input.getSubNode()); + } else { + return engineCanonicalizeXPathNodeSet(input.getNodeSet()); + } + } + return null; + } catch (CanonicalizationException ex) { + throw new CanonicalizationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new CanonicalizationException("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } catch (SAXException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + /** + * @param writer The writer to set. + */ + public void setWriter(OutputStream writer) { + this.writer = writer; + } + + /** + * Canonicalizes a Subtree node. + * + * @param rootNode + * the root of the subtree to 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 && 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.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 cache=new HashMap(); + /** + * Method canonicalizeSubTree, this function is a recursive one. + * + * @param currentNode + * @param ns + * @param endnode + * @throws CanonicalizationException + * @throws IOException + */ + protected final void canonicalizeSubTree( + Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel + ) throws CanonicalizationException, IOException { + if (isVisibleInt(currentNode) == -1) { + return; + } + Node sibling = null; + Node parentNode = null; + final OutputStream writer = this.writer; + final Node excludeNode = this.excludeNode; + final boolean includeComments = this.includeComments; + Map cache = new HashMap(); do { - switch (currentNode.getNodeType()) { + switch (currentNode.getNodeType()) { - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); + case Node.ENTITY_NODE : + case Node.NOTATION_NODE : + case Node.ATTRIBUTE_NODE : + // illegal node type during traversal + throw new CanonicalizationException("empty"); case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - sibling= currentNode.getFirstChild(); - break; + case Node.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; - case Node.COMMENT_NODE : - if (includeComments) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE : - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; - - case Node.TEXT_NODE : - case Node.CDATA_SECTION_NODE : - outputTextToWriter(currentNode.getNodeValue(), writer); - break; - - case Node.ELEMENT_NODE : - documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - if (currentNode==excludeNode) { - break; - } - Element currentElement = (Element) currentNode; - //Add a level to the nssymbtable. So latter can be pop-back. - ns.outputNodePush(); - writer.write('<'); - String name=currentElement.getTagName(); - UtfHelpper.writeByte(name,writer,cache); - - Iterator attrs = this.handleAttributesSubtree(currentElement,ns); - if (attrs!=null) { - //we output all Attrs which are available - while (attrs.hasNext()) { - Attr attr = attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); - } - } - writer.write('>'); - sibling= currentNode.getFirstChild(); - if (sibling==null) { - writer.write(_END_TAG); - UtfHelpper.writeStringToUtf8(name,writer); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - if (parentNode != null) { - sibling= currentNode.getNextSibling(); - } - } else { - parentNode=currentElement; - } - break; + case Node.COMMENT_NODE : + if (includeComments) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); } - while (sibling==null && parentNode!=null) { - writer.write(_END_TAG); - UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - if (parentNode==endnode) - return; - sibling=parentNode.getNextSibling(); - parentNode=parentNode.getParentNode(); - if (parentNode !=null && parentNode.getNodeType() != Node.ELEMENT_NODE) { - documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; - parentNode=null; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); - } while(true); - } + 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; - private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) - throws CanonicalizationException { - - 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(); - } - return sol; - } else if (this._writer instanceof UnsyncByteArrayOutputStream) { - byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray(); - if (reset) { - ((UnsyncByteArrayOutputStream)this._writer).reset(); - } - return result; - } - return null; - } catch (UnsupportedEncodingException ex) { - throw new CanonicalizationException("empty", ex); - } catch (IOException ex) { - throw new CanonicalizationException("empty", ex); - } - } - - /** - * Canoicalizes all the nodes included in the currentNode and contained in the - * _xpathNodeSet field. - * - * @param currentNode - * @param endnode - * @throws CanonicalizationException - * @throws IOException - */ - final void canonicalizeXPathNodeSet(Node currentNode,Node endnode ) - throws CanonicalizationException, IOException { - if (isVisibleInt(currentNode)==-1) - return; - boolean currentNodeIsVisible = false; - NameSpaceSymbTable ns=new NameSpaceSymbTable(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) - getParentNameSpaces((Element)currentNode,ns); - Node sibling=null; - Node parentNode=null; - OutputStream writer=this._writer; - int documentLevel=NODE_BEFORE_DOCUMENT_ELEMENT; - Map cache=new HashMap(); - do { - switch (currentNode.getNodeType()) { - - case Node.DOCUMENT_TYPE_NODE : - default : - break; - - case Node.ENTITY_NODE : - case Node.NOTATION_NODE : - case Node.ATTRIBUTE_NODE : - // illegal node type during traversal - throw new CanonicalizationException("empty"); - - case Node.DOCUMENT_FRAGMENT_NODE : - case Node.DOCUMENT_NODE : - ns.outputNodePush(); - //currentNode = currentNode.getFirstChild(); - sibling= currentNode.getFirstChild(); - break; - - case Node.COMMENT_NODE : - if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) { - outputCommentToWriter((Comment) currentNode, writer, documentLevel); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE : - if (isVisible(currentNode)) - outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); - break; - - case Node.TEXT_NODE : - case Node.CDATA_SECTION_NODE : - if (isVisible(currentNode)) { - outputTextToWriter(currentNode.getNodeValue(), writer); - for (Node nextSibling = currentNode.getNextSibling(); - (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) - || (nextSibling.getNodeType() - == Node.CDATA_SECTION_NODE)); - nextSibling = nextSibling.getNextSibling()) { - outputTextToWriter(nextSibling.getNodeValue(), writer); - currentNode=nextSibling; - sibling=currentNode.getNextSibling(); - } - - } - break; - - case Node.ELEMENT_NODE : - documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - Element currentElement = (Element) currentNode; - //Add a level to the nssymbtable. So latter can be pop-back. - String name=null; - int i=isVisibleDO(currentNode,ns.getLevel()); - if (i==-1) { - sibling= currentNode.getNextSibling(); - break; - } - currentNodeIsVisible=(i==1); - if (currentNodeIsVisible) { - ns.outputNodePush(); - writer.write('<'); - name=currentElement.getTagName(); - UtfHelpper.writeByte(name,writer,cache); - } else { - ns.push(); - } - - Iterator attrs = handleAttributes(currentElement,ns); - if (attrs!=null) { - //we output all Attrs which are available - while (attrs.hasNext()) { - Attr attr = attrs.next(); - outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache); - } - } - if (currentNodeIsVisible) { - writer.write('>'); - } - sibling= currentNode.getFirstChild(); - - if (sibling==null) { - if (currentNodeIsVisible) { - writer.write(_END_TAG); - UtfHelpper.writeByte(name,writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - } else { - ns.pop(); - } - if (parentNode != null) { - sibling= currentNode.getNextSibling(); - } - } else { - parentNode=currentElement; - } - break; - } - while (sibling==null && parentNode!=null) { - if (isVisible(parentNode)) { - writer.write(_END_TAG); - UtfHelpper.writeByte(((Element)parentNode).getTagName(),writer,cache); - writer.write('>'); - //We fineshed with this level, pop to the previous definitions. - ns.outputNodePop(); - } else { - ns.pop(); - } - if (parentNode==endnode) - return; - sibling=parentNode.getNextSibling(); - parentNode=parentNode.getParentNode(); - if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) { - parentNode=null; - documentLevel=NODE_AFTER_DOCUMENT_ELEMENT; - } - } - if (sibling==null) - return; - currentNode=sibling; - sibling=currentNode.getNextSibling(); - } while(true); - } - int isVisibleDO(Node currentNode,int level) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - int i=(it.next()).isNodeIncludeDO(currentNode,level); - if (i!=1) - return i; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return 0; - return 1; - } - int isVisibleInt(Node currentNode) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - int i=(it.next()).isNodeInclude(currentNode); - if (i!=1) - return i; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return 0; - return 1; - } - - boolean isVisible(Node currentNode) { - if (nodeFilter!=null) { - Iterator it=nodeFilter.iterator(); - while (it.hasNext()) { - if ((it.next()).isNodeInclude(currentNode)!=1) - return false; - } - } - if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode)) - return false; - return true; - } - - void handleParent(Element e,NameSpaceSymbTable ns) { - if (!e.hasAttributes()) { - return; - } - NamedNodeMap attrs = e.getAttributes(); - int attrsLength = attrs.getLength(); - for (int i = 0; i < attrsLength; i++) { - Attr N = (Attr) attrs.item(i); - if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) { - //Not a namespace definition, ignore. - continue; - } - - String NName=N.getLocalName(); - String NValue=N.getNodeValue(); - if (XML.equals(NName) - && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) { - continue; - } - ns.addMapping(NName,NValue,N); - } - } - - /** - * Adds to ns the definitons from the parent elements of el - * @param el - * @param ns - */ - final void getParentNameSpaces(Element el,NameSpaceSymbTable ns) { - List parents=new ArrayList(10); - Node n1=el.getParentNode(); - if (n1 == null || n1.getNodeType() != Node.ELEMENT_NODE) { - return; - } - //Obtain all the parents of the elemnt - Node parent = n1; - while (parent!=null && parent.getNodeType() == Node.ELEMENT_NODE) { - parents.add((Element)parent); - parent = parent.getParentNode(); - } - //Visit them in reverse order. - ListIterator it=parents.listIterator(parents.size()); - while (it.hasPrevious()) { - Element ele=it.previous(); - handleParent(ele, ns); - } - Attr nsprefix; - if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null) - && "".equals(nsprefix.getValue())) { - ns.addMappingAndRender("xmlns","",nullNode); - } - } - /** - * Obtain the attributes to output for this node in XPathNodeSet c14n. - * - * @param E - * @param ns - * @return the attributes nodes to output. - * @throws CanonicalizationException - */ - abstract Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) - throws CanonicalizationException; - - /** - * Obtain the attributes to output for this node in a Subtree c14n. - * - * @param E - * @param ns - * @return the attributes nodes to output. - * @throws CanonicalizationException - */ - abstract Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns) - throws CanonicalizationException; - - abstract void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException; - - /** - * Outputs an Attribute to the internal Writer. - * - * The string value of the node is modified by replacing - *
    - *
  • all ampersands (&) with &amp;
  • - *
  • all open angle brackets (<) with &lt;
  • - *
  • all quotation mark characters with &quot;
  • - *
  • and the whitespace characters #x9, #xA, and #xD, with character - * references. The character references are written in uppercase - * hexadecimal with no leading zeroes (for example, #xD is represented - * by the character reference &#xD;)
  • - *
- * - * @param name - * @param value - * @param writer - * @throws IOException - */ - static final void outputAttrToWriter(final String name, final String value, final OutputStream writer, - final Map cache) throws IOException { - writer.write(' '); - UtfHelpper.writeByte(name,writer,cache); - writer.write(equalsStr); - byte []toWrite; - final int length = value.length(); - int i=0; - while (i < length) { - char c = value.charAt(i++); - - switch (c) { - - case '&' : - toWrite=_AMP_; + 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 '<' : - 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); + Iterator attrs = this.handleAttributesSubtree(currentElement, ns); + if (attrs != null) { + //we output all Attrs which are available + while (attrs.hasNext()) { + Attr attr = attrs.next(); + outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); } - } - } + } + writer.write('>'); + sibling = currentNode.getFirstChild(); + if (sibling == null) { + writer.write(END_TAG); + UtfHelpper.writeStringToUtf8(name, writer); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + if (parentNode != null) { + sibling = currentNode.getNextSibling(); + } + } else { + parentNode = currentElement; + } + break; - 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 getSortedSetAsCollection(SortedSet result) { - return (Collection)(Collection)result; + case Node.DOCUMENT_TYPE_NODE : + default : + break; + } + while (sibling == null && parentNode != null) { + writer.write(END_TAG); + UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + if (parentNode == endnode) { + return; + } + sibling = parentNode.getNextSibling(); + parentNode = parentNode.getParentNode(); + if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) { + documentLevel = NODE_AFTER_DOCUMENT_ELEMENT; + parentNode = null; + } + } + if (sibling == null) { + return; + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); + } while(true); } + private byte[] engineCanonicalizeXPathNodeSetInternal(Node doc) + throws CanonicalizationException { + try { + this.canonicalizeXPathNodeSet(doc, doc); + this.writer.flush(); + if (this.writer instanceof ByteArrayOutputStream) { + byte[] sol = ((ByteArrayOutputStream)this.writer).toByteArray(); + if (reset) { + ((ByteArrayOutputStream)this.writer).reset(); + } else { + this.writer.close(); + } + return sol; + } else if (this.writer instanceof UnsyncByteArrayOutputStream) { + byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray(); + if (reset) { + ((UnsyncByteArrayOutputStream)this.writer).reset(); + } else { + this.writer.close(); + } + return result; + } else { + this.writer.close(); + } + return null; + } catch (UnsupportedEncodingException ex) { + throw new CanonicalizationException("empty", ex); + } catch (IOException ex) { + throw new CanonicalizationException("empty", ex); + } + } + + /** + * Canonicalizes all the nodes included in the currentNode and contained in the + * xpathNodeSet field. + * + * @param currentNode + * @param endnode + * @throws CanonicalizationException + * @throws IOException + */ + protected final void canonicalizeXPathNodeSet(Node currentNode, Node endnode) + throws CanonicalizationException, IOException { + if (isVisibleInt(currentNode) == -1) { + return; + } + boolean currentNodeIsVisible = false; + NameSpaceSymbTable ns = new NameSpaceSymbTable(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + getParentNameSpaces((Element)currentNode, ns); + } + if (currentNode == null) { + return; + } + Node sibling = null; + Node parentNode = null; + OutputStream writer = this.writer; + int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT; + Map cache = new HashMap(); + do { + switch (currentNode.getNodeType()) { + + case Node.ENTITY_NODE : + case Node.NOTATION_NODE : + case Node.ATTRIBUTE_NODE : + // illegal node type during traversal + throw new CanonicalizationException("empty"); + + case Node.DOCUMENT_FRAGMENT_NODE : + case Node.DOCUMENT_NODE : + ns.outputNodePush(); + sibling = currentNode.getFirstChild(); + break; + + case Node.COMMENT_NODE : + if (this.includeComments && (isVisibleDO(currentNode, ns.getLevel()) == 1)) { + outputCommentToWriter((Comment) currentNode, writer, documentLevel); + } + break; + + case Node.PROCESSING_INSTRUCTION_NODE : + if (isVisible(currentNode)) { + outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel); + } + break; + + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE : + if (isVisible(currentNode)) { + outputTextToWriter(currentNode.getNodeValue(), writer); + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + outputTextToWriter(nextSibling.getNodeValue(), writer); + currentNode = nextSibling; + sibling = currentNode.getNextSibling(); + } + } + break; + + case Node.ELEMENT_NODE : + documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + Element currentElement = (Element) currentNode; + //Add a level to the nssymbtable. So latter can be pop-back. + String name = null; + int i = isVisibleDO(currentNode, ns.getLevel()); + if (i == -1) { + sibling = currentNode.getNextSibling(); + break; + } + currentNodeIsVisible = (i == 1); + if (currentNodeIsVisible) { + ns.outputNodePush(); + writer.write('<'); + name = currentElement.getTagName(); + UtfHelpper.writeByte(name, writer, cache); + } else { + ns.push(); + } + + Iterator attrs = handleAttributes(currentElement,ns); + if (attrs != null) { + //we output all Attrs which are available + while (attrs.hasNext()) { + Attr attr = attrs.next(); + outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache); + } + } + if (currentNodeIsVisible) { + writer.write('>'); + } + sibling = currentNode.getFirstChild(); + + if (sibling == null) { + if (currentNodeIsVisible) { + writer.write(END_TAG); + UtfHelpper.writeByte(name, writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + } else { + ns.pop(); + } + if (parentNode != null) { + sibling = currentNode.getNextSibling(); + } + } else { + parentNode = currentElement; + } + break; + + case Node.DOCUMENT_TYPE_NODE : + default : + break; + } + while (sibling == null && parentNode != null) { + if (isVisible(parentNode)) { + writer.write(END_TAG); + UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache); + writer.write('>'); + //We finished with this level, pop to the previous definitions. + ns.outputNodePop(); + } else { + ns.pop(); + } + if (parentNode == endnode) { + return; + } + sibling = parentNode.getNextSibling(); + parentNode = parentNode.getParentNode(); + if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) { + parentNode = null; + documentLevel = NODE_AFTER_DOCUMENT_ELEMENT; + } + } + if (sibling == null) { + return; + } + currentNode = sibling; + sibling = currentNode.getNextSibling(); + } while(true); + } + + protected int isVisibleDO(Node currentNode, int level) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + int i = (it.next()).isNodeIncludeDO(currentNode, level); + if (i != 1) { + return i; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return 0; + } + return 1; + } + + protected int isVisibleInt(Node currentNode) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + int i = (it.next()).isNodeInclude(currentNode); + if (i != 1) { + return i; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return 0; + } + return 1; + } + + protected boolean isVisible(Node currentNode) { + if (nodeFilter != null) { + Iterator it = nodeFilter.iterator(); + while (it.hasNext()) { + if (it.next().isNodeInclude(currentNode) != 1) { + return false; + } + } + } + if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) { + return false; + } + return true; + } + + protected void handleParent(Element e, NameSpaceSymbTable ns) { + if (!e.hasAttributes() && e.getNamespaceURI() == null) { + return; + } + NamedNodeMap attrs = e.getAttributes(); + int attrsLength = attrs.getLength(); + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + String NName = attribute.getLocalName(); + String NValue = attribute.getNodeValue(); + + if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI()) + && (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue))) { + ns.addMapping(NName, NValue, attribute); + } + } + if (e.getNamespaceURI() != null) { + String NName = e.getPrefix(); + String NValue = e.getNamespaceURI(); + String Name; + if (NName == null || NName.equals("")) { + NName = XMLNS; + Name = XMLNS; + } else { + Name = XMLNS + ":" + NName; + } + Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name); + n.setValue(NValue); + ns.addMapping(NName, NValue, n); + } + } + + /** + * Adds to ns the definitions from the parent elements of el + * @param el + * @param ns + */ + protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) { + Node n1 = el.getParentNode(); + if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) { + return; + } + //Obtain all the parents of the element + List parents = new ArrayList(); + Node parent = n1; + while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) { + parents.add((Element)parent); + parent = parent.getParentNode(); + } + //Visit them in reverse order. + ListIterator it = parents.listIterator(parents.size()); + while (it.hasPrevious()) { + Element ele = it.previous(); + handleParent(ele, ns); + } + parents.clear(); + Attr nsprefix; + if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null) + && "".equals(nsprefix.getValue())) { + ns.addMappingAndRender(XMLNS, "", nullNode); + } + } + + /** + * Obtain the attributes to output for this node in XPathNodeSet c14n. + * + * @param element + * @param ns + * @return the attributes nodes to output. + * @throws CanonicalizationException + */ + abstract Iterator 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 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 + *
    + *
  • all ampersands (&) with &amp;
  • + *
  • all open angle brackets (<) with &lt;
  • + *
  • all quotation mark characters with &quot;
  • + *
  • and the whitespace characters #x9, #xA, and #xD, with character + * references. The character references are written in uppercase + * hexadecimal with no leading zeroes (for example, #xD is represented + * by the character reference &#xD;)
  • + *
+ * + * @param name + * @param value + * @param writer + * @throws IOException + */ + protected static final void outputAttrToWriter( + final String name, final String value, + final OutputStream writer, final Map cache + ) throws IOException { + writer.write(' '); + UtfHelpper.writeByte(name, writer, cache); + writer.write(equalsStr); + byte[] toWrite; + final int length = value.length(); + int i = 0; + while (i < length) { + char c = value.charAt(i++); + + switch (c) { + + case '&' : + toWrite = AMP; + break; + + case '<' : + toWrite = LT; + break; + + case '"' : + toWrite = QUOT; + break; + + case 0x09 : // '\t' + toWrite = X9; + break; + + case 0x0A : // '\n' + toWrite = XA; + break; + + case 0x0D : // '\r' + toWrite = XD; + break; + + default : + if (c < 0x80) { + writer.write(c); + } else { + UtfHelpper.writeCharToUtf8(c, writer); + } + continue; + } + writer.write(toWrite); + } + + 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); + } + } + } + + 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 + */ + 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); + } + } + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java new file mode 100644 index 00000000000..17d8705a210 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java @@ -0,0 +1,184 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.c14n.implementations; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import org.w3c.dom.Attr; +import org.w3c.dom.Comment; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; +import org.xml.sax.SAXException; + +/** + * Serializes the physical representation of the subtree. All the attributes + * present in the subtree are emitted. The attributes are sorted within an element, + * with the namespace declarations appearing before the regular attributes. + * This algorithm is not a true canonicalization since equivalent subtrees + * may produce different output. It is therefore unsuitable for digital signatures. + * This same property makes it ideal for XML Encryption Syntax and Processing, + * because the decrypted XML content will share the same physical representation + * as the original XML content that was encrypted. + */ +public class CanonicalizerPhysical extends CanonicalizerBase { + + private final SortedSet result = new TreeSet(COMPARE); + + /** + * Constructor Canonicalizer20010315 + */ + public CanonicalizerPhysical() { + super(true); + } + + /** + * Always throws a CanonicalizationException. + * + * @param xpathNodeSet + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException always + */ + public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Always throws a CanonicalizationException. + * + * @param rootNode + * @param inclusiveNamespaces + * @return none it always fails + * @throws CanonicalizationException + */ + public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + /** + * Returns the Attr[]s to be output for the given element. + *
+ * The code of this method is a copy of {@link #handleAttributes(Element, + * NameSpaceSymbTable)}, + * whereas it takes into account that subtree-c14n is -- well -- subtree-based. + * So if the element in question isRoot of c14n, it's parent is not in the + * node set, as well as all other ancestors. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributesSubtree(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + if (!element.hasAttributes()) { + return null; + } + + // result will contain all the attrs declared directly on that element + final SortedSet result = this.result; + result.clear(); + + if (element.hasAttributes()) { + NamedNodeMap attrs = element.getAttributes(); + int attrsLength = attrs.getLength(); + + for (int i = 0; i < attrsLength; i++) { + Attr attribute = (Attr) attrs.item(i); + result.add(attribute); + } + } + + return result.iterator(); + } + + /** + * Returns the Attr[]s to be output for the given element. + * + * @param element + * @param ns + * @return the Attr[]s to be output + * @throws CanonicalizationException + */ + @Override + protected Iterator handleAttributes(Element element, NameSpaceSymbTable ns) + throws CanonicalizationException { + + /** $todo$ well, should we throw UnsupportedOperationException ? */ + throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation"); + } + + protected void circumventBugIfNeeded(XMLSignatureInput input) + throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { + // nothing to do + } + + @Override + protected void handleParent(Element e, NameSpaceSymbTable ns) { + // nothing to do + } + + /** @inheritDoc */ + public final String engineGetURI() { + return Canonicalizer.ALGO_ID_C14N_PHYSICAL; + } + + /** @inheritDoc */ + public final boolean engineGetIncludeComments() { + return true; + } + + @Override + protected void outputPItoWriter(ProcessingInstruction currentPI, + OutputStream writer, int position) throws IOException { + // Processing Instructions before or after the document element are not treated specially + super.outputPItoWriter(currentPI, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT); + } + + @Override + protected void outputCommentToWriter(Comment currentComment, + OutputStream writer, int position) throws IOException { + // Comments before or after the document element are not treated specially + super.outputCommentToWriter(currentComment, writer, NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT); + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java index 114bf7e0a86..54ae150b30e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.c14n.implementations; @@ -29,191 +31,185 @@ import java.util.List; import org.w3c.dom.Attr; import org.w3c.dom.Node; - - /** - * A stack based Symble Table. + * A stack based Symbol Table. *
For speed reasons all the symbols are introduced in the same map, * and at the same time in a list so it can be removed when the frame is pop back. * @author Raul Benito - **/ + */ public class NameSpaceSymbTable { - /**The map betwen prefix-> entry table. */ - SymbMap symb; - /**The level of nameSpaces (for Inclusive visibility).*/ - int nameSpaces=0; - /**The stacks for removing the definitions when doing pop.*/ - List level; - boolean cloned=true; - static final String XMLNS="xmlns"; - final static SymbMap initialMap=new SymbMap(); - static { - NameSpaceSymbEntry ne=new NameSpaceSymbEntry("",null,true,XMLNS); - ne.lastrendered=""; - initialMap.put(XMLNS,ne); - } + private static final String XMLNS = "xmlns"; + private static final SymbMap initialMap = new SymbMap(); + + static { + NameSpaceSymbEntry ne = new NameSpaceSymbEntry("", null, true, XMLNS); + ne.lastrendered = ""; + initialMap.put(XMLNS, ne); + } + + /**The map betwen prefix-> entry table. */ + private SymbMap symb; + + /**The stacks for removing the definitions when doing pop.*/ + private List level; + private boolean cloned = true; + /** * Default constractor **/ public NameSpaceSymbTable() { - level = new ArrayList(10); + level = new ArrayList(); //Insert the default binding for xmlns. - symb=(SymbMap) initialMap.clone(); + symb = (SymbMap) initialMap.clone(); } /** - * Get all the unrendered nodes in the name space. - * For Inclusive rendering + * Get all the unrendered nodes in the name space. + * For Inclusive rendering * @param result the list where to fill the unrendered xmlns definitions. - **/ - public void getUnrenderedNodes(Collection result) { - //List result=new ArrayList(); - Iterator it=symb.entrySet().iterator(); - while (it.hasNext()) { - NameSpaceSymbEntry n= it.next(); - //put them rendered? - if ((!n.rendered) && (n.n!=null)) { - n=(NameSpaceSymbEntry) n.clone(); + **/ + public void getUnrenderedNodes(Collection result) { + Iterator it = symb.entrySet().iterator(); + while (it.hasNext()) { + NameSpaceSymbEntry n = it.next(); + //put them rendered? + if ((!n.rendered) && (n.n != null)) { + n = (NameSpaceSymbEntry) n.clone(); needsClone(); - symb.put(n.prefix,n); - n.lastrendered=n.uri; - n.rendered=true; + symb.put(n.prefix, n); + n.lastrendered = n.uri; + n.rendered = true; - result.add(n.n); - - } - } + result.add(n.n); + } } + } - /** + /** * Push a frame for visible namespace. * For Inclusive rendering. **/ - public void outputNodePush() { - nameSpaces++; - push(); - } + public void outputNodePush() { + push(); + } - /** + /** * Pop a frame for visible namespace. **/ - public void outputNodePop() { - nameSpaces--; - pop(); - } + public void outputNodePop() { + pop(); + } - /** + /** * Push a frame for a node. * Inclusive or Exclusive. **/ - public void push() { - //Put the number of namespace definitions in the stack. + public void push() { + //Put the number of namespace definitions in the stack. level.add(null); - cloned=false; - } + cloned = false; + } - /** + /** * Pop a frame. * Inclusive or Exclusive. **/ - public void pop() { - int size=level.size()-1; - Object ob= level.remove(size); - if (ob!=null) { - symb=(SymbMap)ob; - if (size==0) { - cloned=false; - } else - cloned=(level.get(size-1)!=symb); + public void pop() { + int size = level.size() - 1; + Object ob = level.remove(size); + if (ob != null) { + symb = (SymbMap)ob; + if (size == 0) { + cloned = false; + } else { + cloned = (level.get(size - 1) != symb); + } } else { - cloned=false; + cloned = false; } + } - - } - - final void needsClone() { - if (!cloned) { - level.set(level.size()-1,symb); - symb=(SymbMap) symb.clone(); - cloned=true; + final void needsClone() { + if (!cloned) { + level.set(level.size() - 1, symb); + symb = (SymbMap) symb.clone(); + cloned = true; } } - /** - * Gets the attribute node that defines the binding for the prefix. + /** + * Gets the attribute node that defines the binding for the prefix. * @param prefix the prefix to obtain the attribute. * @return null if there is no need to render the prefix. Otherwise the node of * definition. **/ - public Attr getMapping(String prefix) { - NameSpaceSymbEntry entry=symb.get(prefix); - if (entry==null) { - //There is no definition for the prefix(a bug?). - return null; - } - if (entry.rendered) { - //No need to render an entry already rendered. - return null; - } - // Mark this entry as render. - entry=(NameSpaceSymbEntry) entry.clone(); - needsClone(); - symb.put(prefix,entry); - entry.rendered=true; - entry.level=nameSpaces; - entry.lastrendered=entry.uri; - // Return the node for outputing. - return entry.n; + public Attr getMapping(String prefix) { + NameSpaceSymbEntry entry = symb.get(prefix); + if (entry == null) { + //There is no definition for the prefix(a bug?). + return null; } + if (entry.rendered) { + //No need to render an entry already rendered. + return null; + } + // Mark this entry as render. + entry = (NameSpaceSymbEntry) entry.clone(); + needsClone(); + symb.put(prefix, entry); + entry.rendered = true; + entry.lastrendered = entry.uri; + // Return the node for outputing. + return entry.n; + } - /** + /** * Gets a definition without mark it as render. * For render in exclusive c14n the namespaces in the include prefixes. * @param prefix The prefix whose definition is neaded. * @return the attr to render, null if there is no need to render **/ - public Attr getMappingWithoutRendered(String prefix) { - NameSpaceSymbEntry entry= symb.get(prefix); - if (entry==null) { - return null; - } - if (entry.rendered) { - return null; - } - return entry.n; + public Attr getMappingWithoutRendered(String prefix) { + NameSpaceSymbEntry entry = symb.get(prefix); + if (entry == null) { + return null; } + if (entry.rendered) { + return null; + } + return entry.n; + } - /** + /** * Adds the mapping for a prefix. * @param prefix the prefix of definition * @param uri the Uri of the definition * @param n the attribute that have the definition * @return true if there is already defined. **/ - public boolean addMapping(String prefix, String uri,Attr n) { - NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob!=null) && uri.equals(ob.uri)) { - //If we have it previously defined. Don't keep working. - return false; - } - //Creates and entry in the table for this new definition. - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,false,prefix); - needsClone(); - symb.put(prefix, ne); - if (ob != null) { - //We have a previous definition store it for the pop. - //Check if a previous definition(not the inmidiatly one) has been rendered. - ne.lastrendered=ob.lastrendered; - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - //Yes it is. Mark as rendered. - ne.rendered=true; - } - } - return true; + public boolean addMapping(String prefix, String uri, Attr n) { + NameSpaceSymbEntry ob = symb.get(prefix); + if ((ob != null) && uri.equals(ob.uri)) { + //If we have it previously defined. Don't keep working. + return false; } + //Creates and entry in the table for this new definition. + NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix); + needsClone(); + symb.put(prefix, ne); + if (ob != null) { + //We have a previous definition store it for the pop. + //Check if a previous definition(not the inmidiatly one) has been rendered. + ne.lastrendered = ob.lastrendered; + if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { + //Yes it is. Mark as rendered. + ne.rendered = true; + } + } + return true; + } /** * Adds a definition and mark it as render. @@ -223,79 +219,91 @@ public class NameSpaceSymbTable { * @param n the attribute that have the definition * @return the attr to render, null if there is no need to render **/ - public Node addMappingAndRender(String prefix, String uri,Attr n) { + public Node addMappingAndRender(String prefix, String uri, Attr n) { NameSpaceSymbEntry ob = symb.get(prefix); - if ((ob!=null) && uri.equals(ob.uri)) { + if ((ob != null) && uri.equals(ob.uri)) { if (!ob.rendered) { - ob=(NameSpaceSymbEntry) ob.clone(); + ob = (NameSpaceSymbEntry) ob.clone(); needsClone(); - symb.put(prefix,ob); - ob.lastrendered=uri; - ob.rendered=true; + symb.put(prefix, ob); + ob.lastrendered = uri; + ob.rendered = true; return ob.n; } return null; } - NameSpaceSymbEntry ne=new NameSpaceSymbEntry(uri,n,true,prefix); - ne.lastrendered=uri; + NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri,n,true,prefix); + ne.lastrendered = uri; needsClone(); symb.put(prefix, ne); - if (ob != null) { - - if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) { - ne.rendered=true; - return null; - } + if ((ob != null) && (ob.lastrendered != null) && (ob.lastrendered.equals(uri))) { + ne.rendered = true; + return null; } return ne.n; } - public int getLevel() { - // TODO Auto-generated method stub - return level.size(); - } + public int getLevel() { + return level.size(); + } - public void removeMapping(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public void removeMapping(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null) { + if (ob != null) { needsClone(); - symb.put(prefix,null); - } + symb.put(prefix, null); } + } - public void removeMappingIfNotRender(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public void removeMappingIfNotRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null && !ob.rendered) { + if (ob != null && !ob.rendered) { needsClone(); - symb.put(prefix,null); - } + symb.put(prefix, null); } + } - public boolean removeMappingIfRender(String prefix) { - NameSpaceSymbEntry ob = symb.get(prefix); + public boolean removeMappingIfRender(String prefix) { + NameSpaceSymbEntry ob = symb.get(prefix); - if (ob!=null && ob.rendered) { + if (ob != null && ob.rendered) { needsClone(); - symb.put(prefix,null); + symb.put(prefix, null); } return false; - } + } } /** * The internal structure of NameSpaceSymbTable. **/ class NameSpaceSymbEntry implements Cloneable { - NameSpaceSymbEntry(String name,Attr n,boolean rendered,String prefix) { - this.uri=name; - this.rendered=rendered; - this.n=n; - this.prefix=prefix; + + String prefix; + + /**The URI that the prefix defines */ + String uri; + + /**The last output in the URI for this prefix (This for speed reason).*/ + String lastrendered = null; + + /**This prefix-URI has been already render or not.*/ + boolean rendered = false; + + /**The attribute to include.*/ + Attr n; + + NameSpaceSymbEntry(String name, Attr n, boolean rendered, String prefix) { + this.uri = name; + this.rendered = rendered; + this.n = n; + this.prefix = prefix; } + /** @inheritDoc */ public Object clone() { try { @@ -304,46 +312,35 @@ class NameSpaceSymbEntry implements Cloneable { return null; } } - /** The level where the definition was rendered(Only for inclusive) */ - int level=0; - String prefix; - /**The URI that the prefix defines */ - String uri; - /**The last output in the URI for this prefix (This for speed reason).*/ - String lastrendered=null; - /**This prefix-URI has been already render or not.*/ - boolean rendered=false; - /**The attribute to include.*/ - Attr n; }; class SymbMap implements Cloneable { - int free=23; + int free = 23; NameSpaceSymbEntry[] entries; String[] keys; - SymbMap() { - entries=new NameSpaceSymbEntry[free]; - keys=new String[free]; - } + + SymbMap() { + entries = new NameSpaceSymbEntry[free]; + keys = new String[free]; + } + void put(String key, NameSpaceSymbEntry value) { int index = index(key); Object oldKey = keys[index]; keys[index] = key; entries[index] = value; - if (oldKey==null || !oldKey.equals(key)) { - if (--free == 0) { - free=entries.length; - int newCapacity = free<<2; - rehash(newCapacity); - } + if ((oldKey == null || !oldKey.equals(key)) && (--free == 0)) { + free = entries.length; + int newCapacity = free << 2; + rehash(newCapacity); } } List entrySet() { - List a=new ArrayList(); - for (int i=0;i a = new ArrayList(); + for (int i = 0;i < entries.length;i++) { + if ((entries[i] != null) && !("".equals(entries[i].uri))) { + a.add(entries[i]); } } return a; @@ -353,16 +350,16 @@ class SymbMap implements Cloneable { Object[] set = keys; int length = set.length; //abs of index - int index = (obj.hashCode() & 0x7fffffff) % length; + int index = (obj.hashCode() & 0x7fffffff) % length; Object cur = set[index]; - if (cur == null || (cur.equals( obj))) { - return index; + if (cur == null || (cur.equals(obj))) { + return index; } - length=length-1; + length--; do { - index=index==length? 0:++index; - cur = set[index]; + index = index == length ? 0 : ++index; + cur = set[index]; } while (cur != null && (!cur.equals(obj))); return index; } @@ -381,7 +378,7 @@ class SymbMap implements Cloneable { entries = new NameSpaceSymbEntry[newCapacity]; for (int i = oldCapacity; i-- > 0;) { - if(oldKeys[i] != null) { + if (oldKeys[i] != null) { String o = oldKeys[i]; int index = index(o); keys[index] = o; @@ -391,20 +388,19 @@ class SymbMap implements Cloneable { } NameSpaceSymbEntry get(String key) { - return entries[index(key)]; + return entries[index(key)]; } protected Object clone() { try { - SymbMap copy=(SymbMap) super.clone(); - copy.entries=new NameSpaceSymbEntry[entries.length]; - System.arraycopy(entries,0,copy.entries,0,entries.length); - copy.keys=new String[keys.length]; - System.arraycopy(keys,0,copy.keys,0,keys.length); + SymbMap copy = (SymbMap) super.clone(); + copy.entries = new NameSpaceSymbEntry[entries.length]; + System.arraycopy(entries, 0, copy.entries, 0, entries.length); + copy.keys = new String[keys.length]; + System.arraycopy(keys, 0, copy.keys, 0, keys.length); - return copy; + return copy; } catch (CloneNotSupportedException e) { - // TODO Auto-generated catch block e.printStackTrace(); } return null; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java index b62dd3b0869..0ba49747f31 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java @@ -1,3 +1,25 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.c14n.implementations; import java.io.IOException; @@ -6,150 +28,153 @@ import java.util.Map; public class UtfHelpper { - final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException { - byte []result= cache.get(str); - if (result==null) { - result=getStringInUtf8(str); - cache.put(str,result); - } + static final void writeByte( + final String str, + final OutputStream out, + Map cache + ) throws IOException { + byte[] result = cache.get(str); + if (result == null) { + result = getStringInUtf8(str); + cache.put(str, result); + } - out.write(result); + out.write(result); + } - } - - final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ - if (c < 0x80) { - out.write(c); - return; + static final void writeCharToUtf8(final char c, final OutputStream out) throws IOException { + if (c < 0x80) { + out.write(c); + return; + } + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { + //No Surrogates in sun java + out.write(0x3f); + return; + } + int bias; + int write; + char ch; + if (c > 0x07FF) { + ch = (char)(c>>>12); + write = 0xE0; + if (ch > 0) { + write |= (ch & 0x0F); } - if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ + out.write(write); + write = 0x80; + bias = 0x3F; + } else { + write = 0xC0; + bias = 0x1F; + } + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); + } + out.write(write); + out.write(0x80 | ((c) & 0x3F)); + + } + + static final void writeStringToUtf8( + final String str, + final OutputStream out + ) throws IOException{ + final int length = str.length(); + int i = 0; + char c; + while (i < length) { + c = str.charAt(i++); + if (c < 0x80) { + out.write(c); + continue; + } + if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { //No Surrogates in sun java out.write(0x3f); - return; - } + continue; + } + char ch; int bias; int write; - char ch; if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); + ch = (char)(c>>>12); + write = 0xE0; + if (ch > 0) { + write |= (ch & 0x0F); } out.write(write); - write=0x80; - bias=0x3F; + write = 0x80; + bias = 0x3F; } else { - write=0xC0; - bias=0x1F; + write = 0xC0; + bias = 0x1F; } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); } out.write(write); out.write(0x80 | ((c) & 0x3F)); - } + } - final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ - final int length=str.length(); - int i=0; - char c; - while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) { + //No Surrogates in sun java + result[out++] = 0x3f; + continue; + } + if (!expanded) { + byte newResult[] = new byte[3*length]; + System.arraycopy(result, 0, newResult, 0, out); + result = newResult; + expanded = true; + } + char ch; + int bias; + byte write; + if (c > 0x07FF) { + ch = (char)(c>>>12); + write = (byte)0xE0; + if (ch > 0) { + write |= (ch & 0x0F); } - if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ - //No Surrogates in sun java - out.write(0x3f); - continue; - } - char ch; - int bias; - int write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - out.write(write); - write=0x80; - bias=0x3F; - } else { - write=0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - out.write(write); - out.write(0x80 | ((c) & 0x3F)); - - } - - } - public final static byte[] getStringInUtf8(final String str) { - final int length=str.length(); - boolean expanded=false; - byte []result=new byte[length]; - int i=0; - int out=0; - char c; - while (i= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){ - //No Surrogates in sun java - result[out++]=0x3f; - - continue; - } - if (!expanded) { - byte newResult[]=new byte[3*length]; - System.arraycopy(result, 0, newResult, 0, out); - result=newResult; - expanded=true; - } - char ch; - int bias; - byte write; - if (c > 0x07FF) { - ch=(char)(c>>>12); - write=(byte)0xE0; - if (ch>0) { - write |= ( ch & 0x0F); - } - result[out++]=write; - write=(byte)0x80; - bias=0x3F; - } else { - write=(byte)0xC0; - bias=0x1F; - } - ch=(char)(c>>>6); - if (ch>0) { - write|= (ch & bias); - } - result[out++]=write; - result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/ - - } - if (expanded) { - byte newResult[]=new byte[out]; - System.arraycopy(result, 0, newResult, 0, out); - result=newResult; - } - return result; - } - - + result[out++] = write; + write = (byte)0x80; + bias = 0x3F; + } else { + write = (byte)0xC0; + bias = 0x1F; + } + ch = (char)(c>>>6); + if (ch > 0) { + write |= (ch & bias); + } + result[out++] = write; + result[out++] = (byte)(0x80 | ((c) & 0x3F)); + } + if (expanded) { + byte newResult[] = new byte[out]; + System.arraycopy(result, 0, newResult, 0, out); + result = newResult; + } + return result; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java new file mode 100644 index 00000000000..a21f1488ec7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java @@ -0,0 +1,249 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.encryption; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Converts Strings into Nodes and visa versa. + * + * An abstract class for common Serializer functionality + */ +public abstract class AbstractSerializer implements Serializer { + + protected Canonicalizer canon; + + public void setCanonicalizer(Canonicalizer canon) { + this.canon = canon; + } + + /** + * Returns a String representation of the specified + * Element. + *

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

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

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

+ * Refer also to comments about setup of format. + * + * @param content the NodeList to serialize. + * @return the String representation of the serialized + * NodeList. + * @throws Exception + */ + public String serialize(NodeList content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + for (int i = 0; i < content.getLength(); i++) { + canon.canonicalizeSubtree(content.item(i)); + } + String ret = baos.toString("UTF-8"); + baos.reset(); + return ret; + } + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @throws Exception + */ + public byte[] serializeToByteArray(NodeList content) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + for (int i = 0; i < content.getLength(); i++) { + canon.canonicalizeSubtree(content.item(i)); + } + return baos.toByteArray(); + } + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the canonicalization of the node + * @throws Exception + */ + public String canonSerialize(Node node) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + canon.canonicalizeSubtree(node); + String ret = baos.toString("UTF-8"); + baos.reset(); + return ret; + } + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the (byte[]) canonicalization of the node + * @throws Exception + */ + public byte[] canonSerializeToByteArray(Node node) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + canon.setWriter(baos); + canon.notReset(); + canon.canonicalizeSubtree(node); + return baos.toByteArray(); + } + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; + + protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException { + // Create the context to parse the document against + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + try { + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8"); + outputStreamWriter.write(" storedNamespaces = new HashMap(); + Node wk = ctx; + while (wk != null) { + NamedNodeMap atts = wk.getAttributes(); + if (atts != null) { + for (int i = 0; i < atts.getLength(); ++i) { + Node att = atts.item(i); + String nodeName = att.getNodeName(); + if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:")) + && !storedNamespaces.containsKey(att.getNodeName())) { + outputStreamWriter.write(" "); + outputStreamWriter.write(nodeName); + outputStreamWriter.write("=\""); + outputStreamWriter.write(att.getNodeValue()); + outputStreamWriter.write("\""); + storedNamespaces.put(nodeName, att.getNodeValue()); + } + } + } + wk = wk.getParentNode(); + } + outputStreamWriter.write(">"); + outputStreamWriter.flush(); + byteArrayOutputStream.write(source); + + outputStreamWriter.write(""); + outputStreamWriter.close(); + + return byteArrayOutputStream.toByteArray(); + } catch (UnsupportedEncodingException e) { + throw new XMLEncryptionException("empty", e); + } catch (IOException e) { + throw new XMLEncryptionException("empty", e); + } + } + + protected static String createContext(String source, Node ctx) { + // Create the context to parse the document against + StringBuilder sb = new StringBuilder(); + sb.append(" storedNamespaces = new HashMap(); + Node wk = ctx; + while (wk != null) { + NamedNodeMap atts = wk.getAttributes(); + if (atts != null) { + for (int i = 0; i < atts.getLength(); ++i) { + Node att = atts.item(i); + String nodeName = att.getNodeName(); + if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:")) + && !storedNamespaces.containsKey(att.getNodeName())) { + sb.append(" " + nodeName + "=\"" + att.getNodeValue() + "\""); + storedNamespaces.put(nodeName, att.getNodeValue()); + } + } + } + wk = wk.getParentNode(); + } + sb.append(">" + source + ""); + return sb.toString(); + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java index 803fca8c65f..c1da9befd71 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import com.sun.org.apache.xml.internal.security.keys.KeyInfo; import org.w3c.dom.Element; - /** * A Key Agreement algorithm provides for the derivation of a shared secret key * based on a shared secret computed from certain types of compatible public @@ -79,9 +79,10 @@ import org.w3c.dom.Element; * @author Axl Mattheus */ public interface AgreementMethod { + /** - * Returns an byte array. - * @return + * Returns a byte array. + * @return a byte array. */ byte[] getKANonce(); @@ -92,8 +93,8 @@ public interface AgreementMethod { void setKANonce(byte[] kanonce); /** - * Returns aditional information regarding the AgreementMethod. - * @return + * Returns additional information regarding the AgreementMethod. + * @return additional information regarding the AgreementMethod. */ Iterator getAgreementMethodInformation(); @@ -134,7 +135,7 @@ public interface AgreementMethod { void setOriginatorKeyInfo(KeyInfo keyInfo); /** - * Retruns information relating to the recipient's shared secret. + * Returns information relating to the recipient's shared secret. * * @return information relating to the recipient's shared secret. */ diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java index 8a03d389d7b..39654a9ff8d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - /** * CipherData provides encrypted data. It must either contain the * encrypted octet sequence as base64 encoded text of the @@ -42,10 +43,12 @@ package com.sun.org.apache.xml.internal.security.encryption; * @author Axl Mattheus */ public interface CipherData { + /** VALUE_TYPE ASN */ - public static final int VALUE_TYPE = 0x00000001; + int VALUE_TYPE = 0x00000001; + /** REFERENCE_TYPE ASN */ - public static final int REFERENCE_TYPE = 0x00000002; + int REFERENCE_TYPE = 0x00000002; /** * Returns the type of encrypted data contained in the @@ -76,18 +79,17 @@ public interface CipherData { * Returns a reference to an external location containing the encrypted * octet sequence (byte array). * - * @return the reference to an external location containing the enctrypted - * octet sequence. + * @return the reference to an external location containing the encrypted + * octet sequence. */ CipherReference getCipherReference(); /** * Sets the CipherData's reference. * - * @param reference an external location containing the enctrypted octet - * sequence. + * @param reference an external location containing the encrypted octet sequence. * @throws XMLEncryptionException */ - void setCipherReference(CipherReference reference) throws - XMLEncryptionException; + void setCipherReference(CipherReference reference) throws XMLEncryptionException; } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java index 1610741193f..75b0dcb7971 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java @@ -2,34 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; import org.w3c.dom.Attr; - /** * CipherReference identifies a source which, when processed, * yields the encrypted octet sequence. *

* The actual value is obtained as follows. The CipherReference URI * contains an identifier that is dereferenced. Should the - * CipherReference element contain an OPTIONAL sequence of * Transforms, the data resulting from dereferencing the URI is * transformed as specified so as to yield the intended cipher value. For * example, if the value is base64 encoded within an XML document; the @@ -62,20 +62,21 @@ public interface CipherReference { /** * Returns an URI that contains an identifier that should be * dereferenced. - * @return + * @return an URI that contains an identifier that should be + * dereferenced. */ String getURI(); - /** - * Gets the URI as an Attribute node. Used to meld the CipherREference - * with the XMLSignature ResourceResolvers - * @return - */ - public Attr getURIAsAttr(); + /** + * Gets the URI as an Attribute node. Used to meld the CipherReference + * with the XMLSignature ResourceResolvers + * @return the URI as an Attribute node + */ + Attr getURIAsAttr(); /** * Returns the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @return the transform that specifies how to transform the reference to * yield the intended cipher value. @@ -84,10 +85,11 @@ public interface CipherReference { /** * Sets the Transforms that specifies how to transform the - * URI to yield the appropiate cipher value. + * URI to yield the appropriate cipher value. * * @param transforms the set of Transforms that specifies how * to transform the reference to yield the intended cipher value. */ void setTransforms(Transforms transforms); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java index 28486365d72..193aef8a908 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - /** * CipherValue is the wrapper for cipher text. * @@ -28,20 +29,18 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface CipherValue { /** - * Resturns the Base 64 encoded, encrypted octets that is the - * CihperValue. + * Returns the Base 64 encoded, encrypted octets that is the + * CipherValue. * * @return cipher value. */ - String getValue(); - // byte[] getValue(); + String getValue(); /** * Sets the Base 64 encoded, encrypted octets that is the - * CihperValue. + * CipherValue. * * @param value the cipher value. */ - void setValue(String value); - // void setValue(byte[] value); + void setValue(String value); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java new file mode 100644 index 00000000000..f0ffb91f1c2 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java @@ -0,0 +1,114 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.encryption; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Converts Strings into Nodes and visa versa. + */ +public class DocumentSerializer extends AbstractSerializer { + + protected DocumentBuilderFactory dbf; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException { + byte[] fragment = createContext(source, ctx); + return deserialize(ctx, new InputSource(new ByteArrayInputStream(fragment))); + } + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + public Node deserialize(String source, Node ctx) throws XMLEncryptionException { + String fragment = createContext(source, ctx); + return deserialize(ctx, new InputSource(new StringReader(fragment))); + } + + /** + * @param ctx + * @param inputSource + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException { + try { + if (dbf == null) { + dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); + dbf.setValidating(false); + } + DocumentBuilder db = dbf.newDocumentBuilder(); + Document d = db.parse(inputSource); + + Document contextDocument = null; + if (Node.DOCUMENT_NODE == ctx.getNodeType()) { + contextDocument = (Document)ctx; + } else { + contextDocument = ctx.getOwnerDocument(); + } + + Element fragElt = + (Element) contextDocument.importNode(d.getDocumentElement(), true); + DocumentFragment result = contextDocument.createDocumentFragment(); + Node child = fragElt.getFirstChild(); + while (child != null) { + fragElt.removeChild(child); + result.appendChild(child); + child = fragElt.getFirstChild(); + } + return result; + } catch (SAXException se) { + throw new XMLEncryptionException("empty", se); + } catch (ParserConfigurationException pce) { + throw new XMLEncryptionException("empty", pce); + } catch (IOException ioe) { + throw new XMLEncryptionException("empty", ioe); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java index 79038a67cb5..c09eeceaa59 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - /** * The EncryptedData element is the core element in the syntax. Not * only does its CipherData child contain the encrypted data, but @@ -42,3 +43,4 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface EncryptedData extends EncryptedType { } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java index 9607917108b..05fafaf873b 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - - /** * The EncryptedKey element is used to transport encryption keys * from the originator to a known recipient(s). It may be used as a stand-alone @@ -51,9 +51,9 @@ package com.sun.org.apache.xml.internal.security.encryption; * @author Axl Mattheus */ public interface EncryptedKey extends EncryptedType { + /** - * Returns a hint as to which recipient this encrypted key value is intended - * for. + * Returns a hint as to which recipient this encrypted key value is intended for. * * @return the recipient of the EncryptedKey. */ @@ -110,3 +110,4 @@ public interface EncryptedKey extends EncryptedType { */ void setCarriedName(String name); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java index 17ffded82a5..61e7e51df9d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import com.sun.org.apache.xml.internal.security.keys.KeyInfo; - /** * EncryptedType is the abstract type from which EncryptedData and * EncryptedKey are derived. While these two latter element types @@ -50,6 +50,7 @@ import com.sun.org.apache.xml.internal.security.keys.KeyInfo; * @author Axl Mattheus */ public interface EncryptedType { + /** * Returns a String providing for the standard method of * assigning an id to the element within the document context. @@ -61,7 +62,7 @@ public interface EncryptedType { /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -117,7 +118,7 @@ public interface EncryptedType { void setMimeType(String type); /** - * Retusn an URI representing the encoding of the + * Return an URI representing the encoding of the * EncryptedType. * * @return the encoding of this EncryptedType. @@ -128,7 +129,7 @@ public interface EncryptedType { * Sets the URI representing the encoding of the * EncryptedType. * - * @param encoding. + * @param encoding */ void setEncoding(String encoding); @@ -189,7 +190,8 @@ public interface EncryptedType { * Sets the EncryptionProperties that supplies additional * information about the generation of the EncryptedType. * - * @param properties. + * @param properties */ void setEncryptionProperties(EncryptionProperties properties); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java index 2664db9ae94..05c3cdc76cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import org.w3c.dom.Element; - /** * EncryptionMethod describes the encryption algorithm applied to * the cipher data. If the element is absent, the encryption algorithm must be @@ -82,6 +82,30 @@ public interface EncryptionMethod { */ void setOAEPparams(byte[] parameters); + /** + * Set the Digest Algorithm to use + * @param digestAlgorithm the Digest Algorithm to use + */ + void setDigestAlgorithm(String digestAlgorithm); + + /** + * Get the Digest Algorithm to use + * @return the Digest Algorithm to use + */ + String getDigestAlgorithm(); + + /** + * Set the MGF Algorithm to use + * @param mgfAlgorithm the MGF Algorithm to use + */ + void setMGFAlgorithm(String mgfAlgorithm); + + /** + * Get the MGF Algorithm to use + * @return the MGF Algorithm to use + */ + String getMGFAlgorithm(); + /** * Returns an iterator over all the additional elements contained in the * EncryptionMethod. @@ -106,3 +130,4 @@ public interface EncryptionMethod { */ void removeEncryptionMethodInformation(Element information); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java index da1eb65d255..736d63f151a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; - /** * EncryptionProperties can hold additional information concerning * the generation of the EncryptedData or @@ -46,6 +46,7 @@ import java.util.Iterator; * @author Axl Mattheus */ public interface EncryptionProperties { + /** * Returns the EncryptionProperties' id. * @@ -72,14 +73,15 @@ public interface EncryptionProperties { /** * Adds an EncryptionProperty. * - * @param property. + * @param property */ void addEncryptionProperty(EncryptionProperty property); /** * Removes the specified EncryptionProperty. * - * @param property. + * @param property */ void removeEncryptionProperty(EncryptionProperty property); } + diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java index 4cd6c4696cd..fc969018033 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java @@ -2,25 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import org.w3c.dom.Element; @@ -50,6 +51,7 @@ import org.w3c.dom.Element; * @author Axl Mattheus */ public interface EncryptionProperty { + /** * Returns the EncryptedType being described. * @@ -61,7 +63,7 @@ public interface EncryptionProperty { /** * Sets the target. * - * @param target. + * @param target */ void setTarget(String target); @@ -75,7 +77,7 @@ public interface EncryptionProperty { /** * Sets the id. * - * @param id. + * @param id */ void setId(String id); @@ -98,7 +100,7 @@ public interface EncryptionProperty { /** * Returns the properties of the EncryptionProperty. * - * @return an Iterator over all the addiitonal encryption + * @return an Iterator over all the additional encryption * information contained in this class. */ Iterator getEncryptionInformation(); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java index 4523a895aaf..dc528ce1a06 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java @@ -2,29 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; import org.w3c.dom.Element; - /** * A wrapper for a pointer from a key value of an EncryptedKey to * items encrypted by that key value (EncryptedData or @@ -44,6 +44,13 @@ import org.w3c.dom.Element; * @see ReferenceList */ public interface Reference { + /** + * Returns the Element tag name for this Reference. + * + * @return the tag name of this Reference. + */ + String getType(); + /** * Returns a URI that points to an Element that * were encrypted using the key defined in the enclosing @@ -79,14 +86,14 @@ public interface Reference { /** * Adds retrieval information. * - * @param info. + * @param info */ void addElementRetrievalInformation(Element info); /** * Removes the specified retrieval information. * - * @param info. + * @param info */ void removeElementRetrievalInformation(Element info); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java index 2cf0ec5ed44..73d46a2f0b9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java @@ -2,28 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - import java.util.Iterator; - /** * ReferenceList is an element that contains pointers from a key * value of an EncryptedKey to items encrypted by that key value @@ -45,10 +45,12 @@ import java.util.Iterator; * @see Reference */ public interface ReferenceList { - /** DATA TAG */ - public static final int DATA_REFERENCE = 0x00000001; + + /** DATA TAG */ + int DATA_REFERENCE = 0x00000001; + /** KEY TAG */ - public static final int KEY_REFERENCE = 0x00000002; + int KEY_REFERENCE = 0x00000002; /** * Adds a reference to this reference list. @@ -57,21 +59,21 @@ public interface ReferenceList { * @throws IllegalAccessException if the Reference is not an * instance of DataReference or KeyReference. */ - public void add(Reference reference); + void add(Reference reference); /** * Removes a reference from the ReferenceList. * * @param reference the reference to remove. */ - public void remove(Reference reference); + void remove(Reference reference); /** * Returns the size of the ReferenceList. * * @return the size of the ReferenceList. */ - public int size(); + int size(); /** * Indicates if the ReferenceList is empty. @@ -79,29 +81,29 @@ public interface ReferenceList { * @return true if the ReferenceList is * empty, else false. */ - public boolean isEmpty(); + boolean isEmpty(); /** * Returns an Iterator over all the References - * contatined in this ReferenceList. + * contained in this ReferenceList. * * @return Iterator. */ - public Iterator getReferences(); + Iterator getReferences(); /** * DataReference factory method. Returns a * DataReference. * @param uri - * @return + * @return a DataReference. */ - public Reference newDataReference(String uri); + Reference newDataReference(String uri); /** * KeyReference factory method. Returns a * KeyReference. * @param uri - * @return + * @return a KeyReference. */ - public Reference newKeyReference(String uri); + Reference newKeyReference(String uri); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java new file mode 100644 index 00000000000..8f3cd8fac9a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java @@ -0,0 +1,77 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.encryption; + +import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Converts Strings into Nodes and visa versa. + */ +public interface Serializer { + + /** + * Set the Canonicalizer object to use. + */ + void setCanonicalizer(Canonicalizer canon); + + /** + * Returns a byte[] representation of the specified + * Element. + * + * @param element the Element to serialize. + * @return the byte[] representation of the serilaized + * Element. + * @throws Exception + */ + byte[] serializeToByteArray(Element element) throws Exception; + + /** + * Returns a byte[] representation of the specified + * NodeList. + * + * @param content the NodeList to serialize. + * @return the byte[] representation of the serialized + * NodeList. + * @throws Exception + */ + byte[] serializeToByteArray(NodeList content) throws Exception; + + /** + * Use the Canonicalizer to serialize the node + * @param node + * @return the (byte[]) canonicalization of the node + * @throws Exception + */ + byte[] canonSerializeToByteArray(Node node) throws Exception; + + /** + * @param source + * @param ctx + * @return the Node resulting from the parse of the source + * @throws XMLEncryptionException + */ + Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java index b2434c025a5..02d083b65ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java @@ -2,27 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; - - - /** * A container for ds:Transforms. *

@@ -40,36 +39,12 @@ package com.sun.org.apache.xml.internal.security.encryption; */ public interface Transforms { /** - * Returns an Iterator over all the transforms contained in - * this transform list. - * - * @return all transforms. + * Temporary method to turn the XMLEncryption Transforms class + * into a DS class. The main logic is currently implemented in the + * DS class, so we need to get to get the base class. + *

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

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

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

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

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

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

- * - * @param transformation the name of the transformation, e.g., - * XMLCipher.TRIPLEDES which is - * shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @param provider the JCE provider that supplies the transformation - * @param canon the name of the c14n algorithm, if - * null use standard serializer - * @return - * @throws XMLEncryptionException - */ - public static XMLCipher getProviderInstance( - String transformation, - String provider, - String canon) - throws XMLEncryptionException { - - XMLCipher instance = XMLCipher.getProviderInstance(transformation, provider); - if (canon != null) { - try { - instance._canon = Canonicalizer.getInstance(canon); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - } - return instance; - } - - /** - * Returns an XMLCipher that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - * EncryptionMethod element. - * - * @return The XMLCipher + * + * @param transformation the name of the transformation + * @param provider the JCE provider that supplies the transformation + * @param canon the name of the c14n algorithm, if null use standard + * serializer + * @return the XMLCipher * @throws XMLEncryptionException */ + public static XMLCipher getProviderInstance( + String transformation, String provider, String canon + ) throws XMLEncryptionException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm"); + } + if (null == provider) { + throw new NullPointerException("Provider unexpectedly null.."); + } + validateTransformation(transformation); + return new XMLCipher(transformation, provider, canon, null); + } - public static XMLCipher getInstance() - throws XMLEncryptionException { - // sanity checks - logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation..."); - - XMLCipher instance = new XMLCipher(); - - instance._algorithm = null; - instance._requestedJCEProvider = null; - instance._key = null; - instance._kek = null; - instance._contextCipher = null; - - /* Create a canonicaliser - used when serialising DOM to octets - * prior to encryption (and for the reverse) */ - - try { - instance._canon = Canonicalizer.getInstance - (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); - } catch (InvalidCanonicalizerException ice) { - throw new XMLEncryptionException("empty", ice); - } - - return (instance); + /** + * Returns an XMLCipher that implements the specified + * transformation, operates on the specified context document and serializes + * the document with the specified canonicalization algorithm before it + * encrypts the document. + *

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

+ * Returns the EncryptedData being built during an ENCRYPT operation. + * This can then be used by applications to add KeyInfo elements and + * set other parameters. + * + * @return The EncryptedData being built + */ + public EncryptedData getEncryptedData() { + // Sanity checks + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Returning EncryptedData"); } + return ed; + } - /** - * Set a Key Encryption Key. - *

- * The Key Encryption Key (KEK) is used for encrypting/decrypting - * EncryptedKey elements. By setting this separately, the XMLCipher - * class can know whether a key applies to the data part or wrapped key - * part of an encrypted object. - * - * @param kek The key to use for de/encrypting key data - */ - - public void setKEK(Key kek) { - - _kek = kek; - + /** + * Get the EncryptedData being build + * + * Returns the EncryptedData being built during an ENCRYPT operation. + * This can then be used by applications to add KeyInfo elements and + * set other parameters. + * + * @return The EncryptedData being built + */ + public EncryptedKey getEncryptedKey() { + // Sanity checks + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); } + return ek; + } - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate EncryptedData - *

- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedData EncryptedData object to martial - * @return the DOM Element representing the passed in - * object + /** + * Set a Key Encryption Key. + *

+ * The Key Encryption Key (KEK) is used for encrypting/decrypting + * EncryptedKey elements. By setting this separately, the XMLCipher + * class can know whether a key applies to the data part or wrapped key + * part of an encrypted object. + * + * @param kek The key to use for de/encrypting key data */ - public Element martial(EncryptedData encryptedData) { + public void setKEK(Key kek) { + this.kek = kek; + } - return (_factory.toElement (encryptedData)); + /** + * Martial an EncryptedData + * + * Takes an EncryptedData object and returns a DOM Element that + * represents the appropriate EncryptedData + *

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

- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedKey EncryptedKey object to martial - * @return the DOM Element representing the passed in - * object */ + /** + * Martial an EncryptedKey + * + * Takes an EncryptedKey object and returns a DOM Element that + * represents the appropriate EncryptedKey + * + *

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

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

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

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

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

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

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

- * NOTE: For internal use only. + * Create an AgreementMethod object * - * @author Axl Mattheus + * @param algorithm Algorithm of the agreement method + * @return a new AgreementMethod */ - - private class Serializer { - /** - * Initialize the XMLSerializer with the specified context - * Document. - *

- * Setup OutputFormat in a way that the serialization does not - * modifiy the contents, that is it shall not do any pretty printing - * and so on. This would destroy the original content before - * encryption. If that content was signed before encryption and the - * serialization modifies the content the signature verification will - * fail. - */ - Serializer() { - } - - /** - * Returns a String representation of the specified - * Document. - *

- * Refer also to comments about setup of format. - * - * @param document the Document to serialize. - * @return the String representation of the serilaized - * Document. - * @throws Exception - */ - String serialize(Document document) throws Exception { - return canonSerialize(document); - } - - /** - * Returns a String representation of the specified - * Element. - *

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

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

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

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

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

  *  <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
  *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
  * 
- * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public abstract class KeyResolverSpi { - /** - * This method helps the {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} to decide whether a - * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi} is able to perform the requested action. - * - * @param element - * @param BaseURI - * @param storage - * @return - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - throw new UnsupportedOperationException(); - } - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ - public PublicKey engineResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - throw new UnsupportedOperationException(); + /** Field properties */ + protected java.util.Map properties = null; + + protected boolean globalResolver = false; + + protected boolean secureValidation; + + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param baseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + throw new UnsupportedOperationException(); + } + + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ + public PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + throw new UnsupportedOperationException(); }; - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolvePublicKey(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolvePublicKey(element, baseURI, storage); } private KeyResolverSpi cloneIfNeeded() throws KeyResolverException { - KeyResolverSpi tmp=this; + KeyResolverSpi tmp = this; if (globalResolver) { - try { - tmp = (KeyResolverSpi) getClass().newInstance(); - } catch (InstantiationException e) { - throw new KeyResolverException("",e); - } catch (IllegalAccessException e) { - throw new KeyResolverException("",e); - } + try { + tmp = getClass().newInstance(); + } catch (InstantiationException e) { + throw new KeyResolverException("", e); + } catch (IllegalAccessException e) { + throw new KeyResolverException("", e); + } } return tmp; } @@ -110,116 +124,138 @@ public abstract class KeyResolverSpi { * Method engineResolveCertificate * * @param element - * @param BaseURI + * @param baseURI * @param storage * @return resolved X509Certificate key from the registered from the elements * * @throws KeyResolverException */ public X509Certificate engineResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException{ - throw new UnsupportedOperationException(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveCertificate - * - * @param element - * @param BaseURI - * @param storage - * @return resolved X509Certificate key from the registered from the elements - * - * @throws KeyResolverException - */ + /** + * Method engineLookupResolveX509Certificate + * + * @param element + * @param baseURI + * @param storage + * @return resolved X509Certificate key from the registered from the elements + * + * @throws KeyResolverException + */ public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveX509Certificate(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveX509Certificate(element, baseURI, storage); } /** * Method engineResolveSecretKey * * @param element - * @param BaseURI + * @param baseURI * @param storage * @return resolved SecretKey key from the registered from the elements * * @throws KeyResolverException */ public SecretKey engineResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException{ - throw new UnsupportedOperationException(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveSecretKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved SecretKey key from the registered from the elements - * - * @throws KeyResolverException - */ - public SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveSecretKey(element, BaseURI, storage); - } + /** + * Method engineLookupAndResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveSecretKey(element, baseURI, storage); + } - /** Field _properties */ - protected java.util.Map _properties = null; + /** + * Method engineLookupAndResolvePrivateKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + // This method was added later, it has no equivalent + // engineResolvePrivateKey() in the old API. + // We cannot throw UnsupportedOperationException because + // KeyResolverSpi implementations who don't know about + // this method would stop the search too early. + return null; + } - protected boolean globalResolver=false; + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) - _properties=new HashMap(); - this._properties.put(key, value); - } + /** + * Method engineGetProperty + * + * @param key + * @return obtain the property appointed by key + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } - /** - * Method engineGetProperty - * - * @param key - * @return obtain the property appointed by key - */ - public String engineGetProperty(String key) { - if (_properties==null) - return null; + return properties.get(key); + } - return this._properties.get(key); - } + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understood the property + */ + public boolean understandsProperty(String propertyToTest) { + if (properties == null) { + return false; + } - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understood the property - */ - public boolean understandsProperty(String propertyToTest) { - if (_properties==null) - return false; + return properties.get(propertyToTest) != null; + } - return this._properties.get(propertyToTest)!=null; - } - public void setGlobalResolver(boolean globalResolver) { + public void setGlobalResolver(boolean globalResolver) { this.globalResolver = globalResolver; - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java new file mode 100644 index 00000000000..dbd2e084f0c --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java @@ -0,0 +1,83 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys from a + * dsig11:DEREncodedKeyValue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValueResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE); + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI); + return derKeyValue.getPublicKey(); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java index 20bf7bad777..784d5fc874d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java @@ -2,30 +2,29 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; @@ -34,66 +33,70 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class DSAKeyValueResolver extends KeyResolverSpi { - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (element == null) { - return null; - } - Element dsaKeyElement=null; - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - if (isKeyValue) { - dsaKeyElement = - XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_DSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:DSAKeyValue directly (without KeyValue) - dsaKeyElement = element; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName()); + + + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (element == null) { + return null; + } + Element dsaKeyElement = null; + boolean isKeyValue = + XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + if (isKeyValue) { + dsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:DSAKeyValue directly (without KeyValue) + dsaKeyElement = element; + } + + if (dsaKeyElement == null) { + return null; + } + + try { + DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI); + PublicKey pk = dsaKeyValue.getPublicKey(); + + return pk; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); } + //do nothing + } - if (dsaKeyElement == null) { - return null; - } - - try { - DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, - BaseURI); - PublicKey pk = dsaKeyValue.getPublicKey(); - - return pk; - } catch (XMLSecurityException ex) { - //do nothing - } - - return null; - } + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage){ - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java index 6adc050e893..a1be10b977f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java @@ -2,39 +2,43 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; import java.security.Key; import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; import javax.crypto.SecretKey; import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey; import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; +import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * The EncryptedKeyResolver is not a generic resolver. It can * only be for specific instantiations, as the key being unwrapped will @@ -47,78 +51,100 @@ import org.w3c.dom.Element; * * @author Berin Lautenbach */ - public class EncryptedKeyResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(EncryptedKeyResolver.class.getName()); + private Key kek; + private String algorithm; + private List internalKeyResolvers; - Key _kek; - String _algorithm; - - /** - * Constructor for use when a KEK needs to be derived from a KeyInfo - * list - * @param algorithm - */ - public EncryptedKeyResolver(String algorithm) { - _kek = null; - _algorithm=algorithm; - } - - /** - * Constructor used for when a KEK has been set - * @param algorithm - * @param kek - */ - - public EncryptedKeyResolver(String algorithm, Key kek) { - _algorithm = algorithm; - _kek = kek; + /** + * Constructor for use when a KEK needs to be derived from a KeyInfo + * list + * @param algorithm + */ + public EncryptedKeyResolver(String algorithm) { + kek = null; + this.algorithm = algorithm; + } + /** + * Constructor used for when a KEK has been set + * @param algorithm + * @param kek + */ + public EncryptedKeyResolver(String algorithm, Key kek) { + this.algorithm = algorithm; + this.kek = kek; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to help + * resolve the KEK. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + if (internalKeyResolvers == null) { + internalKeyResolvers = new ArrayList(); } + internalKeyResolvers.add(realKeyResolver); + } /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - SecretKey key=null; - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + if (element == null) { + return null; + } - if (element == null) { - return null; - } + SecretKey key = null; + boolean isEncryptedKey = + XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY); + if (isEncryptedKey) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); + } + try { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, kek); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + cipher.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + EncryptedKey ek = cipher.loadEncryptedKey(element); + key = (SecretKey) cipher.decryptKey(ek, algorithm); + } catch (XMLEncryptionException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + } - boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, - EncryptionConstants._TAG_ENCRYPTEDKEY); - - if (isEncryptedKey) { - log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); - try { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, _kek); - EncryptedKey ek = cipher.loadEncryptedKey(element); - key = (SecretKey) cipher.decryptKey(ek, _algorithm); - } - catch (Exception e) {} - } - - return key; - } + return key; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java new file mode 100644 index 00000000000..0e63715e2df --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java @@ -0,0 +1,290 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.KeyInfo; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** + * KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a + * dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReferenceResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE); + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPublicKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getX509Certificate(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getSecretKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPrivateKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** + * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance. + * + * @param element + * @param baseURI + * @param storage + * @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved + * @throws XMLSecurityException + */ + private KeyInfo resolveReferentKeyInfo(Element element, String baseURI, StorageResolver storage) throws XMLSecurityException { + KeyInfoReference reference = new KeyInfoReference(element, baseURI); + Attr uriAttr = reference.getURIAttr(); + + XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation); + + Element referentElement = null; + try { + referentElement = obtainReferenceElement(resource); + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + return null; + } + + if (referentElement == null) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue()); + return null; + } + + validateReference(referentElement); + + KeyInfo referent = new KeyInfo(referentElement, baseURI); + referent.addStorageResolver(storage); + return referent; + } + + /** + * Validate the Element referred to by the KeyInfoReference. + * + * @param referentElement + * + * @throws XMLSecurityException + */ + private void validateReference(Element referentElement) throws XMLSecurityException { + if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) { + Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) }; + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs); + } + + KeyInfo referent = new KeyInfo(referentElement, ""); + if (referent.containsKeyInfoReference()) { + if (secureValidation) { + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure"); + } else { + // Don't support chains of references at this time. If do support in the future, this is where the code + // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic + // to implement, and/or very expensive given remote URI references. + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure"); + } + } + + } + + /** + * Resolve the XML signature input represented by the specified URI. + * + * @param uri + * @param baseURI + * @param secureValidation + * @return + * @throws XMLSecurityException + */ + private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation) + throws XMLSecurityException { + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + return resource; + } + + /** + * Resolve the Element effectively represented by the XML signature input source. + * + * @param resource + * @return + * @throws CanonicalizationException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws KeyResolverException + */ + private Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet"); + return null; + } else { + // Retrieved resource is a byte stream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + } + return e; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java new file mode 100644 index 00000000000..708cda45049 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java @@ -0,0 +1,353 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Enumeration; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a PrivateKey within a KeyStore based on the KeyInfo hints. + * For X509Data hints, the certificate associated with the private key entry must match. + * For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore. + */ +public class PrivateKeyResolver extends KeyResolverSpi { + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(PrivateKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public PrivateKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + this.password = password; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param BaseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA) + || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + return true; + } + + return false; + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param BaseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + PrivateKey privKey = resolveX509Data(element, baseURI); + if (privKey != null) { + return privKey; + } + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?"); + String keyName = element.getFirstChild().getNodeValue(); + + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + private PrivateKey resolveX509Data(Element element, String baseURI) { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?"); + + try { + X509Data x509Data = new X509Data(element, baseURI); + + int len = x509Data.lengthSKI(); + for (int i = 0; i < len; i++) { + XMLX509SKI x509SKI = x509Data.itemSKI(i); + PrivateKey privKey = resolveX509SKI(x509SKI); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthIssuerSerial(); + for (int i = 0; i < len; i++) { + XMLX509IssuerSerial x509Serial = x509Data.itemIssuerSerial(i); + PrivateKey privKey = resolveX509IssuerSerial(x509Serial); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthSubjectName(); + for (int i = 0; i < len; i++) { + XMLX509SubjectName x509SubjectName = x509Data.itemSubjectName(i); + PrivateKey privKey = resolveX509SubjectName(x509SubjectName); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthCertificate(); + for (int i = 0; i < len; i++) { + XMLX509Certificate x509Cert = x509Data.itemCertificate(i); + PrivateKey privKey = resolveX509Certificate(x509Cert); + if (privKey != null) { + return privKey; + } + } + } catch (XMLSecurityException e) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } catch (KeyStoreException e) { + log.log(java.util.logging.Level.FINE, "KeyStoreException", e); + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Key Identifier + */ + private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert); + + if (certSKI.equals(x509SKI)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair. + */ + private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509IssuerSerial certSerial = + new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert); + + if (certSerial.equals(x509Serial)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Name. + */ + private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SubjectName certSN = + new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert); + + if (certSN.equals(x509SubjectName)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Certificate. + */ + private PrivateKey resolveX509Certificate( + XMLX509Certificate x509Cert + ) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?"); + byte[] x509CertBytes = x509Cert.getCertificateBytes(); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + byte[] certBytes = null; + + try { + certBytes = cert.getEncoded(); + } catch (CertificateEncodingException e1) { + } + + if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } + catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java index fb38e872590..b493f98182d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -34,69 +34,63 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class RSAKeyValueResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); - - /** Field _rsaKeyElement */ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RSAKeyValueResolver.class.getName()); - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); - if (element == null) { - return null; - } + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + if (element == null) { + return null; + } - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - Element rsaKeyElement=null; - if (isKeyValue) { - rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_RSAKEYVALUE, 0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:RSAKeyValue directly (without KeyValue) - rsaKeyElement = element; - } + boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + Element rsaKeyElement = null; + if (isKeyValue) { + rsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:RSAKeyValue directly (without KeyValue) + rsaKeyElement = element; + } + if (rsaKeyElement == null) { + return null; + } - if (rsaKeyElement == null) { - return null; - } + try { + RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI); - try { - RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, - BaseURI); + return rsaKeyValue.getPublicKey(); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } - return rsaKeyValue.getPublicKey(); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } + return null; + } - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java index 4ba848a681d..e5159c084b6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.PublicKey; @@ -35,6 +35,8 @@ import java.util.ListIterator; import java.util.Set; import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -51,11 +53,11 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * The RetrievalMethodResolver can retrieve public keys and certificates from * other locations. The location is specified using the ds:RetrievalMethod @@ -65,252 +67,325 @@ import org.xml.sax.SAXException; * RetrievalMethodResolver cannot handle itself, resolving of the extracted * element is delegated back to the KeyResolver mechanism. * - * @author $Author: mullan $ modified by Dave Garcia + * @author $Author: raul $ modified by Dave Garcia */ public class RetrievalMethodResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RetrievalMethodResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RetrievalMethodResolver.class.getName()); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - { - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return null; - } - - try { - //Create a retrieval method over the given element - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - //a raw certificate, direct parsing is done! - X509Certificate cert=getRawCertificate(resource); - if (cert != null) { - return cert.getPublicKey(); - } - return null; - }; - Element e = obtainRefrenceElement(resource); - return resolveKey(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - static private Element obtainRefrenceElement(XMLSignatureInput resource) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException { - Element e; - if (resource.isElement()){ - e=(Element) resource.getSubNode(); - } else if (resource.isNodeSet()) { - //Retrieved resource is a nodeSet - e=getDocumentElement(resource.getNodeSet()); - } else { - //Retrieved resource is an inputStream - byte inputBytes[] = resource.getBytes(); - e = getDocFromBytes(inputBytes); - //otherwise, we parse the resource, create an Element and delegate - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); - } - return e; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - { - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return null; - } - - try { - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - X509Certificate cert=getRawCertificate(resource); - return cert; - } - Element e = obtainRefrenceElement(resource); - return resolveCertificate(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private X509Certificate resolveCertificate(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getX509Certificate(e,BaseURI, storage); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private PublicKey resolveKey(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getPublicKey(e,BaseURI, storage); - } - return null; - } - - static private X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException{ - byte inputBytes[] = resource.getBytes(); - // if the resource stores a raw certificate, we have to handle it - CertificateFactory certFact =CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert =(X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); - return cert; - } - /** - * Resolves the input from the given retrieval method - * @return - * @throws XMLSecurityException - */ - static private XMLSignatureInput resolveInput(RetrievalMethod rm,String BaseURI) throws XMLSecurityException{ - Attr uri = rm.getURIAttr(); - //Apply the trnasforms - Transforms transforms = rm.getTransforms(); - ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); - if (resRes != null) { - XMLSignatureInput resource = resRes.resolve(uri, BaseURI); - if (transforms != null) { - log.log(java.util.logging.Level.FINE, "We have Transforms"); - resource = transforms.performTransforms(resource); - } - return resource; - } - return null; - } - - /** - * Parses a byte array and returns the parsed Element. - * - * @param bytes - * @return the Document Element after parsing bytes - * @throws KeyResolverException if something goes wrong - */ - static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { - try { - javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); - org.w3c.dom.Document doc = - db.parse(new java.io.ByteArrayInputStream(bytes)); - return doc.getDocumentElement(); - } catch (org.xml.sax.SAXException ex) { - throw new KeyResolverException("empty", ex); - } catch (java.io.IOException ex) { - throw new KeyResolverException("empty", ex); - } catch (javax.xml.parsers.ParserConfigurationException ex) { - throw new KeyResolverException("empty", ex); - } - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } - - static Element getDocumentElement(Set set) { - Iterator it=set.iterator(); - Element e=null; - while (it.hasNext()) { - Node currentNode=it.next(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) { - e=(Element)currentNode; - break; - } - - } - List parents=new ArrayList(10); - - //Obtain all the parents of the elemnt - while (e != null) { - parents.add(e); - Node n=e.getParentNode(); - if (n == null || n.getNodeType() != Node.ELEMENT_NODE) { - break; - } - e=(Element)n; - } - //Visit them in reverse order. - ListIterator it2=parents.listIterator(parents.size()-1); - Element ele=null; - while (it2.hasPrevious()) { - ele=it2.previous(); - if (set.contains(ele)) { - return ele; - } + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) { + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { + return null; } + + try { + // Create a retrieval method over the given element + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + // a raw certificate, direct parsing is done! + X509Certificate cert = getRawCertificate(resource); + if (cert != null) { + return cert.getPublicKey(); + } return null; - } + } + Element e = obtainReferenceElement(resource); + + // Check to make sure that the reference is not to another RetrievalMethod + // which points to this element + if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) { + if (secureValidation) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; + } + } + + return resolveKey(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage) { + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { + return null; + } + + try { + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + return getRawCertificate(resource); + } + + Element e = obtainReferenceElement(resource); + + // Check to make sure that the reference is not to another RetrievalMethod + // which points to this element + if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) { + if (secureValidation) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; + } + } + + return resolveCertificate(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Retrieves a x509Certificate from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static X509Certificate resolveCertificate( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getX509Certificate(e, baseURI, storage); + } + return null; + } + + /** + * Retrieves a PublicKey from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static PublicKey resolveKey( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getPublicKey(e, baseURI, storage); + } + return null; + } + + private static Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + // Retrieved resource is a nodeSet + e = getDocumentElement(resource.getNodeSet()); + } else { + // Retrieved resource is an inputStream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + // otherwise, we parse the resource, create an Element and delegate + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); + } + } + return e; + } + + private static X509Certificate getRawCertificate(XMLSignatureInput resource) + throws CanonicalizationException, IOException, CertificateException { + byte inputBytes[] = resource.getBytes(); + // if the resource stores a raw certificate, we have to handle it + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = (X509Certificate) + certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); + return cert; + } + + /** + * Resolves the input from the given retrieval method + * @return + * @throws XMLSecurityException + */ + private static XMLSignatureInput resolveInput( + RetrievalMethod rm, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + Attr uri = rm.getURIAttr(); + // Apply the transforms + Transforms transforms = rm.getTransforms(); + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + if (transforms != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have Transforms"); + } + resource = transforms.performTransforms(resource); + } + return resource; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } + + private static Element getDocumentElement(Set set) { + Iterator it = set.iterator(); + Element e = null; + while (it.hasNext()) { + Node currentNode = it.next(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + e = (Element) currentNode; + break; + } + } + List parents = new ArrayList(); + + // Obtain all the parents of the elemnt + while (e != null) { + parents.add(e); + Node n = e.getParentNode(); + if (n == null || Node.ELEMENT_NODE != n.getNodeType()) { + break; + } + e = (Element) n; + } + // Visit them in reverse order. + ListIterator it2 = parents.listIterator(parents.size()-1); + Element ele = null; + while (it2.hasPrevious()) { + ele = (Element) it2.previous(); + if (set.contains(ele)) { + return ele; + } + } + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java new file mode 100644 index 00000000000..a5e239f2662 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java @@ -0,0 +1,129 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a SecretKey within a KeyStore based on the KeyName. + * The KeyName is the key entry alias within the KeyStore. + */ +public class SecretKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public SecretKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + this.password = password; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param baseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String keyName = element.getFirstChild().getNodeValue(); + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof SecretKey) { + return (SecretKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java new file mode 100644 index 00000000000..4b23ef1e207 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java @@ -0,0 +1,172 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a single Key based on the KeyName. + */ +public class SingleKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SingleKeyResolver.class.getName()); + + private String keyName; + private PublicKey publicKey; + private PrivateKey privateKey; + private SecretKey secretKey; + + /** + * Constructor. + * @param keyName + * @param publicKey + */ + public SingleKeyResolver(String keyName, PublicKey publicKey) { + this.keyName = keyName; + this.publicKey = publicKey; + } + + /** + * Constructor. + * @param keyName + * @param privateKey + */ + public SingleKeyResolver(String keyName, PrivateKey privateKey) { + this.keyName = keyName; + this.privateKey = privateKey; + } + + /** + * Constructor. + * @param keyName + * @param secretKey + */ + public SingleKeyResolver(String keyName, SecretKey secretKey) { + this.keyName = keyName; + this.secretKey = secretKey; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param BaseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (publicKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return publicKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (secretKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return secretKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (privateKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return privateKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java index 06a49c6708e..06511c37c29 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java @@ -2,30 +2,29 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; @@ -35,96 +34,93 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * Resolves Certificates which are directly contained inside a * ds:X509Certificate Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class X509CertificateResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName()); + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, BaseURI, storage); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + if (cert != null) { + return cert.getPublicKey(); + } - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + return null; + } - if (cert != null) { - return cert.getPublicKey(); - } + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { - return null; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - try { - Element[] els=XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509CERTIFICATE); - if ((els == null) || (els.length == 0)) { - Element el=XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_X509DATA,0); - if (el!=null) { - return engineLookupResolveX509Certificate(el, BaseURI, storage); - } - return null; - } - - // populate Object array - for (int i = 0; i < els.length; i++) { - XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI); - X509Certificate cert = xmlCert.getX509Certificate(); - if (cert!=null) { - return cert; + try { + Element[] els = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE); + if ((els == null) || (els.length == 0)) { + Element el = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0); + if (el != null) { + return engineLookupResolveX509Certificate(el, BaseURI, storage); + } + return null; } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + // populate Object array + for (int i = 0; i < els.length; i++) { + XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI); + X509Certificate cert = xmlCert.getX509Certificate(); + if (cert != null) { + return cert; + } + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java new file mode 100644 index 00000000000..c1b44e68a86 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java @@ -0,0 +1,164 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Iterator; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys and X.509 certificates from a + * dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class X509DigestResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509DigestResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + try { + X509Data x509Data = new X509Data(element, baseURI); + return x509Data.containsDigest(); + } catch (XMLSecurityException e) { + return false; + } + } else { + return false; + } + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + X509Certificate cert = this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + return resolveCertificate(element, baseURI, storage); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** + * Resolves from the storage resolver the actual certificate represented by the digest. + * + * @param element + * @param baseURI + * @param storage + * @return + * @throws XMLSecurityException + */ + private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage) + throws XMLSecurityException { + + XMLX509Digest x509Digests[] = null; + + Element x509childNodes[] = XMLUtils.selectDs11Nodes(element.getFirstChild(), Constants._TAG_X509DIGEST); + + if (x509childNodes == null || x509childNodes.length <= 0) { + return null; + } + + try { + checkStorage(storage); + + x509Digests = new XMLX509Digest[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509Digests[i] = new XMLX509Digest(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate) storageIterator.next(); + + for (int i = 0; i < x509Digests.length; i++) { + XMLX509Digest keyInfoDigest = x509Digests[i]; + byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm()); + + if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found certificate with: " + cert.getSubjectX500Principal().getName()); + } + return cert; + } + + } + } + + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method checkSrorage + * + * @param storage + * @throws KeyResolverException + */ + private void checkStorage(StorageResolver storage) throws KeyResolverException { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509DIGEST }; + KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java index 8f717e71689..1d00692bd03 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java @@ -2,28 +2,30 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; @@ -35,114 +37,114 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509IssuerSerialResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509IssuerSerialResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName()); - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - X509Data x509data = null; - try { - x509data = new X509Data(element, BaseURI); - } catch (XMLSignatureException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (x509data == null) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (!x509data.containsIssuerSerial()) { - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - throw ex; - } - - int noOfISS = x509data.lengthIssuerSerial(); - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + X509Data x509data = null; + try { + x509data = new X509Data(element, baseURI); + } catch (XMLSignatureException ex) { if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " - + certSerial.getIssuerName()); - log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " - + certSerial.getSerialNumber().toString()); + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + if (!x509data.containsIssuerSerial()) { + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; } - for (int i=0; i storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); - if (certSerial.equals(xmliss)) { - log.log(java.util.logging.Level.FINE, "match !!! "); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString()); + } - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < noOfISS; i++) { + XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element Issuer: " + + xmliss.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Element Serial: " + + xmliss.getSerialNumber().toString()); + } + + if (certSerial.equals(xmliss)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java index ac90842059e..8dd381e59ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java @@ -2,28 +2,30 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,124 +37,121 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * - * @author $Author: mullan $ - */ public class X509SKIResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509SKIResolver.class.getName()); - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - } - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA)) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - /** Field _x509childObject[] */ - XMLX509SKI x509childObject[] = null; - - Element x509childNodes[] = null; - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SKI); - - if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SKI }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = new XMLX509SKI[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SKI(x509childNodes[i], BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); - - for (int i = 0; i < x509childObject.length; i++) { - if (certSKI.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "Return PublicKey from " - + cert.getSubjectDN().getName()); - - return cert; - } + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); } - } - } catch (XMLSecurityException ex) { - throw new KeyResolverException("empty", ex); - } + return null; + } + /** Field _x509childObject[] */ + XMLX509SKI x509childObject[] = null; - return null; - } + Element x509childNodes[] = null; + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + if (!((x509childNodes != null) && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SKI }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; + } + + x509childObject = new XMLX509SKI[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); + + for (int i = 0; i < x509childObject.length; i++) { + if (certSKI.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName()); + } + + return cert; + } + } + } + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java index 05e82226c4c..dc2ca4abd5a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java @@ -2,28 +2,30 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,133 +37,140 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509SubjectNameResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509SubjectNameResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName()); - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - Element[] x509childNodes = null; - XMLX509SubjectName x509childObject[] = null; + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + Element[] x509childNodes = null; + XMLX509SubjectName x509childObject[] = null; - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA) ) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SUBJECTNAME); + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + x509childNodes = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME); if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; + && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); + x509childObject = new XMLX509SubjectName[x509childNodes.length]; - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = - new XMLX509SubjectName[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SubjectName(x509childNodes[i], - BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SubjectName certSN = - new XMLX509SubjectName(element.getOwnerDocument(), cert); - - log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); - - for (int i = 0; i < x509childObject.length; i++) { - log.log(java.util.logging.Level.FINE, "Found Element SN: " - + x509childObject[i].getSubjectName()); - - if (certSN.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "match !!! "); - - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI); } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SubjectName certSN = + new XMLX509SubjectName(element.getOwnerDocument(), cert); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + for (int i = 0; i < x509childObject.length; i++) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element SN: " + + x509childObject[i].getSubjectName()); + } + + if (certSN.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } + } + + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java index 7b11e848e8f..88392495d33 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java @@ -2,197 +2,187 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; import java.security.KeyStore; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.SingleCertificateResolver; - /** * This class collects customized resolvers for Certificates. - * - * @author $Author: mullan $ */ public class StorageResolver { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(StorageResolver.class.getName()); - /** Field _storageResolvers */ - List _storageResolvers = null; + /** Field storageResolvers */ + private List storageResolvers = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * Constructor StorageResolver + * + */ + public StorageResolver() {} - /** - * Constructor StorageResolver - * - */ - public StorageResolver() {} + /** + * Constructor StorageResolver + * + * @param resolver + */ + public StorageResolver(StorageResolverSpi resolver) { + this.add(resolver); + } - /** - * Constructor StorageResolver - * - * @param resolver - */ - public StorageResolver(StorageResolverSpi resolver) { - this.add(resolver); - } + /** + * Method addResolver + * + * @param resolver + */ + public void add(StorageResolverSpi resolver) { + if (storageResolvers == null) { + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(resolver); + } - /** - * Method addResolver - * - * @param resolver - */ - public void add(StorageResolverSpi resolver) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._storageResolvers.add(resolver); + /** + * Constructor StorageResolver + * + * @param keyStore + */ + public StorageResolver(KeyStore keyStore) { + this.add(keyStore); + } - this._iterator = null; - } + /** + * Method addKeyStore + * + * @param keyStore + */ + public void add(KeyStore keyStore) { + try { + this.add(new KeyStoreResolver(keyStore)); + } catch (StorageResolverException ex) { + log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); + } + } - /** - * Constructor StorageResolver - * - * @param keyStore - */ - public StorageResolver(KeyStore keyStore) { - this.add(keyStore); - } + /** + * Constructor StorageResolver + * + * @param x509certificate + */ + public StorageResolver(X509Certificate x509certificate) { + this.add(x509certificate); + } - /** - * Method addKeyStore - * - * @param keyStore - */ - public void add(KeyStore keyStore) { + /** + * Method addCertificate + * + * @param x509certificate + */ + public void add(X509Certificate x509certificate) { + this.add(new SingleCertificateResolver(x509certificate)); + } - try { - this.add(new KeyStoreResolver(keyStore)); - } catch (StorageResolverException ex) { - log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); - } - } + /** + * Method getIterator + * @return the iterator for the resolvers. + */ + public Iterator getIterator() { + return new StorageResolverIterator(this.storageResolvers.iterator()); + } - /** - * Constructor StorageResolver - * - * @param x509certificate - */ - public StorageResolver(X509Certificate x509certificate) { - this.add(x509certificate); - } + /** + * Class StorageResolverIterator + * This iterates over all the Certificates found in all the resolvers. + */ + static class StorageResolverIterator implements Iterator { - /** - * Method addCertificate - * - * @param x509certificate - */ - public void add(X509Certificate x509certificate) { - this.add(new SingleCertificateResolver(x509certificate)); - } + /** Field resolvers */ + Iterator resolvers = null; - /** - * Method getIterator - * @return the iterator for the resolvers. - * - */ - public Iterator getIterator() { + /** Field currentResolver */ + Iterator currentResolver = null; - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + /** + * Constructor StorageResolverIterator + * + * @param resolvers + */ + public StorageResolverIterator(Iterator resolvers) { + this.resolvers = resolvers; + currentResolver = findNextResolver(); + } - return this._iterator; - } + /** @inheritDoc */ + public boolean hasNext() { + if (currentResolver == null) { + return false; + } - /** - * Method hasNext - * - * @return true if there is more elements. - */ - public boolean hasNext() { + if (currentResolver.hasNext()) { + return true; + } - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + currentResolver = findNextResolver(); + return (currentResolver != null); + } - return this._iterator.hasNext(); - } + /** @inheritDoc */ + public Certificate next() { + if (hasNext()) { + return currentResolver.next(); + } - /** - * Method next - * - * @return the next element - */ - public X509Certificate next() { - return (X509Certificate) this._iterator.next(); - } + throw new NoSuchElementException(); + } - /** - * Class StorageResolverIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class StorageResolverIterator implements Iterator { + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } - /** Field _resolvers */ - Iterator _resolvers = null; + // Find the next storage with at least one element and return its Iterator + private Iterator findNextResolver() { + while (resolvers.hasNext()) { + StorageResolverSpi resolverSpi = resolvers.next(); + Iterator iter = resolverSpi.getIterator(); + if (iter.hasNext()) { + return iter; + } + } - /** - * Constructor FilesystemIterator - * - * @param resolvers - */ - public StorageResolverIterator(Iterator resolvers) { - this._resolvers = resolvers; - } - - /** @inheritDoc */ - public boolean hasNext() { - return _resolvers.hasNext(); - } - - /** @inheritDoc */ - public Object next() { - return _resolvers.next(); - } - - /** - * Method remove - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + return null; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java index 29dff030f78..af8af531aab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java @@ -2,86 +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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * @author $Author: mullan $ - */ public class StorageResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor StorageResolverException - * - */ - public StorageResolverException() { - super(); - } + /** + * Constructor StorageResolverException + * + */ + public StorageResolverException() { + super(); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - */ - public StorageResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor StorageResolverException + * + * @param msgID + */ + public StorageResolverException(String msgID) { + super(msgID); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - */ - public StorageResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + */ + public StorageResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param _originalException - */ - public StorageResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param originalException + */ + public StorageResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public StorageResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public StorageResolverException(String msgID, Object exArgs[], + Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java index 07211253d22..7cc075a36f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java @@ -2,39 +2,35 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; - - +import java.security.cert.Certificate; import java.util.Iterator; - -/** - * - * @author $Author: mullan $ - */ public abstract class StorageResolverSpi { - /** - * Method getIterator - * - * @return the iterator for the storage - */ - public abstract Iterator getIterator(); + /** + * Method getIterator + * + * @return the iterator for the storage + */ + public abstract Iterator getIterator(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java index 3b38e4a2572..6d7057e1e45 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; @@ -24,6 +26,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; @@ -39,188 +42,188 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; /** * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s - * which reside as files in a single directory available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ + * which reside as files in a single directory available to the + * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. */ public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger( - CertsInFilesystemDirectoryResolver.class.getName()); + CertsInFilesystemDirectoryResolver.class.getName() + ); - /** Field _merlinsCertificatesDir */ - String _merlinsCertificatesDir = null; + /** Field merlinsCertificatesDir */ + private String merlinsCertificatesDir = null; - /** Field _certs */ - private List _certs = new ArrayList(); + /** Field certs */ + private List certs = new ArrayList(); - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param directoryName + * @throws StorageResolverException + */ + public CertsInFilesystemDirectoryResolver(String directoryName) + throws StorageResolverException { + this.merlinsCertificatesDir = directoryName; - /** - * - * - * @param directoryName - * @throws StorageResolverException - */ - public CertsInFilesystemDirectoryResolver(String directoryName) - throws StorageResolverException { + this.readCertsFromHarddrive(); + } - this._merlinsCertificatesDir = directoryName; + /** + * Method readCertsFromHarddrive + * + * @throws StorageResolverException + */ + private void readCertsFromHarddrive() throws StorageResolverException { - this.readCertsFromHarddrive(); + File certDir = new File(this.merlinsCertificatesDir); + List al = new ArrayList(); + String[] names = certDir.list(); - this._iterator = new FilesystemIterator(this._certs); - } + for (int i = 0; i < names.length; i++) { + String currentFileName = names[i]; - /** - * Method readCertsFromHarddrive - * - * @throws StorageResolverException - */ - private void readCertsFromHarddrive() throws StorageResolverException { + if (currentFileName.endsWith(".crt")) { + al.add(names[i]); + } + } - File certDir = new File(this._merlinsCertificatesDir); - ArrayList al = new ArrayList(); - String[] names = certDir.list(); + CertificateFactory cf = null; - for (int i = 0; i < names.length; i++) { - String currentFileName = names[i]; + try { + cf = CertificateFactory.getInstance("X.509"); + } catch (CertificateException ex) { + throw new StorageResolverException("empty", ex); + } - if (currentFileName.endsWith(".crt")) { - al.add(names[i]); - } - } + if (cf == null) { + throw new StorageResolverException("empty"); + } - CertificateFactory cf = null; + for (int i = 0; i < al.size(); i++) { + String filename = certDir.getAbsolutePath() + File.separator + al.get(i); + File file = new File(filename); + boolean added = false; + String dn = null; - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException ex) { - throw new StorageResolverException("empty", ex); - } + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + X509Certificate cert = + (X509Certificate) cf.generateCertificate(fis); - if (cf == null) { - throw new StorageResolverException("empty"); - } + //add to ArrayList + cert.checkValidity(); + this.certs.add(cert); - for (int i = 0; i < al.size(); i++) { - String filename = certDir.getAbsolutePath() + File.separator - + al.get(i); - File file = new File(filename); - boolean added = false; - String dn = null; + dn = cert.getSubjectX500Principal().getName(); + added = true; + } catch (FileNotFoundException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateNotYetValidException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateExpiredException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } finally { + try { + if (fis != null) { + fis.close(); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } + } - try { - FileInputStream fis = new FileInputStream(file); - X509Certificate cert = - (X509Certificate) cf.generateCertificate(fis); - - fis.close(); - - //add to ArrayList - cert.checkValidity(); - this._certs.add(cert); - - dn = cert.getSubjectDN().getName(); - added = true; - } catch (FileNotFoundException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateNotYetValidException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateExpiredException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } - - if (added) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (added && log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); - } - } - } + } + } + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** @inheritDoc */ + public Iterator getIterator() { + return new FilesystemIterator(this.certs); + } - /** - * Class FilesystemIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - private static class FilesystemIterator implements Iterator { + /** + * Class FilesystemIterator + */ + private static class FilesystemIterator implements Iterator { - /** Field _certs */ - List _certs = null; + /** Field certs */ + List certs = null; - /** Field _i */ - int _i; + /** Field i */ + int i; - /** - * Constructor FilesystemIterator - * - * @param certs - */ - public FilesystemIterator(List certs) { - this._certs = certs; - this._i = 0; - } + /** + * Constructor FilesystemIterator + * + * @param certs + */ + public FilesystemIterator(List certs) { + this.certs = certs; + this.i = 0; + } - /** @inheritDoc */ - public boolean hasNext() { - return (this._i < this._certs.size()); - } + /** @inheritDoc */ + public boolean hasNext() { + return (this.i < this.certs.size()); + } - /** @inheritDoc */ - public X509Certificate next() { - return this._certs.get(this._i++); - } + /** @inheritDoc */ + public Certificate next() { + return this.certs.get(this.i++); + } - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Method remove + * + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { + /** + * Method main + * + * @param unused + * @throws Exception + */ + public static void main(String unused[]) throws Exception { - CertsInFilesystemDirectoryResolver krs = - new CertsInFilesystemDirectoryResolver( - "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); + CertsInFilesystemDirectoryResolver krs = + new CertsInFilesystemDirectoryResolver( + "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); + for (Iterator i = krs.getIterator(); i.hasNext(); ) { + X509Certificate cert = (X509Certificate) i.next(); + byte[] ski = + com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert); - System.out.println(); - System.out.println("Base64(SKI())= \"" - + Base64.encode(ski) + "\""); - System.out.println("cert.getSerialNumber()= \"" - + cert.getSerialNumber().toString() + "\""); - System.out.println("cert.getSubjectDN().getName()= \"" - + cert.getSubjectDN().getName() + "\""); - System.out.println("cert.getIssuerDN().getName()= \"" - + cert.getIssuerDN().getName() + "\""); - } - } + System.out.println(); + System.out.println("Base64(SKI())= \"" + + Base64.encode(ski) + "\""); + System.out.println("cert.getSerialNumber()= \"" + + cert.getSerialNumber().toString() + "\""); + System.out.println("cert.getSubjectX500Principal().getName()= \"" + + cert.getSubjectX500Principal().getName() + "\""); + System.out.println("cert.getIssuerX500Principal().getName()= \"" + + cert.getIssuerX500Principal().getName() + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java index 2a5662101b8..1e325d121ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java @@ -2,147 +2,152 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.cert.X509Certificate; +import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * Makes the Certificates from a JAVA {@link KeyStore} object available to the * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class KeyStoreResolver extends StorageResolverSpi { - /** Field _keyStore */ - KeyStore _keyStore = null; + /** Field keyStore */ + private KeyStore keyStore = null; - /** Field _iterator */ - Iterator _iterator = null; - - /** - * Constructor KeyStoreResolver - * - * @param keyStore is the keystore which contains the Certificates - * @throws StorageResolverException - */ - public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { - this._keyStore = keyStore; - this._iterator = new KeyStoreIterator(this._keyStore); - } - - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } - - /** - * Class KeyStoreIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class KeyStoreIterator implements Iterator { - - /** Field _keyStore */ - KeyStore _keyStore = null; - - /** Field _aliases */ - Enumeration _aliases = null; - - /** - * Constructor KeyStoreIterator - * - * @param keyStore - * @throws StorageResolverException - */ - public KeyStoreIterator(KeyStore keyStore) - throws StorageResolverException { - - try { - this._keyStore = keyStore; - this._aliases = this._keyStore.aliases(); - } catch (KeyStoreException ex) { + /** + * Constructor KeyStoreResolver + * + * @param keyStore is the keystore which contains the Certificates + * @throws StorageResolverException + */ + public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { + this.keyStore = keyStore; + // Do a quick check on the keystore + try { + keyStore.aliases(); + } catch (KeyStoreException ex) { throw new StorageResolverException("generic.EmptyMessage", ex); - } - } + } + } - /** @inheritDoc */ - public boolean hasNext() { - return this._aliases.hasMoreElements(); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new KeyStoreIterator(this.keyStore); + } - /** @inheritDoc */ - @SuppressWarnings("unchecked") - public X509Certificate next() { + /** + * Class KeyStoreIterator + */ + static class KeyStoreIterator implements Iterator { - String alias = this._aliases.nextElement(); + /** Field keyStore */ + KeyStore keyStore = null; + + /** Field aliases */ + Enumeration aliases = null; + + /** Field nextCert */ + Certificate nextCert = null; + + /** + * Constructor KeyStoreIterator + * + * @param keyStore + */ + public KeyStoreIterator(KeyStore keyStore) { + try { + this.keyStore = keyStore; + this.aliases = this.keyStore.aliases(); + } catch (KeyStoreException ex) { + // empty Enumeration + this.aliases = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public String nextElement() { + return null; + } + }; + } + } + + /** @inheritDoc */ + public boolean hasNext() { + if (nextCert == null) { + nextCert = findNextCert(); + } + + return (nextCert != null); + } + + /** @inheritDoc */ + public Certificate next() { + if (nextCert == null) { + // maybe caller did not call hasNext() + nextCert = findNextCert(); + + if (nextCert == null) { + throw new NoSuchElementException(); + } + } + + Certificate ret = nextCert; + nextCert = null; + return ret; + } + + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + + // Find the next entry that contains a certificate and return it. + // In particular, this skips over entries containing symmetric keys. + private Certificate findNextCert() { + while (this.aliases.hasMoreElements()) { + String alias = this.aliases.nextElement(); + try { + Certificate cert = this.keyStore.getCertificate(alias); + if (cert != null) { + return cert; + } + } catch (KeyStoreException ex) { + return null; + } + } - try { - return (X509Certificate)this._keyStore.getCertificate(alias); - } catch (KeyStoreException ex) { return null; - } - } + } - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + } - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { - - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - - ks.load( - new java.io.FileInputStream( - "data/com/sun/org/apache/xml/internal/security/samples/input/keystore.jks"), - "xmlsecurity".toCharArray()); - - KeyStoreResolver krs = new KeyStoreResolver(ks); - - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); - - System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski)); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java index 3048bb123ac..e007051fb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java @@ -2,102 +2,93 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * This {@link StorageResolverSpi} makes a single {@link X509Certificate} * available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class SingleCertificateResolver extends StorageResolverSpi { - /** Field _certificate */ - X509Certificate _certificate = null; + /** Field certificate */ + private X509Certificate certificate = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param x509cert the single {@link X509Certificate} + */ + public SingleCertificateResolver(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * - * - * @param x509cert the single {@link X509Certificate} - */ - public SingleCertificateResolver(X509Certificate x509cert) { - this._certificate = x509cert; - this._iterator = new InternalIterator(this._certificate); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new InternalIterator(this.certificate); + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** + * Class InternalIterator + */ + static class InternalIterator implements Iterator { - /** - * Class InternalIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class InternalIterator implements Iterator { + /** Field alreadyReturned */ + boolean alreadyReturned = false; - /** Field _alreadyReturned */ - boolean _alreadyReturned = false; + /** Field certificate */ + X509Certificate certificate = null; - /** Field _certificate */ - X509Certificate _certificate = null; + /** + * Constructor InternalIterator + * + * @param x509cert + */ + public InternalIterator(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * Constructor InternalIterator - * - * @param x509cert - */ - public InternalIterator(X509Certificate x509cert) { - this._certificate = x509cert; - } + /** @inheritDoc */ + public boolean hasNext() { + return !this.alreadyReturned; + } - /** @inheritDoc */ - public boolean hasNext() { - return (!this._alreadyReturned); - } + /** @inheritDoc */ + public Certificate next() { + if (this.alreadyReturned) { + throw new NoSuchElementException(); + } + this.alreadyReturned = true; + return this.certificate; + } - /** @inheritDoc */ - public X509Certificate next() { - - this._alreadyReturned = true; - - return this._certificate; - } - - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml index aea1595741b..55c396c012e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml @@ -52,9 +52,6 @@ - - @@ -78,6 +75,12 @@ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" /> + + + @@ -97,7 +100,7 @@ Description="MD5 message digest from RFC 1321" AlgorithmClass="MessageDigest" RequirementLevel="NOT RECOMMENDED" - SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt" + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" JCEName="MD5"/> + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" + JCEName="SHA1withECDSA"/> + + + + + + @@ -260,7 +284,31 @@ KeyLength="256" RequiredKey="AES" JCEName="AES/CBC/ISO10126Padding"/> + + + + + + + JCEName="RSA/ECB/OAEPPadding"/> + + - - - - + @@ -330,32 +378,8 @@ + DESCRIPTION="A simple resolver for requests of XPointer fragments" /> - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties deleted file mode 100644 index e67ae2c79ef..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# ------------------------------------------------------------------------ -# -# Logging Configuration -# -# ------------------------------------------------------------------------ -# -log4j.rootLogger=DEBUG, LOGTXT - -######################################################################## -# -# Logging based on packages -# -######################################################################## -log4j.logger.com.sun.org.apache.xml.internal.security=DEBUG, LOGTXT -log4j.logger.com.sun.org.apache.xml.internal.security.test.AllTests=DEBUG, LOGTXT - -######################################################################## -# -# Logfile definitions -# -######################################################################## -#Console Log -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.Threshold=DEBUG -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%-5p %C{1}:%L - %m\n -log4j.appender.Console.Target=System.err - -#LOGTXT Log -log4j.appender.LOGTXT=org.apache.log4j.FileAppender -log4j.appender.LOGTXT.File=log.txt -log4j.appender.LOGTXT.Append=true -log4j.appender.LOGTXT.Threshold=DEBUG -log4j.appender.LOGTXT.layout=org.apache.log4j.PatternLayout -log4j.appender.LOGTXT.layout.ConversionPattern=%-5p %C{1}:%L - %m\n - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties index c285aa0f87d..746361d2923 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties @@ -5,6 +5,7 @@ algorithm.extendsWrongClass = Kann URI {0} nicht f algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1} algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm @@ -88,8 +89,13 @@ prefix.AlreadyAssigned = Sie binden den Prefix {0} an den Namespace {1} aber er signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0} signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf. +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler? signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0} @@ -103,6 +109,7 @@ signature.Verification.InvalidDigestOrReference = Ung signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen signature.Verification.MissingID = Cannot resolve element with ID {0} signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1} signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten. signature.Verification.SignatureError = Signatur Fehler diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties index f15104e94b5..a01124ee85f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties @@ -1,126 +1,131 @@ -algorithm.alreadyRegistered = URI {0} already assigned to class {1} -algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH -algorithm.ClassDoesNotExist = Class {0} does not exist -algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} -algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. -algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. -algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. -algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms -algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} -algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm -algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} -algorithms.operationOnlyVerification = A public key can only used for verification of a signature. -algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. -attributeValueIllegal = The attribute {0} has value {1} but must be {2} -c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} -c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} -c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} -c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" -c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} -c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} -c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation -c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) -certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} -certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString -certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier -defaultNamespaceCannotBeSetHere = Default namespace cannot be set here -ElementProxy.nullElement = Cannot create an ElementProxy from a null argument -empty = {0} -encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} -encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams -encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt -encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap -encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit -encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. -encryption.RSAOAEP.dataHashWrong = data hash wrong -encryption.RSAOAEP.dataStartWrong = data wrong start {0} -encryption.RSAOAEP.dataTooShort = data too short -encryption.RSAPKCS15.blockTruncated = block truncated -encryption.RSAPKCS15.noDataInBlock = no data in block -encryption.RSAPKCS15.unknownBlockType = unknown block type -encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers -endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. -errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. -errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. -errorMessages.IOException = Other file I/O and similar exceptions. -errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. -errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. -errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} -errorMessages.NotYetImplementedException = Functionality not yet there. -errorMessages.XMLSignatureException = Verification failed for some other reason. -decoding.divisible.four = It should be divisible by four -decoding.general = Error while decoding -FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. -FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} -FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} -FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} -generic.dontHaveConstructionElement = I do not have a construction Element -generic.EmptyMessage = {0} -generic.NotYetImplemented = {0} Not YET implemented ;-(( -java.security.InvalidKeyException = Invalid key -java.security.NoSuchProviderException = Unknown or unsupported provider -java.security.UnknownKeyType = Unknown or unsupported key type {0} -KeyInfo.needKeyResolver = More than one keyResovler have to be registered -KeyInfo.nokey = Cannot get key from {0} -KeyInfo.noKey = Cannot get the public key -KeyInfo.wrongNumberOfObject = Need {0} keyObjects -KeyInfo.wrongUse = This object was made for getting {0} -keyResolver.alreadyRegistered = {1} class has already been registered for {0} -KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} -KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} -KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} -KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} -KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} -KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} -KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} -KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} -KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} -KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} -KeyStore.alreadyRegistered = {0} Class has already been registered for {1} -KeyStore.register = {1} type class register error in class {0} -KeyStore.registerStore.register = Registeration error for type {0} -KeyValue.IllegalArgument = Cannot create a {0} from {1} -namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} -notYetInitialized = The module {0} is not yet initialized -prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} -signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} -signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature -signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first -signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled -signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled -signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set -signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform -signature.Transform.NotYetImplemented = Transform {0} not yet implemented -signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? -signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} -signature.Transform.node = Current Node: {0} -signature.Transform.nodeAndType = Current Node: {0}, type: {1} -signature.Util.BignumNonPositive = bigInteger.signum() must be positive -signature.Util.NonTextNode = Not a text node -signature.Util.TooManyChilds = Too many childs of Type {0} in {1} -signature.Verification.certificateError = Certificate error -signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References -signature.Verification.internalError = Internal error -signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} -signature.Verification.keyStore = KeyStore error -signature.Verification.MissingID = Cannot resolve element with ID {0} -signature.Verification.MissingResources = Cannot resolve external resource {0} -signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected -signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} -signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput -signature.Verification.SignatureError = Signature error -signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} -signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it -signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference -transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. -transform.init.NotInitialized = -transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization -utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 -Base64Decoding = Error while decoding -utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} -xml.WrongContent = Cannot find {0} in {1} -xml.WrongElement = Cannot create a {0} from a {1} element -xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node -xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} +algorithm.alreadyRegistered = URI {0} already assigned to class {1} +algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH +algorithm.ClassDoesNotExist = Class {0} does not exist +algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} +algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. +algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. +algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} +algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms +algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} +algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm +algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} +algorithms.operationOnlyVerification = A public key can only used for verification of a signature. +algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. +attributeValueIllegal = The attribute {0} has value {1} but must be {2} +c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} +c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} +c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} +c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" +c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} +c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} +c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation +c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) +certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} +certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString +certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier +defaultNamespaceCannotBeSetHere = Default namespace cannot be set here +ElementProxy.nullElement = Cannot create an ElementProxy from a null argument +empty = {0} +encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} +encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams +encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt +encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap +encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit +encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. +encryption.RSAOAEP.dataHashWrong = data hash wrong +encryption.RSAOAEP.dataStartWrong = data wrong start {0} +encryption.RSAOAEP.dataTooShort = data too short +encryption.RSAPKCS15.blockTruncated = block truncated +encryption.RSAPKCS15.noDataInBlock = no data in block +encryption.RSAPKCS15.unknownBlockType = unknown block type +encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers +endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. +errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. +errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. +errorMessages.IOException = Other file I/O and similar exceptions. +errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. +errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. +errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} +errorMessages.NotYetImplementedException = Functionality not yet there. +errorMessages.XMLSignatureException = Verification failed for some other reason. +decoding.divisible.four = It should be divisible by four +decoding.general = Error while decoding +FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. +FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} +FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} +FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} +generic.dontHaveConstructionElement = I do not have a construction Element +generic.EmptyMessage = {0} +generic.NotYetImplemented = {0} Not YET implemented ;-(( +java.security.InvalidKeyException = Invalid key +java.security.NoSuchProviderException = Unknown or unsupported provider +java.security.UnknownKeyType = Unknown or unsupported key type {0} +KeyInfo.needKeyResolver = More than one keyResovler have to be registered +KeyInfo.nokey = Cannot get key from {0} +KeyInfo.noKey = Cannot get the public key +KeyInfo.wrongNumberOfObject = Need {0} keyObjects +KeyInfo.wrongUse = This object was made for getting {0} +keyResolver.alreadyRegistered = {1} class has already been registered for {0} +KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} +KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} +KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} +KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} +KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} +KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} +KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} +KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} +KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} +KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} +KeyStore.alreadyRegistered = {0} Class has already been registered for {1} +KeyStore.register = {1} type class register error in class {0} +KeyStore.registerStore.register = Registeration error for type {0} +KeyValue.IllegalArgument = Cannot create a {0} from {1} +namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} +notYetInitialized = The module {0} is not yet initialized +prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} +signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} +signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature +signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled +signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation +signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled +signature.Transform.NotYetImplemented = Transform {0} not yet implemented +signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? +signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} +signature.Transform.node = Current Node: {0} +signature.Transform.nodeAndType = Current Node: {0}, type: {1} +signature.Util.BignumNonPositive = bigInteger.signum() must be positive +signature.Util.NonTextNode = Not a text node +signature.Util.TooManyChilds = Too many childs of Type {0} in {1} +signature.Verification.certificateError = Certificate error +signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References +signature.Verification.internalError = Internal error +signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} +signature.Verification.keyStore = KeyStore error +signature.Verification.MissingID = Cannot resolve element with ID {0} +signature.Verification.MissingResources = Cannot resolve external resource {0} +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected +signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} +signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput +signature.Verification.SignatureError = Signature error +signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} +signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it +signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference +transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. +transform.init.NotInitialized = +transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization +transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element +utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 +Base64Decoding = Error while decoding +utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} +xml.WrongContent = Cannot find {0} in {1} +xml.WrongElement = Cannot create a {0} from a {1} element +xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node +xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java index 57da56c5cb2..7801315c02d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java @@ -2,85 +2,85 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - /** - * Raised when the computed hash value doesn't match the given DigestValue. Additional human readable info is passed to the constructor -- this being the benefit of raising an exception or returning a value. + * Raised when the computed hash value doesn't match the given DigestValue. + * Additional human readable info is passed to the constructor -- this being the benefit + * of raising an exception or returning a value. * * @author Christian Geuer-Pollmann */ public class InvalidDigestValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidDigestValueException - * - */ - public InvalidDigestValueException() { - super(); - } + /** + * Constructor InvalidDigestValueException + * + */ + public InvalidDigestValueException() { + super(); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - */ - public InvalidDigestValueException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + */ + public InvalidDigestValueException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidDigestValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + */ + public InvalidDigestValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param originalException + */ + public InvalidDigestValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidDigestValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java index 397c1293492..a216ebb4d17 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - /** * Raised if testing the signature value over DigestValue fails because of invalid signature. * @@ -30,58 +30,56 @@ package com.sun.org.apache.xml.internal.security.signature; */ public class InvalidSignatureValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidSignatureValueException - * - */ - public InvalidSignatureValueException() { - super(); - } + /** + * Constructor InvalidSignatureValueException + * + */ + public InvalidSignatureValueException() { + super(); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - */ - public InvalidSignatureValueException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + */ + public InvalidSignatureValueException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + */ + public InvalidSignatureValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java index 351dee5edaf..01d76effdff 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java @@ -2,33 +2,33 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.Map; +import java.util.Set; import javax.xml.parsers.ParserConfigurationException; @@ -38,7 +38,6 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; @@ -50,523 +49,561 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - - /** * Handles <ds:Manifest> elements. *

This element holds the Reference elements

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

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

This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @param followManifests + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences(boolean followManifests) + throws MissingResourceFailureException, XMLSecurityException { + if (referencesEl == null) { + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "verify " + referencesEl.length + " References"); + log.log(java.util.logging.Level.FINE, "I am " + (followManifests + ? "" : "not") + " requested to follow nested Manifests"); + } + if (referencesEl.length == 0) { + throw new XMLSecurityException("empty"); + } + if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT }; - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

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

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

Create a new reference

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

Verify a reference

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

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

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

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

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

    Explanation of the output

    \n" + + "

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

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

    Output

    \n" + "
    \n";
     
    -        /** Field _writer */
    -        private Writer _writer = null;
    +    /** HTML Suffix * */
    +    static final String HTMLSuffix = "
    "; - // J- - // public static final String HTMLPrefix = "
    ";
    -        /** The HTML Prefix* */
    -        static final String HTMLPrefix = "\n"
    -                        + "\n"
    -                        + "\n"
    -                        + "Caninical XML node set\n"
    -                        + " \n"
    -                        + "\n"
    -                        + "\n"
    -                        + "

    Explanation of the output

    \n" - + "

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

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

    Output

    \n" + "
    \n";
    +    static final String HTMLExcludePrefix = "";
     
    -        /** HTML Suffix * */
    -        static final String HTMLSuffix = "
    "; + static final String HTMLIncludePrefix = ""; - static final String HTMLExcludePrefix = ""; + static final String HTMLIncludeOrExcludeSuffix = ""; - static final String HTMLExcludeSuffix = ""; + static final String HTMLIncludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludePrefix = ""; + static final String HTMLExcludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludeSuffix = ""; + private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final String HTMLIncludedInclusiveNamespacePrefix = ""; + private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final String HTMLIncludedInclusiveNamespaceSuffix = ""; + private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - static final String HTMLExcludedInclusiveNamespacePrefix = ""; + static final AttrCompare ATTR_COMPARE = new AttrCompare(); - static final String HTMLExcludedInclusiveNamespaceSuffix = ""; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signature to pretty print + */ + public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) { + if (!xmlSignatureInput.isNodeSet()) { + this.xpathNodeSet = null; + } else { + this.xpathNodeSet = xmlSignatureInput.getInputNodeSet(); + } + } - private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signatur to pretty print + * @param inclusiveNamespace + */ + public XMLSignatureInputDebugger( + XMLSignatureInput xmlSignatureInput, + Set inclusiveNamespace + ) { + this(xmlSignatureInput); + this.inclusiveNamespaces = inclusiveNamespace; + } - private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - - private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - - static final AttrCompare ATTR_COMPARE = new AttrCompare(); - - // J+ - private XMLSignatureInputDebugger() { - // do nothing + /** + * Method getHTMLRepresentation + * + * @return The HTML Representation. + * @throws XMLSignatureException + */ + public String getHTMLRepresentation() throws XMLSignatureException { + if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) { + return HTMLPrefix + "no node set, sorry" + HTMLSuffix; } - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput) { + // get only a single node as anchor to fetch the owner document + Node n = this.xpathNodeSet.iterator().next(); - if (!xmlSignatureInput.isNodeSet()) { - this._xpathNodeSet = null; + this.doc = XMLUtils.getOwnerDocument(n); + + try { + this.writer = new StringWriter(); + + this.canonicalizeXPathNodeSet(this.doc); + this.writer.close(); + + return this.writer.toString(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } finally { + this.xpathNodeSet = null; + this.doc = null; + this.writer = null; + } + } + + /** + * Method canonicalizeXPathNodeSet + * + * @param currentNode + * @throws XMLSignatureException + * @throws IOException + */ + private void canonicalizeXPathNodeSet(Node currentNode) + throws XMLSignatureException, IOException { + + int currentNodeType = currentNode.getNodeType(); + switch (currentNodeType) { + + + case Node.ENTITY_NODE: + case Node.NOTATION_NODE: + case Node.DOCUMENT_FRAGMENT_NODE: + case Node.ATTRIBUTE_NODE: + throw new XMLSignatureException("empty"); + case Node.DOCUMENT_NODE: + this.writer.write(HTMLPrefix); + + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + this.writer.write(HTMLSuffix); + break; + + case Node.COMMENT_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + int position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputCommentToWriter((Comment) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.PROCESSING_INSTRUCTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputPItoWriter((ProcessingInstruction) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + outputTextToWriter(currentNode.getNodeValue()); + + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) + && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + /* + * The XPath data model allows to select only the first of a + * sequence of mixed text and CDATA nodes. But we must output + * them all, so we must search: + * + * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 + */ + this.outputTextToWriter(nextSibling.getNodeValue()); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.ELEMENT_NODE: + Element currentElement = (Element) currentNode; + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("<"); + this.writer.write(currentElement.getTagName()); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // we output all Attrs which are available + NamedNodeMap attrs = currentElement.getAttributes(); + int attrsLength = attrs.getLength(); + Attr attrs2[] = new Attr[attrsLength]; + + for (int i = 0; i < attrsLength; i++) { + attrs2[i] = (Attr)attrs.item(i); + } + + Arrays.sort(attrs2, ATTR_COMPARE); + Object attrs3[] = attrs2; + + for (int i = 0; i < attrsLength; i++) { + Attr a = (Attr) attrs3[i]; + boolean included = this.xpathNodeSet.contains(a); + boolean inclusive = this.inclusiveNamespaces.contains(a.getName()); + + if (included) { + if (inclusive) { + // included and inclusive + this.writer.write(HTMLIncludedInclusiveNamespacePrefix); + } else { + // included and not inclusive + this.writer.write(HTMLIncludePrefix); + } } else { - this._xpathNodeSet = xmlSignatureInput._inputNodeSet; - } - } - - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - * @param inclusiveNamespace - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput, Set inclusiveNamespace) { - - this(xmlSignatureInput); - - this._inclusiveNamespaces = inclusiveNamespace; - } - - /** - * Method getHTMLRepresentation - * - * @return The HTML Representation. - * @throws XMLSignatureException - */ - public String getHTMLRepresentation() throws XMLSignatureException { - - if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) { - return HTMLPrefix + "no node set, sorry" - + HTMLSuffix; - } - - { - - // get only a single node as anchor to fetch the owner document - Node n = this._xpathNodeSet.iterator().next(); - - this._doc = XMLUtils.getOwnerDocument(n); - } - - try { - this._writer = new StringWriter(); - - this.canonicalizeXPathNodeSet(this._doc); - this._writer.close(); - - return this._writer.toString(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } finally { - this._xpathNodeSet = null; - this._doc = null; - this._writer = null; - } - } - - /** - * Method canonicalizeXPathNodeSet - * - * @param currentNode - * @throws XMLSignatureException - * @throws IOException - */ - private void canonicalizeXPathNodeSet(Node currentNode) - throws XMLSignatureException, IOException { - - int currentNodeType = currentNode.getNodeType(); - switch (currentNodeType) { - - case Node.DOCUMENT_TYPE_NODE: - default: - break; - - case Node.ENTITY_NODE: - case Node.NOTATION_NODE: - case Node.DOCUMENT_FRAGMENT_NODE: - case Node.ATTRIBUTE_NODE: - throw new XMLSignatureException("empty"); - case Node.DOCUMENT_NODE: - this._writer.write(HTMLPrefix); - - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - this._writer.write(HTMLSuffix); - break; - - case Node.COMMENT_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - int position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputCommentToWriter((Comment) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputPItoWriter((ProcessingInstruction) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.TEXT_NODE: - case Node.CDATA_SECTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - outputTextToWriter(currentNode.getNodeValue()); - - for (Node nextSibling = currentNode.getNextSibling(); (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) || (nextSibling - .getNodeType() == Node.CDATA_SECTION_NODE)); nextSibling = nextSibling - .getNextSibling()) { - - /* - * The XPath data model allows to select only the first of a - * sequence of mixed text and CDATA nodes. But we must output - * them all, so we must search: - * - * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 - */ - this.outputTextToWriter(nextSibling.getNodeValue()); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.ELEMENT_NODE: - Element currentElement = (Element) currentNode; - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("<"); - this._writer.write(currentElement.getTagName()); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // we output all Attrs which are available - NamedNodeMap attrs = currentElement.getAttributes(); - int attrsLength = attrs.getLength(); - Attr attrs2[] = new Attr[attrsLength]; - - for (int i = 0; i < attrsLength; i++) { - attrs2[i] = (Attr)attrs.item(i); - } - - Arrays.sort(attrs2, ATTR_COMPARE); - Object attrs3[] = attrs2; - - for (int i = 0; i < attrsLength; i++) { - Attr a = (Attr) attrs3[i]; - boolean included = this._xpathNodeSet.contains(a); - boolean inclusive = this._inclusiveNamespaces.contains(a - .getName()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespacePrefix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludePrefix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespacePrefix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludePrefix); - } - } - - this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespaceSuffix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludeSuffix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespaceSuffix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludeSuffix); - } - } - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // traversal - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("</"); - this._writer.write(currentElement.getTagName()); - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - } - } - - /** - * Checks whether a Comment or ProcessingInstruction is before or after the - * document element. This is needed for prepending or appending "\n"s. - * - * @param currentNode - * comment or pi to check - * @return NODE_BEFORE_DOCUMENT_ELEMENT, - * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or - * NODE_AFTER_DOCUMENT_ELEMENT - * @see #NODE_BEFORE_DOCUMENT_ELEMENT - * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT - * @see #NODE_AFTER_DOCUMENT_ELEMENT - */ - private int getPositionRelativeToDocumentElement(Node currentNode) { - - if (currentNode == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - Document doc = currentNode.getOwnerDocument(); - - if (currentNode.getParentNode() != doc) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - Element documentElement = doc.getDocumentElement(); - - if (documentElement == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - if (documentElement == currentNode) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - for (Node x = currentNode; x != null; x = x.getNextSibling()) { - if (x == documentElement) { - return NODE_BEFORE_DOCUMENT_ELEMENT; - } - } - - return NODE_AFTER_DOCUMENT_ELEMENT; - } - - /** - * Normalizes an {@link Attr}ibute value - * - * The string value of the node is modified by replacing - *
      - *
    • all ampersands (&) with &amp;
    • - *
    • all open angle brackets (<) with &lt;
    • - *
    • all quotation mark characters with &quot;
    • - *
    • and the whitespace characters #x9, #xA, and #xD, - * with character references. The character references are written in - * uppercase hexadecimal with no leading zeroes (for example, #xD - * is represented by the character reference &#xD;)
    • - *
    - * - * @param name - * @param value - * @throws IOException - */ - private void outputAttrToWriter(String name, String value) - throws IOException { - - this._writer.write(" "); - this._writer.write(name); - this._writer.write("=\""); - - int length = value.length(); - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '"': - this._writer.write("&quot;"); - break; - - case 0x09: // '\t' - this._writer.write("&#x9;"); - break; - - case 0x0A: // '\n' - this._writer.write("&#xA;"); - break; - - case 0x0D: // '\r' - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("\""); - } - - /** - * Normalizes a {@link org.w3c.dom.Comment} value - * - * @param currentPI - * @throws IOException - */ - private void outputPItoWriter(ProcessingInstruction currentPI) - throws IOException { - - if (currentPI == null) { - return; - } - - this._writer.write("<?"); - - String target = currentPI.getTarget(); - int length = target.length(); - - for (int i = 0; i < length; i++) { - char c = target.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - String data = currentPI.getData(); - - length = data.length(); - - if (length > 0) { - this._writer.write(" "); - - for (int i = 0; i < length; i++) { - char c = data.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } + if (inclusive) { + // excluded and inclusive + this.writer.write(HTMLExcludedInclusiveNamespacePrefix); + } else { + // excluded and not inclusive + this.writer.write(HTMLExcludePrefix); } } - this._writer.write("?>"); + this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); + this.writer.write(HTMLIncludeOrExcludeSuffix); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // traversal + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; + currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("</"); + this.writer.write(currentElement.getTagName()); + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.DOCUMENT_TYPE_NODE: + default: + break; + } + } + + /** + * Checks whether a Comment or ProcessingInstruction is before or after the + * document element. This is needed for prepending or appending "\n"s. + * + * @param currentNode + * comment or pi to check + * @return NODE_BEFORE_DOCUMENT_ELEMENT, + * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or + * NODE_AFTER_DOCUMENT_ELEMENT + * @see #NODE_BEFORE_DOCUMENT_ELEMENT + * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT + * @see #NODE_AFTER_DOCUMENT_ELEMENT + */ + private int getPositionRelativeToDocumentElement(Node currentNode) { + if (currentNode == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputCommentToWriter - * - * @param currentComment - * @throws IOException - */ - private void outputCommentToWriter(Comment currentComment) - throws IOException { + Document doc = currentNode.getOwnerDocument(); - if (currentComment == null) { - return; - } - - this._writer.write("<!--"); - - String data = currentComment.getData(); - int length = data.length(); - - for (int i = 0; i < length; i++) { - char c = data.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("-->"); + if (currentNode.getParentNode() != doc) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputTextToWriter - * - * @param text - * @throws IOException - */ - private void outputTextToWriter(String text) throws IOException { + Element documentElement = doc.getDocumentElement(); - if (text == null) { - return; - } - - int length = text.length(); - - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '>': - this._writer.write("&gt;"); - break; - - case 0xD: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } + if (documentElement == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } + + if (documentElement == currentNode) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } + + for (Node x = currentNode; x != null; x = x.getNextSibling()) { + if (x == documentElement) { + return NODE_BEFORE_DOCUMENT_ELEMENT; + } + } + + return NODE_AFTER_DOCUMENT_ELEMENT; + } + + /** + * Normalizes an {@link Attr}ibute value + * + * The string value of the node is modified by replacing + *
      + *
    • all ampersands (&) with &amp;
    • + *
    • all open angle brackets (<) with &lt;
    • + *
    • all quotation mark characters with &quot;
    • + *
    • and the whitespace characters #x9, #xA, and #xD, + * with character references. The character references are written in + * uppercase hexadecimal with no leading zeroes (for example, #xD + * is represented by the character reference &#xD;)
    • + *
    + * + * @param name + * @param value + * @throws IOException + */ + private void outputAttrToWriter(String name, String value) throws IOException { + this.writer.write(" "); + this.writer.write(name); + this.writer.write("=\""); + + int length = value.length(); + + for (int i = 0; i < length; i++) { + char c = value.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '"': + this.writer.write("&quot;"); + break; + + case 0x09: // '\t' + this.writer.write("&#x9;"); + break; + + case 0x0A: // '\n' + this.writer.write("&#xA;"); + break; + + case 0x0D: // '\r' + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("\""); + } + + /** + * Normalizes a {@link org.w3c.dom.Comment} value + * + * @param currentPI + * @throws IOException + */ + private void outputPItoWriter(ProcessingInstruction currentPI) throws IOException { + + if (currentPI == null) { + return; + } + + this.writer.write("<?"); + + String target = currentPI.getTarget(); + int length = target.length(); + + for (int i = 0; i < length; i++) { + char c = target.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + String data = currentPI.getData(); + + length = data.length(); + + if (length > 0) { + this.writer.write(" "); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + } + + this.writer.write("?>"); + } + + /** + * Method outputCommentToWriter + * + * @param currentComment + * @throws IOException + */ + private void outputCommentToWriter(Comment currentComment) throws IOException { + + if (currentComment == null) { + return; + } + + this.writer.write("<!--"); + + String data = currentComment.getData(); + int length = data.length(); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("-->"); + } + + /** + * Method outputTextToWriter + * + * @param text + * @throws IOException + */ + private void outputTextToWriter(String text) throws IOException { + if (text == null) { + return; + } + + int length = text.length(); + + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '>': + this.writer.write("&gt;"); + break; + + case 0xD: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java new file mode 100644 index 00000000000..81de122aead --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java @@ -0,0 +1,34 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +/** + * An abstract representation of the result of dereferencing a ds:Reference URI. + */ +public interface ReferenceData { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java new file mode 100644 index 00000000000..dc18c427eb7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java @@ -0,0 +1,53 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.Iterator; + +import org.w3c.dom.Node; + +/** + * An abstract representation of a ReferenceData type containing a node-set. + */ +public interface ReferenceNodeSetData extends ReferenceData { + + /** + * Returns a read-only iterator over the nodes contained in this + * NodeSetData in + * + * document order. Attempts to modify the returned iterator + * via the remove method throw + * UnsupportedOperationException. + * + * @return an Iterator over the nodes in this + * NodeSetData in document order + */ + Iterator iterator(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java new file mode 100644 index 00000000000..0f59fb95bcf --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java @@ -0,0 +1,105 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.io.InputStream; + +/** + * A representation of a ReferenceData type containing an OctetStream. + */ +public class ReferenceOctetStreamData implements ReferenceData { + private InputStream octetStream; + private String uri; + private String mimeType; + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + } + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @param uri the URI String identifying the data object (may be + * null) + * @param mimeType the MIME type associated with the data object (may be + * null) + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream, String uri, + String mimeType) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + this.uri = uri; + this.mimeType = mimeType; + } + + /** + * Returns the input stream of this ReferenceOctetStreamData. + * + * @return the input stream of this ReferenceOctetStreamData. + */ + public InputStream getOctetStream() { + return octetStream; + } + + /** + * Returns the URI String identifying the data object represented by this + * ReferenceOctetStreamData. + * + * @return the URI String or null if not applicable + */ + public String getURI() { + return uri; + } + + /** + * Returns the MIME type associated with the data object represented by this + * ReferenceOctetStreamData. + * + * @return the MIME type or null if not applicable + */ + public String getMimeType() { + return mimeType; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java new file mode 100644 index 00000000000..cfa45e0435a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java @@ -0,0 +1,181 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * A representation of a ReferenceNodeSetData type containing a node-set. + * This is a subtype of NodeSetData that represents a dereferenced + * same-document URI as the root of a subdocument. The main reason is + * for efficiency and performance, as some transforms can operate + * directly on the subdocument and there is no need to convert it + * first to an XPath node-set. + */ +public class ReferenceSubTreeData implements ReferenceNodeSetData { + + private boolean excludeComments; + private Node root; + + public ReferenceSubTreeData(Node root, boolean excludeComments) { + this.root = root; + this.excludeComments = excludeComments; + } + + public Iterator iterator() { + return new DelayedNodeIterator(root, excludeComments); + } + + public Node getRoot() { + return root; + } + + public boolean excludeComments() { + return excludeComments; + } + + /** + * This is an Iterator that contains a backing node-set that is + * not populated until the caller first attempts to advance the iterator. + */ + static class DelayedNodeIterator implements Iterator { + private Node root; + private List nodeSet; + private ListIterator li; + private boolean withComments; + + DelayedNodeIterator(Node root, boolean excludeComments) { + this.root = root; + this.withComments = !excludeComments; + } + + public boolean hasNext() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + return li.hasNext(); + } + + public Node next() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + if (li.hasNext()) { + return li.next(); + } else { + throw new NoSuchElementException(); + } + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Dereferences a same-document URI fragment. + * + * @param node the node (document or element) referenced by the + * URI fragment. If null, returns an empty set. + * @return a set of nodes (minus any comment nodes) + */ + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); + if (node != null) { + nodeSetMinusCommentNodes(node, nodeSet, null); + } + return nodeSet; + } + + /** + * Recursively traverses the subtree, and returns an XPath-equivalent + * node-set of all nodes traversed, excluding any comment nodes, + * if specified. + * + * @param node the node to traverse + * @param nodeSet the set of nodes traversed so far + * @param the previous sibling node + */ + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + nodeSet.add(node); + NamedNodeMap attrs = node.getAttributes(); + if (attrs != null) { + for (int i = 0, len = attrs.getLength(); i < len; i++) { + nodeSet.add(attrs.item(i)); + } + } + Node pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.DOCUMENT_NODE : + pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE: + // emulate XPath which only returns the first node in + // contiguous text/cdata nodes + if (prevSibling != null && + (prevSibling.getNodeType() == Node.TEXT_NODE || + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; + } + nodeSet.add(node); + break; + case Node.PROCESSING_INSTRUCTION_NODE : + nodeSet.add(node); + break; + case Node.COMMENT_NODE: + if (withComments) { + nodeSet.add(node); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java index 2236e950853..68ceb3bf243 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java @@ -2,86 +2,84 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class InvalidTransformException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidTransformException - * - */ - public InvalidTransformException() { - super(); - } + /** + * Constructor InvalidTransformException + * + */ + public InvalidTransformException() { + super(); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - */ - public InvalidTransformException(String _msgId) { - super(_msgId); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + */ + public InvalidTransformException(String msgId) { + super(msgId); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - */ - public InvalidTransformException(String _msgId, Object exArgs[]) { - super(_msgId, exArgs); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + */ + public InvalidTransformException(String msgId, Object exArgs[]) { + super(msgId, exArgs); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param _originalException - */ - public InvalidTransformException(String _msgId, Exception _originalException) { - super(_msgId, _originalException); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param originalException + */ + public InvalidTransformException(String msgId, Exception originalException) { + super(msgId, originalException); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - * @param _originalException - */ - public InvalidTransformException(String _msgId, Object exArgs[], - Exception _originalException) { - super(_msgId, exArgs, _originalException); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + * @param originalException + */ + public InvalidTransformException(String msgId, Object exArgs[], Exception originalException) { + super(msgId, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java index 3c910219bfd..37d67ba9f24 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java @@ -263,7 +263,7 @@ public final class Transform extends SignatureElementProxy { * @return the URI representation of Transformation algorithm */ public String getURI() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); } /** @@ -329,7 +329,7 @@ public final class Transform extends SignatureElementProxy { private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes) throws InvalidTransformException { - this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); Class transformSpiClass = transformSpiHash.get(algorithmURI); if (transformSpiClass == null) { @@ -360,7 +360,7 @@ public final class Transform extends SignatureElementProxy { // give it to the current document if (contextNodes != null) { for (int i = 0; i < contextNodes.getLength(); i++) { - this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); + this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); } } return newTransformSpi; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java index d6c16fa771e..0624c8c7759 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java @@ -2,29 +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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; -/** - * - * @author $Author: mullan $ - */ - public interface TransformParam { -} +} \ No newline at end of file diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java index 35aa9ff0f6e..7607d188be5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; @@ -37,28 +39,13 @@ import org.xml.sax.SAXException; * @author Christian Geuer-Pollmann */ public abstract class TransformSpi { - /** - * For API compatibility not thread safe. - * @deprecated - */ - @Deprecated - protected Transform _transformObject = null; - /** - * Set the transform object. - * Depeprecated For API compatibility. - * @param transform the Transform - * @deprecated - */ - @Deprecated - protected void setTransform(Transform transform) { - this._transformObject = transform; - } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * * @param input {@link XMLSignatureInput} as the input of transformation * @param os where to output this transformation. - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -68,13 +55,12 @@ public abstract class TransformSpi { * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, OutputStream os, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - return enginePerformTransform(input, _transformObject); + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + throw new UnsupportedOperationException(); } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * In order to be compatible with preexisting Transform implementations, @@ -83,7 +69,7 @@ public abstract class TransformSpi { * implementation. * * @param input {@link XMLSignatureInput} as the input of transformation - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -93,26 +79,14 @@ public abstract class TransformSpi { * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - //Default implementation overide with a much better - try { - TransformSpi tmp = (TransformSpi) getClass().newInstance(); - tmp.setTransform(_transformObject); - return tmp.enginePerformTransform(input); - } catch (InstantiationException e) { - throw new TransformationException("",e); - } catch (IllegalAccessException e) { - throw new TransformationException("",e); - } + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null, transformObject); } /** * The mega method which MUST be implemented by the Transformation Algorithm. - * @deprecated * @param input {@link XMLSignatureInput} as the input of transformation * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException @@ -122,15 +96,13 @@ public abstract class TransformSpi { * @throws SAXException * @throws TransformationException */ - @Deprecated protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - throw new UnsupportedOperationException(); + XMLSignatureInput input + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null); } + /** * Returns the URI representation of Transformation algorithm * diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java index 10e8723e238..1296475f6b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java @@ -2,86 +2,83 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class TransformationException extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor TransformationException + * + */ + public TransformationException() { + super(); + } - /** - * Constructor TransformationException - * - */ - public TransformationException() { - super(); - } + /** + * Constructor TransformationException + * + * @param msgID + */ + public TransformationException(String msgID) { + super(msgID); + } - /** - * Constructor TransformationException - * - * @param _msgID - */ - public TransformationException(String _msgID) { - super(_msgID); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + */ + public TransformationException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - */ - public TransformationException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param originalException + */ + public TransformationException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor TransformationException - * - * @param _msgID - * @param _originalException - */ - public TransformationException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public TransformationException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public TransformationException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java index ce44e1713e4..7f29fd6a9f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; @@ -51,56 +53,64 @@ import org.w3c.dom.NodeList; */ public class Transforms extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(Transforms.class.getName()); /** Canonicalization - Required Canonical XML (omits comments) */ public static final String TRANSFORM_C14N_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML with Comments */ public static final String TRANSFORM_C14N_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + /** Canonicalization - Required Canonical XML 1.1 (omits comments) */ public static final String TRANSFORM_C14N11_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML 1.1 with Comments */ public static final String TRANSFORM_C14N11_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS; + /** Canonicalization - Required Exclusive Canonicalization (omits comments) */ public static final String TRANSFORM_C14N_EXCL_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + /** Canonicalization - Recommended Exclusive Canonicalization with Comments */ public static final String TRANSFORM_C14N_EXCL_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + /** Transform - Optional XSLT */ public static final String TRANSFORM_XSLT = "http://www.w3.org/TR/1999/REC-xslt-19991116"; + /** Transform - Required base64 decoding */ public static final String TRANSFORM_BASE64_DECODE = Constants.SignatureSpecNS + "base64"; + /** Transform - Recommended XPath */ public static final String TRANSFORM_XPATH = "http://www.w3.org/TR/1999/REC-xpath-19991116"; + /** Transform - Required Enveloped Signature */ public static final String TRANSFORM_ENVELOPED_SIGNATURE = Constants.SignatureSpecNS + "enveloped-signature"; + /** Transform - XPointer */ public static final String TRANSFORM_XPOINTER = "http://www.w3.org/TR/2001/WD-xptr-20010108"; - /** Transform - XPath Filter v2.0 */ - public static final String TRANSFORM_XPATH2FILTER04 - = "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Transform - XPath Filter */ public static final String TRANSFORM_XPATH2FILTER = "http://www.w3.org/2002/06/xmldsig-filter2"; - /** Transform - XPath Filter CHGP private */ - public static final String TRANSFORM_XPATHFILTERCHGP - = "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - Element []transforms; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Transforms.class.getName()); + + private Element[] transforms; protected Transforms() { }; + private boolean secureValidation; + /** * Constructs {@link Transforms}. * @@ -109,7 +119,7 @@ public class Transforms extends SignatureElementProxy { */ public Transforms(Document doc) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -125,24 +135,27 @@ public class Transforms extends SignatureElementProxy { * @throws XMLSignatureException */ public Transforms(Element element, String BaseURI) - throws DOMException, XMLSignatureException, - InvalidTransformException, TransformationException, - XMLSecurityException { - + throws DOMException, XMLSignatureException, InvalidTransformException, + TransformationException, XMLSecurityException { super(element, BaseURI); int numberOfTransformElems = this.getLength(); if (numberOfTransformElems == 0) { - // At least one Transform element must be present. Bad. - Object exArgs[] = { Constants._TAG_TRANSFORM, - Constants._TAG_TRANSFORMS }; + Object exArgs[] = { Constants._TAG_TRANSFORM, Constants._TAG_TRANSFORMS }; throw new TransformationException("xml.WrongContent", exArgs); } } + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + /** * Adds the Transform with the specified Transform * algorithm URI @@ -151,14 +164,13 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @throws TransformationException */ - public void addTransform(String transformURI) - throws TransformationException { - + public void addTransform(String transformURI) throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI); + Transform transform = new Transform(this.doc, transformURI); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -174,16 +186,15 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @param contextElement * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, Element childElement) */ public void addTransform(String transformURI, Element contextElement) - throws TransformationException { - + throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI, contextElement); + Transform transform = new Transform(this.doc, transformURI, contextElement); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -199,13 +210,12 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @param contextNodes * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, NodeList contextNodes) */ public void addTransform(String transformURI, NodeList contextNodes) - throws TransformationException { + throws TransformationException { try { - Transform transform = new Transform(this._doc, transformURI, contextNodes); + Transform transform = new Transform(this.doc, transformURI, contextNodes); this.addTransform(transform); } catch (InvalidTransformException ex) { throw new TransformationException("empty", ex); @@ -218,13 +228,14 @@ public class Transforms extends SignatureElementProxy { * @param transform {@link Transform} object */ private void addTransform(Transform transform) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")"); + } Element transformElement = transform.getElement(); - this._constructionElement.appendChild(transformElement); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(transformElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -236,7 +247,8 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput) throws TransformationException { + XMLSignatureInput xmlSignatureInput + ) throws TransformationException { return performTransforms(xmlSignatureInput, null); } @@ -250,21 +262,22 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput, OutputStream os) - throws TransformationException { - + XMLSignatureInput xmlSignatureInput, OutputStream os + ) throws TransformationException { try { - int last=this.getLength()-1; + int last = this.getLength() - 1; for (int i = 0; i < last; i++) { Transform t = this.item(i); + String uri = t.getURI(); if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + t.getURI() - + " transform"); + log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform"); } + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput); } - if (last>=0) { + if (last >= 0) { Transform t = this.item(last); + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput, os); } @@ -278,16 +291,26 @@ public class Transforms extends SignatureElementProxy { } } + private void checkSecureValidation(Transform transform) throws TransformationException { + String uri = transform.getURI(); + if (secureValidation && Transforms.TRANSFORM_XSLT.equals(uri)) { + Object exArgs[] = { uri }; + + throw new TransformationException( + "signature.Transform.ForbiddenTransform", exArgs + ); + } + } + /** * Return the nonnegative number of transformations. * * @return the number of transformations */ - public int getLength() - { + public int getLength() { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } return transforms.length; } @@ -301,13 +324,12 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public Transform item(int i) throws TransformationException { - try { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } - return new Transform(transforms[i], this._baseURI); + return new Transform(transforms[i], this.baseURI); } catch (XMLSecurityException ex) { throw new TransformationException("empty", ex); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java index 15c1b576df5..7d8cc74e1ef 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.dtm.DTM; @@ -36,7 +36,6 @@ import com.sun.org.apache.xpath.internal.res.XPATHErrorResources; import org.w3c.dom.Document; import org.w3c.dom.Node; - /** * The 'here()' function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node @@ -56,107 +55,98 @@ import org.w3c.dom.Node; */ public class FuncHere extends Function { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * The here function returns a node-set containing the attribute or - * processing instruction node or the parent element of the text node - * that directly bears the XPath expression. This expression results - * in an error if the containing XPath expression does not appear in the - * same XML document against which the XPath expression is being evaluated. - * - * @param xctxt - * @return the xobject - * @throws javax.xml.transform.TransformerException - */ - public XObject execute(XPathContext xctxt) - throws javax.xml.transform.TransformerException { + /** + * The here function returns a node-set containing the attribute or + * processing instruction node or the parent element of the text node + * that directly bears the XPath expression. This expression results + * in an error if the containing XPath expression does not appear in the + * same XML document against which the XPath expression is being evaluated. + * + * @param xctxt + * @return the xobject + * @throws javax.xml.transform.TransformerException + */ + @Override + public XObject execute(XPathContext xctxt) + throws javax.xml.transform.TransformerException { - Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); + Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); - if (xpathOwnerNode == null) { - return null; - } + if (xpathOwnerNode == null) { + return null; + } - int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); + int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); - int currentNode = xctxt.getCurrentNode(); - DTM dtm = xctxt.getDTM(currentNode); - int docContext = dtm.getDocument(); + int currentNode = xctxt.getCurrentNode(); + DTM dtm = xctxt.getDTM(currentNode); + int docContext = dtm.getDocument(); - if (DTM.NULL == docContext) { - error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); - } + if (DTM.NULL == docContext) { + error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); + } - { + { + // check whether currentNode and the node containing the XPath expression + // are in the same document + Document currentDoc = + XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); + Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); - // check whether currentNode and the node containing the XPath expression - // are in the same document - Document currentDoc = - XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); - Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); + if (currentDoc != xpathOwnerDoc) { + throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); + } + } - if (currentDoc != xpathOwnerDoc) { - throw new TransformerException(I18n - .translate("xpath.funcHere.documentsDiffer")); - } - } + XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); + NodeSetDTM nodeSet = nodes.mutableNodeset(); - XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); - NodeSetDTM nodeSet = nodes.mutableNodeset(); + { + int hereNode = DTM.NULL; - { - int hereNode = DTM.NULL; + switch (dtm.getNodeType(xpathOwnerNodeDTM)) { - switch (dtm.getNodeType(xpathOwnerNodeDTM)) { + case Node.ATTRIBUTE_NODE : + case Node.PROCESSING_INSTRUCTION_NODE : { + // returns a node-set containing the attribute / processing instruction node + hereNode = xpathOwnerNodeDTM; - case Node.ATTRIBUTE_NODE : { - // returns a node-set containing the attribute - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + case Node.TEXT_NODE : { + // returns a node-set containing the parent element of the + // text node that directly bears the XPath expression + hereNode = dtm.getParent(xpathOwnerNodeDTM); - break; - } - case Node.PROCESSING_INSTRUCTION_NODE : { - // returns a node-set containing the processing instruction node - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + default : + break; + } + } - break; - } - case Node.TEXT_NODE : { - // returns a node-set containing the parent element of the - // text node that directly bears the XPath expression - hereNode = dtm.getParent(xpathOwnerNodeDTM); + /** $todo$ Do I have to do this detach() call? */ + nodeSet.detach(); - nodeSet.addNode(hereNode); + return nodes; + } - break; - } - default : - break; - } - } - - /** $todo$ Do I have to do this detach() call? */ - nodeSet.detach(); - - return nodes; - } - - /** - * No arguments to process, so this does nothing. - * @param vars - * @param globalsSize - */ - @SuppressWarnings("rawtypes") - public void fixupVariables(java.util.Vector vars, int globalsSize) { - - // do nothing - } + /** + * No arguments to process, so this does nothing. + * @param vars + * @param globalsSize + */ + @SuppressWarnings("rawtypes") + public void fixupVariables(java.util.Vector vars, int globalsSize) { + // do nothing + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java deleted file mode 100644 index 6cc15ae3898..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.transforms.implementations; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.XPathContext; -import org.w3c.dom.Node; - - -/** - * {@link FuncHereContext} extends {@link XPathContext} for supplying context - * for the here() function. The here() function needs to know - * where in an XML instance the XPath text string appeared. This can be - * in {@link org.w3c.dom.Text}, {@link org.w3c.dom.Attr}ibutes and {@ProcessingInstrinction} nodes. The - * correct node must be supplied to the constructor of {@link FuncHereContext}. - * The supplied Node MUST contain the XPath which is to be executed. - * - *
    - * From: Scott_Boag\@lotus.com
    - * To: Christian Geuer-Pollmann 
    - * CC: xalan-dev@xml.apache.org
    - * Subject: Re: Cleanup of XPathContext & definition of XSLTContext
    - * Date: Tue, 21 Aug 2001 18:36:24 -0400
    - *
    - * > My point is to say to get this baby to run, the XPath must have a
    - * > possibility to retrieve the information where itself occured in a
    - * > document.
    - *
    - * It sounds to me like you have to derive an XMLSigContext from the
    - * XPathContext?
    - *
    - * > and supplied the Node which contains the xpath string as "owner". Question:
    - * > Is this the correct use of the owner object? It works, but I don't know
    - * > whether this is correct from the xalan-philosophy...
    - *
    - * Philosophically it's fine.  The owner is the TransformerImpl if XPath is
    - * running under XSLT.  If it is not running under XSLT, it can be whatever
    - * you want.
    - *
    - * -scott
    - * 
    - * - * @author $Author: mullan $ - * @see com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere - * @see com.sun.org.apache.xml.internal.security.utils.XPathFuncHereAPI - * @see XML Signature - The here() function - */ -public class FuncHereContext extends XPathContext { - - /** - * This constuctor is disabled because if we use the here() function we - * always need to know in which node the XPath occured. - */ - private FuncHereContext() {} - - /** - * Constructor FuncHereContext - * - * @param owner - */ - public FuncHereContext(Node owner) { - super(owner); - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param xpathContext - */ - public FuncHereContext(Node owner, XPathContext xpathContext) { - - super(owner); - - try { - super.m_dtmManager = xpathContext.getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param previouslyUsed - */ - public FuncHereContext(Node owner, CachedXPathAPI previouslyUsed) { - - super(owner); - - try { - super.m_dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param dtmManager - */ - public FuncHereContext(Node owner, DTMManager dtmManager) { - - super(owner); - - try { - super.m_dtmManager = dtmManager; - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java index b1d3de8bce7..206d31016cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStream; @@ -72,115 +72,106 @@ import org.xml.sax.SAXException; */ public class TransformBase64Decode extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_BASE64_DECODE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_BASE64_DECODE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return TransformBase64Decode.implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return TransformBase64Decode.implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @inheritDoc - * @throws CanonicalizationException - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @inheritDoc + * @throws CanonicalizationException + * @throws IOException + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + return enginePerformTransform(input, null, transformObject); + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, - OutputStream os, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - try { - if (input.isElement()) { - Node el=input.getSubNode(); - if (input.getSubNode().getNodeType()==Node.TEXT_NODE) { - el=el.getParentNode(); - } - StringBuffer sb=new StringBuffer(); - traverseElement((Element)el,sb); - if (os==null) { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + try { + if (input.isElement()) { + Node el = input.getSubNode(); + if (input.getSubNode().getNodeType() == Node.TEXT_NODE) { + el = el.getParentNode(); + } + StringBuilder sb = new StringBuilder(); + traverseElement((Element)el, sb); + if (os == null) { + byte[] decodedBytes = Base64.decode(sb.toString()); + return new XMLSignatureInput(decodedBytes); + } + Base64.decode(sb.toString(), os); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + if (input.isOctetStream() || input.isNodeSet()) { + if (os == null) { + byte[] base64Bytes = input.getBytes(); + byte[] decodedBytes = Base64.decode(base64Bytes); + return new XMLSignatureInput(decodedBytes); + } + if (input.isByteArray() || input.isNodeSet()) { + Base64.decode(input.getBytes(), os); + } else { + Base64.decode(new BufferedInputStream(input.getOctetStreamReal()), os); + } + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + try { + //Exceptional case there is current not text case testing this(Before it was a + //a common case). + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document doc = + dbf.newDocumentBuilder().parse(input.getOctetStream()); + + Element rootNode = doc.getDocumentElement(); + StringBuilder sb = new StringBuilder(); + traverseElement(rootNode, sb); byte[] decodedBytes = Base64.decode(sb.toString()); return new XMLSignatureInput(decodedBytes); - } - Base64.decode(sb.toString(),os); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - } - if (input.isOctetStream() || input.isNodeSet()) { - - - if (os==null) { - byte[] base64Bytes = input.getBytes(); - byte[] decodedBytes = Base64.decode(base64Bytes); - return new XMLSignatureInput(decodedBytes); - } - if (input.isByteArray() || input.isNodeSet()) { - Base64.decode(input.getBytes(),os); - } else { - Base64.decode(new BufferedInputStream(input.getOctetStreamReal()) - ,os); - } - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - - } - - try { - // Exceptional case there is current not text case testing this - // (before it was a a common case). - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - Document doc = - dbf.newDocumentBuilder().parse(input.getOctetStream()); - - Element rootNode = doc.getDocumentElement(); - StringBuffer sb = new StringBuffer(); - traverseElement(rootNode,sb); - byte[] decodedBytes = Base64.decode(sb.toString()); - - return new XMLSignatureInput(decodedBytes); - } catch (ParserConfigurationException e) { - throw new TransformationException("c14n.Canonicalizer.Exception",e); - } catch (SAXException e) { - throw new TransformationException("SAX exception", e); - } + } catch (ParserConfigurationException e) { + throw new TransformationException("c14n.Canonicalizer.Exception",e); + } catch (SAXException e) { + throw new TransformationException("SAX exception", e); + } } catch (Base64DecodingException e) { throw new TransformationException("Base64Decoding", e); } - } + } - void traverseElement(org.w3c.dom.Element node,StringBuffer sb) { - Node sibling=node.getFirstChild(); - while (sibling!=null) { - switch (sibling.getNodeType()) { - case Node.ELEMENT_NODE: - traverseElement((Element)sibling,sb); - break; - case Node.TEXT_NODE: - sb.append(((Text)sibling).getData()); + void traverseElement(org.w3c.dom.Element node, StringBuilder sb) { + Node sibling = node.getFirstChild(); + while (sibling != null) { + switch (sibling.getNodeType()) { + case Node.ELEMENT_NODE: + traverseElement((Element)sibling, sb); + break; + case Node.TEXT_NODE: + sb.append(((Text)sibling).getData()); } - sibling=sibling.getNextSibling(); + sibling = sibling.getNextSibling(); } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java index 1b0c7fb6448..9c94199be05 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -37,39 +39,30 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14N extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + /** + * @inheritDoc + */ + protected String engineGetURI() { + return TransformC14N.implementedTransformURI; + } - /** - * @inheritDoc - */ - protected String engineGetURI() { - return TransformC14N.implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { output.setOutputStream(os); - } - return output; - } + } + return output; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java index a4f6e34025f..b3510fc06b5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,15 +43,9 @@ public class TransformC14N11 extends TransformSpi { return Transforms.TRANSFORM_C14N11_OMIT_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments(); if (os != null) { c14n.setWriter(os); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java index 1a7a213e718..e01f17312c7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,15 +43,9 @@ public class TransformC14N11_WithComments extends TransformSpi { return Transforms.TRANSFORM_C14N11_WITH_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments(); if (os != null) { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java index f4b2407055b..3b7bdd13691 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -36,71 +38,59 @@ import org.w3c.dom.Element; /** * Class TransformC14NExclusive * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public class TransformC14NExclusive extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return the transformed of the input - * @throws CanonicalizationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI()).getInclusiveNamespaces(); + } - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); - } + Canonicalizer20010315ExclOmitComments c14n = + new Canonicalizer20010315ExclOmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); - Canonicalizer20010315ExclOmitComments c14n = - new Canonicalizer20010315ExclOmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java index 2380750d052..d1456b30e00 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,59 +43,54 @@ import org.w3c.dom.Element; */ public class TransformC14NExclusiveWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; - /** - * Method engineGetURI - *@inheritDoc - * - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + *@inheritDoc + * + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI() + ).getInclusiveNamespaces(); + } - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); + Canonicalizer20010315ExclWithComments c14n = + new Canonicalizer20010315ExclWithComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); + XMLSignatureInput output = new XMLSignatureInput(result); + + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); } - - Canonicalizer20010315ExclWithComments c14n = - new Canonicalizer20010315ExclWithComments(); - if (os!=null) { - c14n.setWriter( os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - XMLSignatureInput output=new XMLSignatureInput(result); - - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java index b1087076d27..33aee9cd753 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -37,37 +39,31 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14NWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_WITH_COMMENTS; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { + /** @inheritDoc */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments(); - if (os!=null) { - c14n.setWriter( os); + if (os != null) { + c14n.setWriter(os); } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java index c447468bd63..9f108c1bb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java @@ -2,24 +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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.OutputStream; + import com.sun.org.apache.xml.internal.security.signature.NodeFilter; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -39,99 +43,99 @@ import org.w3c.dom.Node; */ public class TransformEnvelopedSignature extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_ENVELOPED_SIGNATURE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_ENVELOPED_SIGNATURE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - - - - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - - Node signatureElement = _transformObject.getElement(); - - - signatureElement = searchSignatureElement(signatureElement); - input.setExcludeNode(signatureElement); - input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); - return input; - - // - - - } - - /** - * @param signatureElement - * @return the node that is the signature - * @throws TransformationException - */ - private static Node searchSignatureElement(Node signatureElement) throws TransformationException { - boolean found=false; - - while (true) { - if ((signatureElement == null) - || (signatureElement.getNodeType() == Node.DOCUMENT_NODE)) { - break; - } - Element el=(Element)signatureElement; - if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) - && - el.getLocalName().equals(Constants._TAG_SIGNATURE)) { - found = true; - break; - } - - signatureElement = signatureElement.getParentNode(); - } - - if (!found) { - throw new TransformationException( - "envelopedSignatureTransformNotInSignatureElement"); - } - return signatureElement; + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; } - static class EnvelopedNodeFilter implements NodeFilter { - Node exclude; - EnvelopedNodeFilter(Node n) { - exclude=n; + + /** + * @inheritDoc + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + + Node signatureElement = transformObject.getElement(); + + signatureElement = searchSignatureElement(signatureElement); + input.setExcludeNode(signatureElement); + input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + return input; + } + + /** + * @param signatureElement + * @return the node that is the signature + * @throws TransformationException + */ + private static Node searchSignatureElement(Node signatureElement) + throws TransformationException { + boolean found = false; + + while (true) { + if (signatureElement == null + || signatureElement.getNodeType() == Node.DOCUMENT_NODE) { + break; + } + Element el = (Element) signatureElement; + if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) + && el.getLocalName().equals(Constants._TAG_SIGNATURE)) { + found = true; + break; + } + + signatureElement = signatureElement.getParentNode(); } - public int isNodeIncludeDO(Node n, int level) { - if ((n==exclude)) - return -1; - return 1; + + if (!found) { + throw new TransformationException( + "transform.envelopedSignatureTransformNotInSignatureElement"); + } + return signatureElement; } + + static class EnvelopedNodeFilter implements NodeFilter { + + Node exclude; + + EnvelopedNodeFilter(Node n) { + exclude = n; + } + + public int isNodeIncludeDO(Node n, int level) { + if (n == exclude) { + return -1; + } + return 1; + } + /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node n) { - if ((n==exclude) || XMLUtils.isDescendantOrSelf(exclude,n)) - return -1; - return 1; + if (n == exclude || XMLUtils.isDescendantOrSelf(exclude, n)) { + return -1; + } + return 1; //return !XMLUtils.isDescendantOrSelf(exclude,n); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java index f7411344f42..db958096963 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java @@ -2,24 +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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.OutputStream; + import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; @@ -29,12 +33,10 @@ import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.objects.XObject; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -51,118 +53,112 @@ import org.w3c.dom.Node; */ public class TransformXPath extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = Transforms.TRANSFORM_XPATH; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + Element xpathElement = + XMLUtils.selectDsNode( + transformObject.getElement().getFirstChild(), Constants._TAG_XPATH, 0); - try { + if (xpathElement == null) { + Object exArgs[] = { "ds:XPath", "Transform" }; - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); + throw new TransformationException("xml.WrongContent", exArgs); + } + Node xpathnode = xpathElement.getChildNodes().item(0); + String str = XMLUtils.getStrFromNode(xpathnode); + input.setNeedsToBeExpanded(needsCircumvent(str)); + if (xpathnode == null) { + throw new DOMException( + DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath" + ); + } + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance)); + input.setNodeSet(true); + return input; + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } + } - - Element xpathElement =XMLUtils.selectDsNode( - _transformObject.getElement().getFirstChild(), - Constants._TAG_XPATH,0); - - if (xpathElement == null) { - Object exArgs[] = { "ds:XPath", "Transform" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - Node xpathnode = xpathElement.getChildNodes().item(0); - String str=CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - input.setNeedsToBeExpanded(needsCircunvent(str)); - if (xpathnode == null) { - throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, - "Text must be in ds:Xpath"); - } - - - input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str)); - input.setNodeSet(true); - return input; - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } - } - - /** - * @param str - * @return true if needs to be circunvent for bug. - */ - private boolean needsCircunvent(String str) { - //return true; - //return false; + /** + * @param str + * @return true if needs to be circumvent for bug. + */ + private boolean needsCircumvent(String str) { return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1); } static class XPathNodeFilter implements NodeFilter { - PrefixResolverDefault prefixResolver; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + + XPathAPI xPathAPI; Node xpathnode; + Element xpathElement; String str; - XPathNodeFilter(Element xpathElement, - Node xpathnode, String str) { - this.xpathnode=xpathnode; - this.str=str; - prefixResolver =new PrefixResolverDefault(xpathElement); + + XPathNodeFilter(Element xpathElement, Node xpathnode, String str, XPathAPI xPathAPI) { + this.xpathnode = xpathnode; + this.str = str; + this.xpathElement = xpathElement; + this.xPathAPI = xPathAPI; } /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node currentNode) { - XObject includeInResult; try { - includeInResult = xPathFuncHereAPI.eval(currentNode, - xpathnode, str,prefixResolver); - if (includeInResult.bool()) - return 1; + boolean include = xPathAPI.evaluate(currentNode, xpathnode, str, xpathElement); + if (include) { + return 1; + } return 0; } catch (TransformerException e) { Object[] eArgs = {currentNode}; - throw new XMLSecurityRuntimeException - ("signature.Transform.node", eArgs, e); + throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e); } catch (Exception e) { - Object[] eArgs = {currentNode, new Short(currentNode.getNodeType())}; - throw new XMLSecurityRuntimeException - ("signature.Transform.nodeAndType",eArgs, e); + Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())}; + throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e); } } + public int isNodeIncludeDO(Node n, int level) { - return isNodeInclude(n); + return isNodeInclude(n); } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java index 2d805d13dd2..d35142222ae 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java @@ -2,30 +2,30 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - import java.io.IOException; +import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -42,9 +42,9 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.transforms.params.XPath2FilterContainer; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -55,254 +55,241 @@ import org.xml.sax.SAXException; /** * Implements the XML Signature XPath Filter v2.0 * - * @author $Author: mullan $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ public class TransformXPath2Filter extends TransformSpi { - /** {@link java.util.logging} logging facility */ -// static java.util.logging.Logger log = -// java.util.logging.Logger.getLogger( -// TransformXPath2Filter.class.getName()); + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPATH2FILTER; - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH2FILTER; - //J- - // contains the type of the filter + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - // contains the node set + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + List unionNodes = new ArrayList(); + List subtractNodes = new ArrayList(); + List intersectNodes = new ArrayList(); - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + Element[] xpathElements = + XMLUtils.selectNodes( + transformObject.getElement().getFirstChild(), + XPath2FilterContainer.XPathFilter2NS, + XPath2FilterContainer._TAG_XPATH2 + ); + if (xpathElements.length == 0) { + Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; + throw new TransformationException("xml.WrongContent", exArgs); + } + Document inputDoc = null; + if (input.getSubNode() != null) { + inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); - try { - List unionNodes=new ArrayList(); - List substractNodes=new ArrayList(); - List intersectNodes=new ArrayList(); + for (int i = 0; i < xpathElements.length; i++) { + Element xpathElement = xpathElements[i]; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + XPath2FilterContainer xpathContainer = + XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI()); + String str = + XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode()); - Element []xpathElements =XMLUtils.selectNodes( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2); - int noOfSteps = xpathElements.length; + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + NodeList subtreeRoots = + xpathAPIInstance.selectNodeList( + inputDoc, + xpathContainer.getXPathFilterTextNode(), + str, + xpathContainer.getElement()); + if (xpathContainer.isIntersect()) { + intersectNodes.add(subtreeRoots); + } else if (xpathContainer.isSubtract()) { + subtractNodes.add(subtreeRoots); + } else if (xpathContainer.isUnion()) { + unionNodes.add(subtreeRoots); + } + } - if (noOfSteps == 0) { - Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - - Document inputDoc = null; - if (input.getSubNode() != null) { - inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); - } - - for (int i = 0; i < noOfSteps; i++) { - Element xpathElement =XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2,i); - XPath2FilterContainer xpathContainer = - XPath2FilterContainer.newInstance(xpathElement, - input.getSourceURI()); - - - NodeList subtreeRoots = xPathFuncHereAPI.selectNodeList(inputDoc, - xpathContainer.getXPathFilterTextNode(), - CachedXPathFuncHereAPI.getStrFromNode(xpathContainer.getXPathFilterTextNode()), - xpathContainer.getElement()); - if (xpathContainer.isIntersect()) { - intersectNodes.add(subtreeRoots); - } else if (xpathContainer.isSubtract()) { - substractNodes.add(subtreeRoots); - } else if (xpathContainer.isUnion()) { - unionNodes.add(subtreeRoots); - } - } - - - input.addNodeFilter(new XPath2NodeFilter(unionNodes, substractNodes, - intersectNodes)); - input.setNodeSet(true); - return input; - } catch (TransformerException ex) { - throw new TransformationException("empty", ex); - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } catch (CanonicalizationException ex) { - throw new TransformationException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new TransformationException("empty", ex); - } catch (XMLSecurityException ex) { - throw new TransformationException("empty", ex); - } catch (SAXException ex) { - throw new TransformationException("empty", ex); - } catch (IOException ex) { - throw new TransformationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new TransformationException("empty", ex); - } - } + input.addNodeFilter( + new XPath2NodeFilter(unionNodes, subtractNodes, intersectNodes) + ); + input.setNodeSet(true); + return input; + } catch (TransformerException ex) { + throw new TransformationException("empty", ex); + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } catch (CanonicalizationException ex) { + throw new TransformationException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new TransformationException("empty", ex); + } catch (XMLSecurityException ex) { + throw new TransformationException("empty", ex); + } catch (SAXException ex) { + throw new TransformationException("empty", ex); + } catch (IOException ex) { + throw new TransformationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new TransformationException("empty", ex); + } + } } class XPath2NodeFilter implements NodeFilter { - boolean hasUnionFilter; - boolean hasSubstractFilter; - boolean hasIntersectFilter; - XPath2NodeFilter(List unionNodes, List substractNodes, - List intersectNodes) { - hasUnionFilter=!unionNodes.isEmpty(); - this.unionNodes=convertNodeListToSet(unionNodes); - hasSubstractFilter=!substractNodes.isEmpty(); - this.substractNodes=convertNodeListToSet(substractNodes); - hasIntersectFilter=!intersectNodes.isEmpty(); - this.intersectNodes=convertNodeListToSet(intersectNodes); + + boolean hasUnionFilter; + boolean hasSubtractFilter; + boolean hasIntersectFilter; + Set unionNodes; + Set subtractNodes; + Set intersectNodes; + int inSubtract = -1; + int inIntersect = -1; + int inUnion = -1; + + XPath2NodeFilter(List unionNodes, List subtractNodes, + List intersectNodes) { + hasUnionFilter = !unionNodes.isEmpty(); + this.unionNodes = convertNodeListToSet(unionNodes); + hasSubtractFilter = !subtractNodes.isEmpty(); + this.subtractNodes = convertNodeListToSet(subtractNodes); + hasIntersectFilter = !intersectNodes.isEmpty(); + this.intersectNodes = convertNodeListToSet(intersectNodes); + } + + /** + * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) + */ + public int isNodeInclude(Node currentNode) { + int result = 1; + + if (hasSubtractFilter && rooted(currentNode, subtractNodes)) { + result = -1; + } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { + result = 0; } - Set unionNodes; - Set substractNodes; - Set intersectNodes; + //TODO OPTIMIZE + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if (rooted(currentNode, unionNodes)) { + return 1; + } + result = 0; + } + return result; + } - /** - * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) - */ - public int isNodeInclude(Node currentNode) { - int result=1; + public int isNodeIncludeDO(Node n, int level) { + int result = 1; + if (hasSubtractFilter) { + if ((inSubtract == -1) || (level <= inSubtract)) { + if (inList(n, subtractNodes)) { + inSubtract = level; + } else { + inSubtract = -1; + } + } + if (inSubtract != -1){ + result = -1; + } + } + if (result != -1 && hasIntersectFilter + && ((inIntersect == -1) || (level <= inIntersect))) { + if (!inList(n, intersectNodes)) { + inIntersect = -1; + result = 0; + } else { + inIntersect = level; + } + } - if (hasSubstractFilter && rooted(currentNode, substractNodes)) { - result = -1; - } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { - result = 0; - } + if (level <= inUnion) { + inUnion = -1; + } + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if ((inUnion == -1) && inList(n, unionNodes)) { + inUnion = level; + } + if (inUnion != -1) { + return 1; + } + result=0; + } - //TODO OPTIMIZE - if (result==1) - return 1; - if (hasUnionFilter) { - if (rooted(currentNode, unionNodes)) { - return 1; - } - result=0; - } - return result; + return result; + } - } - int inSubstract=-1; - int inIntersect=-1; - int inUnion=-1; - public int isNodeIncludeDO(Node n, int level) { - int result=1; - if (hasSubstractFilter) { - if ((inSubstract==-1) || (level<=inSubstract)) { - if (inList(n, substractNodes)) { - inSubstract=level; - } else { - inSubstract=-1; - } - } - if (inSubstract!=-1){ - result=-1; - } - } - if (result!=-1){ - if (hasIntersectFilter) { - if ((inIntersect==-1) || (level<=inIntersect)) { - if (!inList(n, intersectNodes)) { - inIntersect=-1; - result=0; - } else { - inIntersect=level; - } - } - } - } + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean rooted(Node currentNode, Set nodeList) { + if (nodeList.isEmpty()) { + return false; + } + if (nodeList.contains(currentNode)) { + return true; + } + for (Node rootNode : nodeList) { + if (XMLUtils.isDescendantOrSelf(rootNode, currentNode)) { + return true; + } + } + return false; + } - if (level<=inUnion) - inUnion=-1; - if (result==1) - return 1; - if (hasUnionFilter) { - if ((inUnion==-1) && inList(n, unionNodes)) { - inUnion=level; - } - if (inUnion!=-1) - return 1; - result=0; - } - - return result; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean rooted(Node currentNode, Set nodeList ) { - if (nodeList.isEmpty()) { - return false; - } - if (nodeList.contains(currentNode)) { - return true; - } - - for(Node rootNode : nodeList) { - if (XMLUtils.isDescendantOrSelf(rootNode,currentNode)) { - return true; - } - } - return false; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean inList(Node currentNode, Set nodeList ) { - return nodeList.contains(currentNode); - } - - private static Set convertNodeListToSet(List l){ - Set result=new HashSet(); + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean inList(Node currentNode, Set nodeList) { + return nodeList.contains(currentNode); + } + private static Set convertNodeListToSet(List l) { + Set result = new HashSet(); for (NodeList rootNodes : l) { - int length = rootNodes.getLength(); - for (int i = 0; i < length; i++) { - Node rootNode = rootNodes.item(i); - result.add(rootNode); - } + int length = rootNodes.getLength(); + + for (int i = 0; i < length; i++) { + Node rootNode = rootNodes.item(i); + result.add(rootNode); + } } return result; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java index 71ba9604d1c..e2cae9b0237 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java @@ -2,26 +2,27 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - +import java.io.OutputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -29,8 +30,6 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; - - /** * Class TransformXPointer * @@ -38,30 +37,29 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformXPointer extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPOINTER; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPOINTER; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @throws TransformationException - * - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { - Object exArgs[] = { implementedTransformURI }; + Object exArgs[] = { implementedTransformURI }; - throw new TransformationException( - "signature.Transform.NotYetImplemented", exArgs); - } + throw new TransformationException("signature.Transform.NotYetImplemented", exArgs); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java index 12c8f636ca4..bf9adf5096e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -24,7 +26,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.lang.reflect.Method; import javax.xml.XMLConstants; import javax.xml.transform.Source; @@ -55,132 +56,112 @@ import org.w3c.dom.Element; */ public class TransformXSLT extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XSLT; - //J- - static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; - static final String defaultXSLTSpecNSprefix = "xslt"; - static final String XSLTSTYLESHEET = "stylesheet"; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XSLT; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - TransformXSLT.class.getName()); + static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; + static final String defaultXSLTSpecNSprefix = "xslt"; + static final String XSLTSTYLESHEET = "stylesheet"; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(TransformXSLT.class.getName()); - /** - * Method enginePerformTransform - * - * @param input the input for this transform - * @return the result of this Transform - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject) - throws IOException, - TransformationException { - try { - Element transformElement = _transformObject.getElement(); + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream baos, Transform transformObject + ) throws IOException, TransformationException { + try { + Element transformElement = transformObject.getElement(); - Element _xsltElement = - XMLUtils.selectNode(transformElement.getFirstChild(), - XSLTSpecNS,"stylesheet", 0); + Element xsltElement = + XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0); - if (_xsltElement == null) { - Object exArgs[] = { "xslt:stylesheet", "Transform" }; + if (xsltElement == null) { + Object exArgs[] = { "xslt:stylesheet", "Transform" }; - throw new TransformationException("xml.WrongContent", exArgs); - } + throw new TransformationException("xml.WrongContent", exArgs); + } - TransformerFactory tFactory = TransformerFactory.newInstance(); + TransformerFactory tFactory = TransformerFactory.newInstance(); + // Process XSLT stylesheets in a secure manner + tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - // Process XSLT stylesheets in a secure manner - tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - /* - * This transform requires an octet stream as input. If the actual - * input is an XPath node-set, then the signature application should - * attempt to convert it to octets (apply Canonical XML]) as described - * in the Reference Processing Model (section 4.3.3.2). - */ - Source xmlSource = - new StreamSource(new ByteArrayInputStream(input.getBytes())); - Source stylesheet; + /* + * This transform requires an octet stream as input. If the actual + * input is an XPath node-set, then the signature application should + * attempt to convert it to octets (apply Canonical XML]) as described + * in the Reference Processing Model (section 4.3.3.2). + */ + Source xmlSource = + new StreamSource(new ByteArrayInputStream(input.getBytes())); + Source stylesheet; - /* - * This complicated transformation of the stylesheet itself is necessary - * because of the need to get the pure style sheet. If we simply say - * Source stylesheet = new DOMSource(this._xsltElement); - * whereby this._xsltElement is not the rootElement of the Document, - * this causes problems; - * so we convert the stylesheet to byte[] and use this as input stream - */ - { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Transformer transformer = tFactory.newTransformer(); - DOMSource source = new DOMSource(_xsltElement); - StreamResult result = new StreamResult(os); + /* + * This complicated transformation of the stylesheet itself is necessary + * because of the need to get the pure style sheet. If we simply say + * Source stylesheet = new DOMSource(this.xsltElement); + * whereby this.xsltElement is not the rootElement of the Document, + * this causes problems; + * so we convert the stylesheet to byte[] and use this as input stream + */ + { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Transformer transformer = tFactory.newTransformer(); + DOMSource source = new DOMSource(xsltElement); + StreamResult result = new StreamResult(os); - transformer.transform(source, result); + transformer.transform(source, result); - stylesheet = - new StreamSource(new ByteArrayInputStream(os.toByteArray())); - } + stylesheet = + new StreamSource(new ByteArrayInputStream(os.toByteArray())); + } - Transformer transformer = tFactory.newTransformer(stylesheet); + Transformer transformer = tFactory.newTransformer(stylesheet); - // Force Xalan to use \n as line separator on all OSes. This - // avoids OS specific signature validation failures due to line - // separator differences in the transformed output. Unfortunately, - // this is not a standard JAXP property so will not work with non-Xalan - // implementations. - try { - transformer.setOutputProperty - ("{http://xml.apache.org/xalan}line-separator", "\n"); - } catch (Exception e) { - log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " - + e.getMessage()); - } + // Force Xalan to use \n as line separator on all OSes. This + // avoids OS specific signature validation failures due to line + // separator differences in the transformed output. Unfortunately, + // this is not a standard JAXP property so will not work with non-Xalan + // implementations. + try { + transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n"); + } catch (Exception e) { + log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " + e.getMessage()); + } + + if (baos == null) { + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + StreamResult outputTarget = new StreamResult(baos1); + transformer.transform(xmlSource, outputTarget); + return new XMLSignatureInput(baos1.toByteArray()); + } + StreamResult outputTarget = new StreamResult(baos); - if (baos==null) { - ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); - StreamResult outputTarget = new StreamResult(baos1); transformer.transform(xmlSource, outputTarget); - return new XMLSignatureInput(baos1.toByteArray()); - } - StreamResult outputTarget = new StreamResult(baos); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(baos); + return output; + } catch (XMLSecurityException ex) { + Object exArgs[] = { ex.getMessage() }; - transformer.transform(xmlSource, outputTarget); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(baos); - return output; - } catch (XMLSecurityException ex) { - Object exArgs[] = { ex.getMessage() }; + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerConfigurationException ex) { + Object exArgs[] = { ex.getMessage() }; - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerConfigurationException ex) { - Object exArgs[] = { ex.getMessage() }; + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerException ex) { + Object exArgs[] = { ex.getMessage() }; - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerException ex) { - Object exArgs[] = { ex.getMessage() }; - - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } - } + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java index f615881bade..2b6f5da2f16 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java @@ -2,30 +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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - - -import java.util.Iterator; import java.util.Set; import java.util.SortedSet; -import java.util.StringTokenizer; import java.util.TreeSet; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -34,7 +32,6 @@ import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This Object serves as Content for the ds:Transforms for exclusive * Canonicalization. @@ -44,136 +41,130 @@ import org.w3c.dom.Element; * * @author Christian Geuer-Pollmann */ -public class InclusiveNamespaces extends ElementProxy - implements TransformParam { +public class InclusiveNamespaces extends ElementProxy implements TransformParam { - /** Field _TAG_EC_INCLUSIVENAMESPACES */ - public static final String _TAG_EC_INCLUSIVENAMESPACES = - "InclusiveNamespaces"; + /** Field _TAG_EC_INCLUSIVENAMESPACES */ + public static final String _TAG_EC_INCLUSIVENAMESPACES = + "InclusiveNamespaces"; - /** Field _ATT_EC_PREFIXLIST */ - public static final String _ATT_EC_PREFIXLIST = "PrefixList"; + /** Field _ATT_EC_PREFIXLIST */ + public static final String _ATT_EC_PREFIXLIST = "PrefixList"; - /** Field ExclusiveCanonicalizationNamespace */ - public static final String ExclusiveCanonicalizationNamespace = - "http://www.w3.org/2001/10/xml-exc-c14n#"; + /** Field ExclusiveCanonicalizationNamespace */ + public static final String ExclusiveCanonicalizationNamespace = + "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** - * Constructor XPathContainer - * - * @param doc - * @param prefixList - */ - public InclusiveNamespaces(Document doc, String prefixList) { - this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); - } + /** + * Constructor XPathContainer + * + * @param doc + * @param prefixList + */ + public InclusiveNamespaces(Document doc, String prefixList) { + this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); + } - /** - * Constructor InclusiveNamespaces - * - * @param doc - * @param prefixes - */ - public InclusiveNamespaces(Document doc, Set prefixes) { + /** + * Constructor InclusiveNamespaces + * + * @param doc + * @param prefixes + */ + public InclusiveNamespaces(Document doc, Set prefixes) { + super(doc); - super(doc); + SortedSet prefixList = null; + if (prefixes instanceof SortedSet) { + prefixList = (SortedSet)prefixes; + } else { + prefixList = new TreeSet(prefixes); + } - StringBuffer sb = new StringBuffer(); - SortedSet prefixList = new TreeSet(prefixes); + StringBuilder sb = new StringBuilder(); + for (String prefix : prefixList) { + if (prefix.equals("xmlns")) { + sb.append("#default "); + } else { + sb.append(prefix + " "); + } + } + this.constructionElement.setAttributeNS( + null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim()); + } + /** + * Constructor InclusiveNamespaces + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public InclusiveNamespaces(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - for (String prefix : prefixList) { - if (prefix.equals("xmlns")) { - sb.append("#default "); - } else { - sb.append(prefix + " "); - } - } + /** + * Method getInclusiveNamespaces + * + * @return The Inclusive Namespace string + */ + public String getInclusiveNamespaces() { + return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); + } - this._constructionElement - .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST, - sb.toString().trim()); - } + /** + * Decodes the inclusiveNamespaces String and returns all + * selected namespace prefixes as a Set. The #default + * namespace token is represented as an empty namespace prefix + * ("xmlns"). + *
    + * The String inclusiveNamespaces=" xenc ds #default" + * is returned as a Set containing the following Strings: + *
      + *
    • xmlns
    • + *
    • xenc
    • + *
    • ds
    • + *
    + * + * @param inclusiveNamespaces + * @return A set to string + */ + public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + SortedSet prefixes = new TreeSet(); - /** - * Method getInclusiveNamespaces - * - * @return The Inclusive Namespace string - */ - public String getInclusiveNamespaces() { - return this._constructionElement - .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); - } + if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) { + return prefixes; + } - /** - * Constructor InclusiveNamespaces - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public InclusiveNamespaces(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + String[] tokens = inclusiveNamespaces.split("\\s"); + for (String prefix : tokens) { + if (prefix.equals("#default")) { + prefixes.add("xmlns"); + } else { + prefixes.add(prefix); + } + } - /** - * Decodes the inclusiveNamespaces String and returns all - * selected namespace prefixes as a Set. The #default - * namespace token is represented as an empty namespace prefix - * ("xmlns"). - *
    - * The String inclusiveNamespaces=" xenc ds #default" - * is returned as a Set containing the following Strings: - *
      - *
    • xmlns
    • - *
    • xenc
    • - *
    • ds
    • - *
    - * - * @param inclusiveNamespaces - * @return A set to string - */ - public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + return prefixes; + } - SortedSet prefixes = new TreeSet(); + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public String getBaseNamespace() { + return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; + } - if ((inclusiveNamespaces == null) - || (inclusiveNamespaces.length() == 0)) { - return prefixes; - } - - StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n"); - - while (st.hasMoreTokens()) { - String prefix = st.nextToken(); - - if (prefix.equals("#default")) { - prefixes.add("xmlns" ); - } else { - prefixes.add( prefix); - } - } - - return prefixes; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public String getBaseNamespace() { - return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java index 366f31acf80..19de51976cf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -32,284 +32,261 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; - /** Field INTERSECT */ - public static final String INTERSECT = - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; + /** Field INTERSECT */ + public static final String INTERSECT = + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; - /** Field SUBTRACT */ - public static final String SUBTRACT = - XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; + /** Field SUBTRACT */ + public static final String SUBTRACT = + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; - /** Field UNION */ - public static final String UNION = - XPath2FilterContainer._ATT_FILTER_VALUE_UNION; + /** Field UNION */ + public static final String UNION = + XPath2FilterContainer._ATT_FILTER_VALUE_UNION; - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/06/xmldsig-filter2"; + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/06/xmldsig-filter2"; - /** - * Constructor XPath2FilterContainer - * - */ - private XPath2FilterContainer() { + /** + * Constructor XPath2FilterContainer + * + */ + private XPath2FilterContainer() { + // no instantiation + } - // no instantiation - } + /** + * Constructor XPath2FilterContainer + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) { + super(doc); - /** - * Constructor XPath2FilterContainer - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer(Document doc, String xpath2filter, - String filterType) { + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer._ATT_FILTER, filterType); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } - super(doc); + /** + * Constructor XPath2FilterContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException { - this._constructionElement - .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - } + super(element, BaseURI); - /** - * Constructor XPath2FilterContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer(Element element, String BaseURI) - throws XMLSecurityException { + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER); - super(element, BaseURI); + if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; - String filterStr = this._constructionElement.getAttributeNS(null, - XPath2FilterContainer._ATT_FILTER); + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - if (!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; + /** + * Creates a new XPath2FilterContainer with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * Creates a new XPath2FilterContainer with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceSubtract(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - /** - * Creates a new XPath2FilterContainer with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceIntersect(Document doc, - String xpath2filter) { + /** + * Creates a new XPath2FilterContainer with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the filter + */ + public static XPath2FilterContainer newInstanceUnion(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT); - } + /** + * Method newInstances + * + * @param doc + * @param params + * @return the nodelist with the data + */ + public static NodeList newInstances(Document doc, String[][] params) { + HelperNodeList nl = new HelperNodeList(); - /** - * Creates a new XPath2FilterContainer with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceSubtract(Document doc, - String xpath2filter) { + XMLUtils.addReturnToElement(doc, nl); - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT); - } + for (int i = 0; i < params.length; i++) { + String type = params[i][0]; + String xpath = params[i][1]; - /** - * Creates a new XPath2FilterContainer with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the filter - */ - public static XPath2FilterContainer newInstanceUnion(Document doc, - String xpath2filter) { + if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))){ + throw new IllegalArgumentException("The type(" + i + ")=\"" + type + + "\" is illegal"); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION); - } + XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); - /** - * Method newInstances - * - * @param doc - * @param params - * @return the nodelist with the data - */ - public static NodeList newInstances(Document doc, String[][] params) { + nl.appendChild(c.getElement()); + XMLUtils.addReturnToElement(doc, nl); + } - HelperNodeList nl = new HelperNodeList(); + return nl; + } - XMLUtils.addReturnToElement(doc, nl); + /** + * Creates a XPath2FilterContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the filter + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer(element, BaseURI); + } - for (int i = 0; i < params.length; i++) { - String type = params[i][0]; - String xpath = params[i][1]; + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - if (!(type.equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION))) { - throw new IllegalArgumentException("The type(" + i + ")=\"" + type - + "\" is illegal"); - } + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - nl.appendChild(c.getElement()); - XMLUtils.addReturnToElement(doc, nl); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - return nl; - } + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { - /** - * Creates a XPath2FilterContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the filter - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer(element, BaseURI); - } + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); - } + return null; + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + /** + * Method getBaseLocalName + * + * @return the XPATH2 tag + */ + public final String getBaseLocalName() { + return XPath2FilterContainer._TAG_XPATH2; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** - * Method getBaseLocalName - * - * @return the XPATH2 tag - */ - public final String getBaseLocalName() { - return XPath2FilterContainer._TAG_XPATH2; - } - - /** - * Method getBaseNamespace - * - * @return XPATH2 tag namespace - */ - public final String getBaseNamespace() { - return XPath2FilterContainer.XPathFilter2NS; - } + /** + * Method getBaseNamespace + * + * @return XPATH2 tag namespace + */ + public final String getBaseNamespace() { + return XPath2FilterContainer.XPathFilter2NS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java index 25008eed743..2eed2cb1fdf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -31,237 +31,222 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer04 extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer04 extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/04/xmldsig-filter2"; - /** - * Constructor XPath2FilterContainer04 - * - */ - private XPath2FilterContainer04() { + /** + * Constructor XPath2FilterContainer04 + * + */ + private XPath2FilterContainer04() { - // no instantiation - } + // no instantiation + } - /** - * Constructor XPath2FilterContainer04 - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer04(Document doc, String xpath2filter, - String filterType) { + /** + * Constructor XPath2FilterContainer04 + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) { + super(doc); - super(doc); + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER, filterType); - this._constructionElement.setAttributeNS(null, XPath2FilterContainer04._ATT_FILTER, - filterType); + if ((xpath2filter.length() > 2) + && (!Character.isWhitespace(xpath2filter.charAt(0)))) { + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + XMLUtils.addReturnToElement(this.constructionElement); + } else { + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } + } - if ((xpath2filter.length() > 2) - && (!Character.isWhitespace(xpath2filter.charAt(0)))) { - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - XMLUtils.addReturnToElement(this._constructionElement); - } else { - this._constructionElement - .appendChild(doc.createTextNode(xpath2filter)); - } - } + /** + * Constructor XPath2FilterContainer04 + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer04(Element element, String BaseURI) + throws XMLSecurityException { - /** - * Constructor XPath2FilterContainer04 - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer04(Element element, String BaseURI) - throws XMLSecurityException { + super(element, BaseURI); - super(element, BaseURI); + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); - String filterStr = - this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); + if (!filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, + XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; - if (!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, - XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * Creates a new XPath2FilterContainer04 with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceIntersect(Document doc, - String xpath2filter) { + /** + * Creates a new XPath2FilterContainer04 with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceSubtract( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT); - } + /** + * Creates a new XPath2FilterContainer04 with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceUnion( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceSubtract(Document doc, - String xpath2filter) { + /** + * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the instance + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer04 newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer04(element, BaseURI); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT); - } + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceUnion(Document doc, - String xpath2filter) { + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_UNION); - } + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } - /** - * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the instance - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer04 newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer04(element, BaseURI); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); - } + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + return null; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); - } + /** @inheritDoc */ + public final String getBaseLocalName() { + return XPath2FilterContainer04._TAG_XPATH2; + } - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** @inheritDoc */ - public final String getBaseLocalName() { - return XPath2FilterContainer04._TAG_XPATH2; - } - - /** @inheritDoc */ - public final String getBaseNamespace() { - return XPath2FilterContainer04.XPathFilter2NS; - } + /** @inheritDoc */ + public final String getBaseNamespace() { + return XPath2FilterContainer04.XPathFilter2NS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java index 717889d576f..74f2ff1f50d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java @@ -2,26 +2,27 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; @@ -29,7 +30,6 @@ import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; - /** * This Object serves both as namespace prefix resolver and as container for * the ds:XPath Element. It implements the {@link org.w3c.dom.Element} interface @@ -39,45 +39,44 @@ import org.w3c.dom.Text; */ public class XPathContainer extends SignatureElementProxy implements TransformParam { - /** - * Constructor XPathContainer - * - * @param doc - */ - public XPathContainer(Document doc) { - super(doc); - } + /** + * Constructor XPathContainer + * + * @param doc + */ + public XPathContainer(Document doc) { + super(doc); + } - /** - * Sets the TEXT value of the ds:XPath Element. - * - * @param xpath - */ - public void setXPath(String xpath) { + /** + * Sets the TEXT value of the ds:XPath Element. + * + * @param xpath + */ + public void setXPath(String xpath) { + if (this.constructionElement.getChildNodes() != null) { + NodeList nl = this.constructionElement.getChildNodes(); - if (this._constructionElement.getChildNodes() != null) { - NodeList nl = this._constructionElement.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + this.constructionElement.removeChild(nl.item(i)); + } + } - for (int i = 0; i < nl.getLength(); i++) { - this._constructionElement.removeChild(nl.item(i)); - } - } + Text xpathText = this.doc.createTextNode(xpath); + this.constructionElement.appendChild(xpathText); + } - Text xpathText = this._doc.createTextNode(xpath); - this._constructionElement.appendChild(xpathText); - } + /** + * Returns the TEXT value of the ds:XPath Element. + * + * @return the TEXT value of the ds:XPath Element. + */ + public String getXPath() { + return this.getTextFromTextChild(); + } - /** - * Returns the TEXT value of the ds:XPath Element. - * - * @return the TEXT value of the ds:XPath Element. - */ - public String getXPath() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_XPATH; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_XPATH; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java index 86199d7ab63..0bb4f7e5f09 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java @@ -2,320 +2,315 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; -import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Implements the parameters for a custom Transform which has a better performance - * thatn the xfilter2. + * than the xfilter2. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XPathFilterCHGPContainer extends ElementProxy - implements TransformParam { +public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; + public static final String TRANSFORM_XPATHFILTERCHGP = + "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _TAG_EXCLUDE = "Exclude"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; - /** Field _TAG_XPATHCHGP */ - public static final String _TAG_XPATHCHGP = "XPathAlternative"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _TAG_EXCLUDE = "Exclude"; - /** Field _ATT_INCLUDESLASH */ - public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; + /** Field _TAG_XPATHCHGP */ + public static final String _TAG_XPATHCHGP = "XPathAlternative"; - /** Field IncludeSlash */ - public static final boolean IncludeSlash = true; + /** Field _ATT_INCLUDESLASH */ + public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; - /** Field ExcludeSlash */ - public static final boolean ExcludeSlash = false; + /** Field IncludeSlash */ + public static final boolean IncludeSlash = true; - /** - * Constructor XPathFilterCHGPContainer - * - */ - private XPathFilterCHGPContainer() { + /** Field ExcludeSlash */ + public static final boolean ExcludeSlash = false; - // no instantiation - } + /** + * Constructor XPathFilterCHGPContainer + * + */ + private XPathFilterCHGPContainer() { + // no instantiation + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - */ - private XPathFilterCHGPContainer(Document doc, boolean includeSlashPolicy, - String includeButSearch, - String excludeButSearch, String exclude) { + /** + * Constructor XPathFilterCHGPContainer + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + */ + private XPathFilterCHGPContainer( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + super(doc); - super(doc); + if (includeSlashPolicy) { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true" + ); + } else { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false" + ); + } - if (includeSlashPolicy) { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"); - } else { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"); - } + if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) { + Element includeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH + ); - if ((includeButSearch != null) - && (includeButSearch.trim().length() > 0)) { - Element includeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_INCLUDE_BUT_SEARCH); + includeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(includeButSearch)) + ); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(includeButSearchElem); + } - includeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(includeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(includeButSearchElem); - } + if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) { + Element excludeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH + ); - if ((excludeButSearch != null) - && (excludeButSearch.trim().length() > 0)) { - Element excludeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_EXCLUDE_BUT_SEARCH); + excludeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(excludeButSearch))); - excludeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(excludeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeButSearchElem); - } + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeButSearchElem); + } - if ((exclude != null) && (exclude.trim().length() > 0)) { - Element excludeElem = ElementProxy.createElementForFamily(doc, - this.getBaseNamespace(), - XPathFilterCHGPContainer._TAG_EXCLUDE); + if ((exclude != null) && (exclude.trim().length() > 0)) { + Element excludeElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE); - excludeElem - .appendChild(this._doc.createTextNode(indentXPathText(exclude))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeElem); - } + excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude))); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeElem); + } - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method indentXPathText - * - * @param xp - * @return the string with enters - */ - static String indentXPathText(String xp) { + /** + * Method indentXPathText + * + * @param xp + * @return the string with enters + */ + static String indentXPathText(String xp) { + if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { + return "\n" + xp + "\n"; + } + return xp; + } - if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { - return "\n" + xp + "\n"; - } - return xp; + /** + * Constructor XPathFilterCHGPContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPathFilterCHGPContainer(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - } + /** + * Creates a new XPathFilterCHGPContainer; needed for generation. + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + * @return the created object + */ + public static XPathFilterCHGPContainer getInstance( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + return new XPathFilterCHGPContainer( + doc, includeSlashPolicy, includeButSearch, excludeButSearch, exclude); + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPathFilterCHGPContainer(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * + * @throws XMLSecurityException + * @return the created object. + */ + public static XPathFilterCHGPContainer getInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPathFilterCHGPContainer(element, BaseURI); + } - /** - * Creates a new XPathFilterCHGPContainer; needed for generation. - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - * @return the created object - */ - public static XPathFilterCHGPContainer getInstance(Document doc, - boolean includeSlashPolicy, String includeButSearch, - String excludeButSearch, String exclude) { + /** + * Method getXStr + * + * @param type + * @return The Xstr + */ + private String getXStr(String type) { + if (this.length(this.getBaseNamespace(), type) != 1) { + return ""; + } - return new XPathFilterCHGPContainer(doc, includeSlashPolicy, - includeButSearch, excludeButSearch, - exclude); - } + Element xElem = + XMLUtils.selectNode( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); - /** - * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * - * @throws XMLSecurityException - * @return the created object. - */ - public static XPathFilterCHGPContainer getInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPathFilterCHGPContainer(element, BaseURI); - } + return XMLUtils.getFullTextChildrenFromElement(xElem); + } - /** - * Method getXStr - * - * @param type - * @return The Xstr - */ - private String getXStr(String type) { + /** + * Method getIncludeButSearch + * + * @return the string + */ + public String getIncludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return ""; - } + /** + * Method getExcludeButSearch + * + * @return the string + */ + public String getExcludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); + /** + * Method getExclude + * + * @return the string + */ + public String getExclude() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - return XMLUtils.getFullTextChildrenFromElement(xElem); - } + /** + * Method getIncludeSlashPolicy + * + * @return the string + */ + public boolean getIncludeSlashPolicy() { + return this.constructionElement.getAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true"); + } - /** - * Method getIncludeButSearch - * - * @return the string - */ - public String getIncludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } + /** + * Returns the first Text node which contains information from the XPath + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @param type + * @return the first Text node which contains information from the XPath 2 Filter String + */ + private Node getHereContextNode(String type) { - /** - * Method getExcludeButSearch - * - * @return the string - */ - public String getExcludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } + if (this.length(this.getBaseNamespace(), type) != 1) { + return null; + } - /** - * Method getExclude - * - * @return the string - */ - public String getExclude() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); - } + return XMLUtils.selectNodeText( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); + } - /** - * Method getIncludeSlashPolicy - * - * @return the string - */ - public boolean getIncludeSlashPolicy() { + /** + * Method getHereContextNodeIncludeButSearch + * + * @return the string + */ + public Node getHereContextNodeIncludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - return this._constructionElement - .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH) - .equals("true"); - } + /** + * Method getHereContextNodeExcludeButSearch + * + * @return the string + */ + public Node getHereContextNodeExcludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - /** - * Returns the first Text node which contains information from the XPath - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @param type - * @return the first Text node which contains information from the XPath 2 Filter String - */ - private Node getHereContextNode(String type) { + /** + * Method getHereContextNodeExclude + * + * @return the string + */ + public Node getHereContextNodeExclude() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return null; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public final String getBaseLocalName() { + return XPathFilterCHGPContainer._TAG_XPATHCHGP; + } - return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); - } - - /** - * Method getHereContextNodeIncludeButSearch - * - * @return the string - */ - public Node getHereContextNodeIncludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExcludeButSearch - * - * @return the string - */ - public Node getHereContextNodeExcludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExclude - * - * @return the string - */ - public Node getHereContextNodeExclude() { - return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public final String getBaseLocalName() { - return XPathFilterCHGPContainer._TAG_XPATHCHGP; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public final String getBaseNamespace() { - return Transforms.TRANSFORM_XPATHFILTERCHGP; - } + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public final String getBaseNamespace() { + return TRANSFORM_XPATHFILTERCHGP; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java index 9e9c7de8b0f..db1f49eaee4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -32,762 +34,765 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Implementation of MIME's Base64 encoding and decoding conversions. * Optimized code. (raw version taken from oreilly.jonathan.util, - * and currently com.sun.org.apache.xerces.internal.ds.util.Base64) + * and currently org.apache.xerces.ds.util.Base64) * * @author Raul Benito(Of the xerces copy, and little adaptations). * @author Anli Shundi * @author Christian Geuer-Pollmann - * @see RFC 2045 + * @see RFC 2045 * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */ public class Base64 { - - /** Field BASE64DEFAULTLENGTH */ - public static final int BASE64DEFAULTLENGTH = 76; - - private Base64() { - // we don't allow instantiation - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - static final byte[] getBytes(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string - - if ((big.bitLength() % 8) == 0) { // correct values - startSrc = 1; // skip sign bit - - bigLen--; // valid length of the string - } - - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Encode in Base64 the given {@link BigInteger}. - * - * @param big - * @return String with Base64 encoding - */ - public static final String encode(BigInteger big) { - return encode(getBytes(big, big.bitLength())); - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - public static final byte[] encode(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string - - if ((big.bitLength() % 8) == 0) { // correct values - startSrc = 1; // skip sign bit - - bigLen--; // valid length of the string - } - - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Method decodeBigIntegerFromElement - * - * @param element - * @return the biginter obtained from the node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(element)); - } - - /** - * Method decodeBigIntegerFromText - * - * @param text - * @return the biginter obtained from the text node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(text.getData())); - } - - /** - * This method takes an (empty) Element and a BigInteger and adds the - * base64 encoded BigInteger to the Element. - * - * @param element - * @param biginteger - */ - public static final void fillElementWithBigInteger(Element element, - BigInteger biginteger) { - - String encodedInt = encode(biginteger); - - if (encodedInt.length() > 76) { - encodedInt = "\n" + encodedInt + "\n"; - } - - Document doc = element.getOwnerDocument(); - Text text = doc.createTextNode(encodedInt); - - element.appendChild(text); - } - - /** - * Method decode - * - * Takes the Text children of the Element and interprets - * them as input for the Base64.decode() function. - * - * @param element - * @return the byte obtained of the decoding the element - * $todo$ not tested yet - * @throws Base64DecodingException - */ - public static final byte[] decode(Element element) throws Base64DecodingException { - - Node sibling = element.getFirstChild(); - StringBuffer sb = new StringBuffer(); - - while (sibling!=null) { - if (sibling.getNodeType() == Node.TEXT_NODE) { - Text t = (Text) sibling; - - sb.append(t.getData()); - } - sibling=sibling.getNextSibling(); - } - - return decode(sb.toString()); - } - - /** - * Method encodeToElement - * - * @param doc - * @param localName - * @param bytes - * @return an Element with the base64 encoded in the text. - * - */ - public static final Element encodeToElement(Document doc, String localName, - byte[] bytes) { - - Element el = XMLUtils.createElementInSignatureSpace(doc, localName); - Text text = doc.createTextNode(encode(bytes)); - - el.appendChild(text); - - return el; - } - - /** - * Method decode - * - * - * @param base64 - * @return the UTF bytes of the base64 - * @throws Base64DecodingException - * - */ - public final static byte[] decode(byte[] base64) throws Base64DecodingException { - return decodeInternal(base64, -1); - } - - - - /** - * Encode a byte array and fold lines at the standard 76th character unless - * ignore line breaks property is set. - * - * @param binaryData byte[] to be base64 encoded - * @return the String with encoded data - */ - public static final String encode(byte[] binaryData) { - return XMLUtils.ignoreLineBreaks() - ? encode(binaryData, Integer.MAX_VALUE) - : encode(binaryData, BASE64DEFAULTLENGTH); - } - - /** - * Base64 decode the lines from the reader and return an InputStream - * with the bytes. - * - * - * @param reader - * @return InputStream with the decoded bytes - * @exception IOException passes what the reader throws - * @throws IOException - * @throws Base64DecodingException - */ - public final static byte[] decode(BufferedReader reader) - throws IOException, Base64DecodingException { - - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - String line; - - while (null != (line = reader.readLine())) { - byte[] bytes = decode(line); - - baos.write(bytes); - } - - return baos.toByteArray(); - } - - static private final int BASELENGTH = 255; - static private final int LOOKUPLENGTH = 64; - static private final int TWENTYFOURBITGROUP = 24; - static private final int EIGHTBIT = 8; - static private final int SIXTEENBIT = 16; - static private final int FOURBYTE = 4; - static private final int SIGN = -128; - static private final char PAD = '='; - static final private byte [] base64Alphabet = new byte[BASELENGTH]; - static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; - - static { - - for (int i = 0; i= 'A'; i--) { - base64Alphabet[i] = (byte) (i-'A'); - } - for (int i = 'z'; i>= 'a'; i--) { - base64Alphabet[i] = (byte) ( i-'a' + 26); - } - - for (int i = '9'; i >= '0'; i--) { - base64Alphabet[i] = (byte) (i-'0' + 52); - } - - base64Alphabet['+'] = 62; - base64Alphabet['/'] = 63; - - for (int i = 0; i<=25; i++) - lookUpBase64Alphabet[i] = (char)('A'+i); - - for (int i = 26, j = 0; i<=51; i++, j++) - lookUpBase64Alphabet[i] = (char)('a'+ j); - - for (int i = 52, j = 0; i<=61; i++, j++) - lookUpBase64Alphabet[i] = (char)('0' + j); - lookUpBase64Alphabet[62] = '+'; - lookUpBase64Alphabet[63] = '/'; - - } - - protected static final boolean isWhiteSpace(byte octect) { - return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); - } - - protected static final boolean isPad(byte octect) { - return (octect == PAD); - } - - - /** - * Encodes hex octects into Base64 - * - * @param binaryData Array containing binaryData - * @return Encoded Base64 array - */ - /** - * Encode a byte array in Base64 format and return an optionally - * wrapped line. - * - * @param binaryData byte[] data to be encoded - * @param length int length of wrapped lines; No wrapping if less than 4. - * @return a String with encoded data - */ - public static final String encode(byte[] binaryData,int length) { - - if (length<4) { - length=Integer.MAX_VALUE; + /** Field BASE64DEFAULTLENGTH */ + public static final int BASE64DEFAULTLENGTH = 76; + + private static final int BASELENGTH = 255; + private static final int LOOKUPLENGTH = 64; + private static final int TWENTYFOURBITGROUP = 24; + private static final int EIGHTBIT = 8; + private static final int SIXTEENBIT = 16; + private static final int FOURBYTE = 4; + private static final int SIGN = -128; + private static final char PAD = '='; + private static final byte [] base64Alphabet = new byte[BASELENGTH]; + private static final char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; i++) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i>= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); } - if (binaryData == null) - return null; + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } - int lengthDataBits = binaryData.length*EIGHTBIT; - if (lengthDataBits == 0) { - return ""; - } + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; - int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; - int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; - int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets; - int quartesPerLine = length/4; - int numberLines = (numberQuartet-1)/quartesPerLine; - char encodedData[] = null; + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char)('A' + i); + } - encodedData = new char[numberQuartet*4+numberLines]; + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char)('a' + j); + } - byte k=0, l=0, b1=0,b2=0,b3=0; + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char)('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + } - int encodedIndex = 0; - int dataIndex = 0; - int i = 0; - - - for (int line = 0; line < numberLines; line++) { - for (int quartet = 0; quartet < 19; quartet++) { - b1 = binaryData[dataIndex++]; - b2 = binaryData[dataIndex++]; - b3 = binaryData[dataIndex++]; - - - l = (byte)(b2 & 0x0f); - k = (byte)(b1 & 0x03); - - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); - - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - - i++; - } - encodedData[encodedIndex++] = 0xa; - } - - for (; i>2):(byte)((b1)>>2^0xc0); - - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); - - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - } - - // form integral number of 6-bit groups - if (fewerThan24bits == EIGHTBIT) { - b1 = binaryData[dataIndex]; - k = (byte) ( b1 &0x03 ); - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ]; - encodedData[encodedIndex++] = PAD; - encodedData[encodedIndex++] = PAD; - } else if (fewerThan24bits == SIXTEENBIT) { - b1 = binaryData[dataIndex]; - b2 = binaryData[dataIndex +1 ]; - l = ( byte ) ( b2 &0x0f ); - k = ( byte ) ( b1 &0x03 ); - - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; - encodedData[encodedIndex++] = PAD; - } - - //encodedData[encodedIndex] = 0xa; - - return new String(encodedData); - } + private Base64() { + // we don't allow instantiation + } /** - * Decodes Base64 data into octects + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + static final byte[] getBytes(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values + startSrc = 1; // skip sign bit + + bigLen--; // valid length of the string + } + + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Encode in Base64 the given {@link BigInteger}. + * + * @param big + * @return String with Base64 encoding + */ + public static final String encode(BigInteger big) { + return encode(getBytes(big, big.bitLength())); + } + + /** + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + public static final byte[] encode(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values + startSrc = 1; // skip sign bit + + bigLen--; // valid length of the string + } + + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Method decodeBigIntegerFromElement + * + * @param element + * @return the biginteger obtained from the node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromElement(Element element) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(element)); + } + + /** + * Method decodeBigIntegerFromText + * + * @param text + * @return the biginter obtained from the text node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromText(Text text) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(text.getData())); + } + + /** + * This method takes an (empty) Element and a BigInteger and adds the + * base64 encoded BigInteger to the Element. + * + * @param element + * @param biginteger + */ + public static final void fillElementWithBigInteger(Element element, BigInteger biginteger) { + + String encodedInt = encode(biginteger); + + if (!XMLUtils.ignoreLineBreaks() && encodedInt.length() > BASE64DEFAULTLENGTH) { + encodedInt = "\n" + encodedInt + "\n"; + } + + Document doc = element.getOwnerDocument(); + Text text = doc.createTextNode(encodedInt); + + element.appendChild(text); + } + + /** + * Method decode + * + * Takes the Text children of the Element and interprets + * them as input for the Base64.decode() function. + * + * @param element + * @return the byte obtained of the decoding the element + * $todo$ not tested yet + * @throws Base64DecodingException + */ + public static final byte[] decode(Element element) throws Base64DecodingException { + + Node sibling = element.getFirstChild(); + StringBuffer sb = new StringBuffer(); + + while (sibling != null) { + if (sibling.getNodeType() == Node.TEXT_NODE) { + Text t = (Text) sibling; + + sb.append(t.getData()); + } + sibling = sibling.getNextSibling(); + } + + return decode(sb.toString()); + } + + /** + * Method encodeToElement + * + * @param doc + * @param localName + * @param bytes + * @return an Element with the base64 encoded in the text. + * + */ + public static final Element encodeToElement(Document doc, String localName, byte[] bytes) { + Element el = XMLUtils.createElementInSignatureSpace(doc, localName); + Text text = doc.createTextNode(encode(bytes)); + + el.appendChild(text); + + return el; + } + + /** + * Method decode + * + * @param base64 + * @return the UTF bytes of the base64 + * @throws Base64DecodingException + * + */ + public static final byte[] decode(byte[] base64) throws Base64DecodingException { + return decodeInternal(base64, -1); + } + + /** + * Encode a byte array and fold lines at the standard 76th character unless + * ignore line breaks property is set. + * + * @param binaryData byte[] to be base64 encoded + * @return the String with encoded data + */ + public static final String encode(byte[] binaryData) { + return XMLUtils.ignoreLineBreaks() + ? encode(binaryData, Integer.MAX_VALUE) + : encode(binaryData, BASE64DEFAULTLENGTH); + } + + /** + * Base64 decode the lines from the reader and return an InputStream + * with the bytes. + * + * @param reader + * @return InputStream with the decoded bytes + * @exception IOException passes what the reader throws + * @throws IOException + * @throws Base64DecodingException + */ + public static final byte[] decode(BufferedReader reader) + throws IOException, Base64DecodingException { + + byte[] retBytes = null; + UnsyncByteArrayOutputStream baos = null; + try { + baos = new UnsyncByteArrayOutputStream(); + String line; + + while (null != (line = reader.readLine())) { + byte[] bytes = decode(line); + baos.write(bytes); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); + } + + return retBytes; + } + + protected static final boolean isWhiteSpace(byte octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } + + protected static final boolean isPad(byte octect) { + return (octect == PAD); + } + + /** + * Encodes hex octets into Base64 + * + * @param binaryData Array containing binaryData + * @return Encoded Base64 array + */ + /** + * Encode a byte array in Base64 format and return an optionally + * wrapped line. + * + * @param binaryData byte[] data to be encoded + * @param length int length of wrapped lines; No wrapping if less than 4. + * @return a String with encoded data + */ + public static final String encode(byte[] binaryData,int length) { + if (length < 4) { + length = Integer.MAX_VALUE; + } + + if (binaryData == null) { + return null; + } + + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } + + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + int quartesPerLine = length / 4; + int numberLines = (numberQuartet - 1) / quartesPerLine; + char encodedData[] = null; + + encodedData = new char[numberQuartet * 4 + numberLines]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + int encodedIndex = 0; + int dataIndex = 0; + int i = 0; + + for (int line = 0; line < numberLines; line++) { + for (int quartet = 0; quartet < 19; quartet++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + + i++; + } + encodedData[encodedIndex++] = 0xa; + } + + for (; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } + + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 &0x03); + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2):(byte)((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex +1 ]; + l = ( byte ) (b2 & 0x0f); + k = ( byte ) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + + //encodedData[encodedIndex] = 0xa; + + return new String(encodedData); + } + + /** + * Decodes Base64 data into octets * * @param encoded String containing base64 encoded data * @return byte array containing the decoded data * @throws Base64DecodingException if there is a problem decoding the data */ - public final static byte[] decode(String encoded) throws Base64DecodingException { - - if (encoded == null) - return null; - byte []bytes=new byte[encoded.length()]; - int len=getBytesInternal(encoded, bytes); - return decodeInternal(bytes, len); + public static final byte[] decode(String encoded) throws Base64DecodingException { + if (encoded == null) { + return null; } + byte[] bytes = new byte[encoded.length()]; + int len = getBytesInternal(encoded, bytes); + return decodeInternal(bytes, len); + } - protected static final int getBytesInternal(String s,byte[] result) { - int length=s.length(); + protected static final int getBytesInternal(String s, byte[] result) { + int length = s.length(); - int newSize=0; + int newSize = 0; for (int i = 0; i < length; i++) { - byte dataS=(byte)s.charAt(i); - if (!isWhiteSpace(dataS)) + byte dataS = (byte)s.charAt(i); + if (!isWhiteSpace(dataS)) { result[newSize++] = dataS; + } } return newSize; - } - protected final static byte[] decodeInternal(byte[] base64Data, int len) throws Base64DecodingException { - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four - } + protected static final byte[] decodeInternal(byte[] base64Data, int len) + throws Base64DecodingException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int numberQuadruple = (len/FOURBYTE ); + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - if (numberQuadruple == 0) - return new byte[0]; + int numberQuadruple = (len / FOURBYTE); - byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + if (numberQuadruple == 0) { + return new byte[0]; + } + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - int i = 0; - int encodedIndex = 0; - int dataIndex = 0; + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; - //decodedData = new byte[ (numberQuadruple)*3]; - dataIndex=(numberQuadruple-1)*4; - encodedIndex=(numberQuadruple-1)*3; - //first last bits. - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - if ((b1==-1) || (b2==-1)) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null + //decodedData = new byte[ (numberQuadruple)*3]; + dataIndex = (numberQuadruple - 1) * 4; + encodedIndex = (numberQuadruple - 1) * 3; + //first last bits. + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1==-1) || (b2==-1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - byte d3,d4; - b3 = base64Alphabet[d3=base64Data[dataIndex++]]; - b4 = base64Alphabet[d4=base64Data[dataIndex++]]; - if ((b3==-1 ) || (b4==-1) ) { - //Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 1 ]; - decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 2 ]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); - decodedData[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1) || (b4 == -1) ) { + //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 1]; + decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4) ; + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 2]; + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + decodedData[encodedIndex] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); } } else { //No PAD e.g 3cQl decodedData = new byte[encodedIndex+3]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4); } - encodedIndex=0; - dataIndex=0; - //the begin - for (i=numberQuadruple-1; i>0; i--) { - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; + encodedIndex = 0; + dataIndex = 0; + //the begin + for (i = numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - } - return decodedData; - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data String containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(String base64Data, - OutputStream os) throws Base64DecodingException, IOException { - byte[] bytes=new byte[base64Data.length()]; - int len=getBytesInternal(base64Data, bytes); - decode(bytes,os,len); - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data Byte array containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(byte[] base64Data, - OutputStream os) throws Base64DecodingException, IOException { - decode(base64Data,os,-1); - } - protected final static void decode(byte[] base64Data, - OutputStream os,int len) throws Base64DecodingException, IOException { - - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 ); + } + return decodedData; } - int numberQuadruple = (len/FOURBYTE ); + /** + * Decodes Base64 data into outputstream + * + * @param base64Data String containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(String base64Data, OutputStream os) + throws Base64DecodingException, IOException { + byte[] bytes = new byte[base64Data.length()]; + int len = getBytesInternal(base64Data, bytes); + decode(bytes,os,len); + } - if (numberQuadruple == 0) - return; + /** + * Decodes Base64 data into outputstream + * + * @param base64Data Byte array containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(byte[] base64Data, OutputStream os) + throws Base64DecodingException, IOException { + decode(base64Data,os,-1); + } - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + protected static final void decode(byte[] base64Data, OutputStream os, int len) + throws Base64DecodingException, IOException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int i = 0; + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - int dataIndex = 0; + int numberQuadruple = (len / FOURBYTE); - //the begin - for (i=numberQuadruple-1; i>0; i--) { + if (numberQuadruple == 0) { + return; + } + + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + + int i = 0; + int dataIndex = 0; + + //the begin + for (i=numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } + + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf))); + os.write( (byte)(b3 << 6 | b4)); + } b1 = base64Alphabet[base64Data[dataIndex++]]; b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); - } - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - - // first last bits. - if ((b1==-1) || - (b2==-1) ){ - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - byte d3,d4; - b3= base64Alphabet[d3 = base64Data[dataIndex++]]; - b4= base64Alphabet[d4 = base64Data[dataIndex++]]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } - return ; - } - - /** - * Decodes Base64 data into outputstream - * - * @param is containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(InputStream is, - OutputStream os) throws Base64DecodingException, IOException { - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; - - int index=0; - byte []data=new byte[4]; - int read; - //the begin - while ((read=is.read())>0) { - byte readed=(byte)read; - if (isWhiteSpace(readed)) { - continue; - } - if (isPad(readed)) { - data[index++]=readed; - if (index==3) - data[index++]=(byte)is.read(); - break; + // first last bits. + if ((b1 == -1) || (b2 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - - if ((data[index++]=readed)==-1) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - if (index!=4) { - continue; + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1 ) || (b4 == -1) ) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3 ) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write( (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); } - index=0; - b1 = base64Alphabet[data[0]]; - b2 = base64Alphabet[data[1]]; - b3 = base64Alphabet[data[2]]; - b4 = base64Alphabet[data[3]]; - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); } + /** + * Decodes Base64 data into outputstream + * + * @param is containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(InputStream is, OutputStream os) + throws Base64DecodingException, IOException { + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - byte d1=data[0],d2=data[1],d3=data[2], d4=data[3]; - b1 = base64Alphabet[d1]; - b2 = base64Alphabet[d2]; - b3 = base64Alphabet[ d3 ]; - b4 = base64Alphabet[ d4 ]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - b3 = base64Alphabet[ d3 ]; - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl + int index=0; + byte[] data = new byte[4]; + int read; + //the begin + while ((read = is.read()) > 0) { + byte readed = (byte)read; + if (isWhiteSpace(readed)) { + continue; + } + if (isPad(readed)) { + data[index++] = readed; + if (index == 3) { + data[index++] = (byte)is.read(); + } + break; + } - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } + if ((data[index++] = readed) == -1) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - return ; - } - /** - * remove WhiteSpace from MIME containing encoded Base64 data. - * - * @param data the byte array of base64 data (with WS) - * @return the new length - */ - protected static final int removeWhiteSpace(byte[] data) { - if (data == null) - return 0; + if (index != 4) { + continue; + } + index = 0; + b1 = base64Alphabet[data[0]]; + b2 = base64Alphabet[data[1]]; + b3 = base64Alphabet[data[2]]; + b4 = base64Alphabet[data[3]]; - // count characters that's not whitespace - int newSize = 0; - int len = data.length; - for (int i = 0; i < len; i++) { - byte dataS=data[i]; - if (!isWhiteSpace(dataS)) - data[newSize++] = dataS; - } - return newSize; - } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + + byte d1 = data[0], d2 = data[1], d3 = data[2], d4 = data[3]; + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + } + + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data the byte array of base64 data (with WS) + * @return the new length + */ + protected static final int removeWhiteSpace(byte[] data) { + if (data == null) { + return 0; + } + + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + byte dataS = data[i]; + if (!isWhiteSpace(dataS)) { + data[newSize++] = dataS; + } + } + return newSize; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java deleted file mode 100644 index 0a7503a9331..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.utils; - -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import org.w3c.dom.Document; - -/** - * @author Raul Benito - */ -public class CachedXPathAPIHolder { - - static ThreadLocal local=new ThreadLocal(); - static ThreadLocal localDoc=new ThreadLocal(); - - /** - * Sets the doc for the xpath transformation. Resets the cache if needed - * @param doc - */ - public static void setDoc(Document doc) { - if (localDoc.get()!=doc) { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(doc); - return; - } - //Different docs reset. - cx.getXPathContext().reset(); - localDoc.set(doc); - } - } - - /** - * @return the cachexpathapi for this thread - */ - public static CachedXPathAPI getCachedXPathAPI() { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(null); - } - return cx; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java deleted file mode 100644 index fe1ae841755..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.utils; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.Expression; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.XPathContext; -import com.sun.org.apache.xpath.internal.compiler.FunctionTable; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.*; -import org.w3c.dom.traversal.NodeIterator; - -import javax.xml.transform.ErrorListener; -import javax.xml.transform.SourceLocator; -import javax.xml.transform.TransformerException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * - * @author $Author: mullan $ - */ -public class CachedXPathFuncHereAPI { - - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(CachedXPathFuncHereAPI.class.getName()); - /** - * XPathContext, and thus DTMManager and DTMs, persists through multiple - * calls to this object. - */ - FuncHereContext _funcHereContext = null; - - /** Field _dtmManager */ - DTMManager _dtmManager = null; - - XPathContext _context = null; - - String xpathStr=null; - - XPath xpath=null; - - static FunctionTable _funcTable = null; - - static { - fixupFunctionTable(); - } - - /** - * Method getFuncHereContext - * @return the context for this object - * - */ - public FuncHereContext getFuncHereContext() { - return this._funcHereContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - */ - private CachedXPathFuncHereAPI() {} - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param existingXPathContext - */ - public CachedXPathFuncHereAPI(XPathContext existingXPathContext) { - this._dtmManager = existingXPathContext.getDTMManager(); - this._context=existingXPathContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param previouslyUsed - */ - public CachedXPathFuncHereAPI(CachedXPathAPI previouslyUsed) { - this._dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - this._context=previouslyUsed.getXPathContext(); - } - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeIterator selectNodeIterator(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, getStrFromNode(xpathnode), namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, getStrFromNode(xpathnode), contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeList selectNodeList( - Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, str, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, getStrFromNode(xpathnode),contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - xpath = createXPath(str, prefixResolver); - xpathStr=str; - } - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval( - Node contextNode, Node xpathnode, String str, PrefixResolver prefixResolver) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - try { - xpath = createXPath(str, prefixResolver); - } catch (TransformerException ex) { - //Try to see if it is a problem with the classloader. - Throwable th= ex.getCause(); - if (th instanceof ClassNotFoundException) { - if (th.getMessage().indexOf("FuncHere")>0) { - throw new RuntimeException(I18n.translate("endorsed.jdk1.4.0")/*,*/+ex); - } - } - throw ex; - } - xpathStr=str; - } - - // Execute the XPath, and have it return the result - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { - XPath xpath = null; - Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, - ErrorListener.class, FunctionTable.class}; - Object[] objects = new Object[]{str, null, prefixResolver, new Integer(XPath.SELECT), null, _funcTable}; - try { - Constructor constructor = XPath.class.getConstructor(classes); - xpath = constructor.newInstance(objects); - } catch (Throwable t) { - } - if (xpath == null) { - xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - } - return xpath; - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string for the node. - */ - public static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - - // we iterate over all siblings of the context node because eventually, - // the text is "polluted" with pi's or comments - StringBuffer sb = new StringBuffer(); - - for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); - currentSibling != null; - currentSibling = currentSibling.getNextSibling()) { - if (currentSibling.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) currentSibling).getData()); - } - } - - return sb.toString(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return null; - } - - private static void fixupFunctionTable() { - boolean installed = false; - log.log(java.util.logging.Level.INFO, "Registering Here function"); - /** - * Try to register our here() implementation as internal function. - */ - try { - Class []args = {String.class, Expression.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { - Object []params = {"here", new FuncHere()}; - installFunction.invoke(null, params); - installed = true; - } - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - if(!installed) { - try { - _funcTable = new FunctionTable(); - Class []args = {String.class, Class.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - Object []params = {"here", FuncHere.class}; - installFunction.invoke(_funcTable, params); - installed = true; - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - if (installed) { - log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } else { - log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java new file mode 100644 index 00000000000..c9b910a4611 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java @@ -0,0 +1,277 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.sun.org.apache.xml.internal.security.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +/** + * This class is extremely useful for loading resources and classes in a fault + * tolerant manner that works across different applications servers. Do not + * touch this unless you're a grizzled classloading guru veteran who is going to + * verify any change on 6 different application servers. + */ +final class ClassLoaderUtils { + + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName()); + + private ClassLoaderUtils() { + } + + /** + * Load a given resource.

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

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static URL getResource(String resourceName, Class callingClass) { + URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = + Thread.currentThread().getContextClassLoader().getResource( + resourceName.substring(1) + ); + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (url == null) { + url = cluClassloader.getResource(resourceName); + } + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = cluClassloader.getResource(resourceName.substring(1)); + } + + if (url == null) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + url = cl.getResource(resourceName); + } + } + + if (url == null) { + url = callingClass.getResource(resourceName); + } + + if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) { + return getResource('/' + resourceName, callingClass); + } + + return url; + } + + /** + * Load a given resources.

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

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static List getResources(String resourceName, Class callingClass) { + List ret = new ArrayList(); + Enumeration urls = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public URL nextElement() { + return null; + } + + }; + try { + urls = Thread.currentThread().getContextClassLoader().getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = + Thread.currentThread().getContextClassLoader().getResources( + resourceName.substring(1) + ); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (!urls.hasMoreElements()) { + try { + urls = cluClassloader.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = cluClassloader.getResources(resourceName.substring(1)); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + if (!urls.hasMoreElements()) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + try { + urls = cl.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + } + + if (!urls.hasMoreElements()) { + URL url = callingClass.getResource(resourceName); + if (url != null) { + ret.add(url); + } + } + while (urls.hasMoreElements()) { + ret.add(urls.nextElement()); + } + + + if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) { + return getResources('/' + resourceName, callingClass); + } + return ret; + } + + + /** + * This is a convenience method to load a resource as a stream.

    The + * algorithm used to find the resource is given in getResource() + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static InputStream getResourceAsStream(String resourceName, Class callingClass) { + URL url = getResource(resourceName, callingClass); + + try { + return (url != null) ? url.openStream() : null; + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + return null; + } + } + + /** + * Load a class with a given name.

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

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • Using the basic Class.forName() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • From the callingClass.getClassLoader() + *
    + * + * @param className The name of the class to load + * @param callingClass The Class object of the calling object + * @throws ClassNotFoundException If the class cannot be found anywhere. + */ + static Class loadClass(String className, Class callingClass) + throws ClassNotFoundException { + try { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + + if (cl != null) { + return cl.loadClass(className); + } + } catch (ClassNotFoundException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + return loadClass2(className, callingClass); + } + + private static Class loadClass2(String className, Class callingClass) + throws ClassNotFoundException { + try { + return Class.forName(className); + } catch (ClassNotFoundException ex) { + try { + if (ClassLoaderUtils.class.getClassLoader() != null) { + return ClassLoaderUtils.class.getClassLoader().loadClass(className); + } + } catch (ClassNotFoundException exc) { + if (callingClass != null && callingClass.getClassLoader() != null) { + return callingClass.getClassLoader().loadClass(className); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + throw ex; + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java index 39ec71d8794..78907b09595 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Provides all constants and some translation functions for i18n. * @@ -29,202 +29,245 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * XML * Signature specification. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class Constants { - /** Field configurationFile */ - public static final String configurationFile = "data/websig.conf"; + /** Field configurationFile */ + public static final String configurationFile = "data/websig.conf"; - /** Field configurationFileNew */ - public static final String configurationFileNew = ".xmlsecurityconfig"; + /** Field configurationFileNew */ + public static final String configurationFileNew = ".xmlsecurityconfig"; - /** Field exceptionMessagesResourceBundleDir */ - public static final String exceptionMessagesResourceBundleDir = - "com/sun/org/apache/xml/internal/security/resource"; + /** Field exceptionMessagesResourceBundleDir */ + public static final String exceptionMessagesResourceBundleDir = + "com/sun/org/apache/xml/internal/security/resource"; - /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ - public static final String exceptionMessagesResourceBundleBase = - exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - //J- - /** - * The URL of the XML Signature specification - */ - public static final String SIGNATURESPECIFICATION_URL = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ + public static final String exceptionMessagesResourceBundleBase = + exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - /** - * The namespace of the XML Signature specification - */ - public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - /** The URL for more algorithm **/ - public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** The URI for XML spec*/ - public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** The URI for XMLNS spec*/ - public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; + /** + * The URL of the + * XML Signature specification + */ + public static final String SIGNATURESPECIFICATION_URL = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; - /** Tag of Attr Algorithm**/ - public static final String _ATT_ALGORITHM = "Algorithm"; - /** Tag of Attr URI**/ - public static final String _ATT_URI = "URI"; - /** Tag of Attr Type**/ - public static final String _ATT_TYPE = "Type"; - /** Tag of Attr Id**/ - public static final String _ATT_ID = "Id"; - /** Tag of Attr MimeType**/ - public static final String _ATT_MIMETYPE = "MimeType"; - /** Tag of Attr Encoding**/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr Target**/ - public static final String _ATT_TARGET = "Target"; + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) - // KeyValue (DSAKeyValue|RSAKeyValue) - // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) - // RSAKeyValue (Modulus, Exponent) - // RetrievalMethod (Transforms?) - // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) - // X509IssuerSerial (X509IssuerName, X509SerialNumber) - // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) - // SPKIData (SPKISexp) + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#"; - /** Tag of Element CanonicalizationMethod **/ - public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; - /** Tag of Element DigestMethod **/ - public static final String _TAG_DIGESTMETHOD = "DigestMethod"; - /** Tag of Element DigestValue **/ - public static final String _TAG_DIGESTVALUE = "DigestValue"; - /** Tag of Element Manifest **/ - public static final String _TAG_MANIFEST = "Manifest"; - /** Tag of Element Methods **/ - public static final String _TAG_METHODS = "Methods"; - /** Tag of Element Object **/ - public static final String _TAG_OBJECT = "Object"; - /** Tag of Element Reference **/ - public static final String _TAG_REFERENCE = "Reference"; - /** Tag of Element Signature **/ - public static final String _TAG_SIGNATURE = "Signature"; - /** Tag of Element SignatureMethod **/ - public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; - /** Tag of Element HMACOutputLength **/ - public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; - /** Tag of Element SignatureProperties **/ - public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; - /** Tag of Element SignatureProperty **/ - public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; - /** Tag of Element SignatureValue **/ - public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; - /** Tag of Element SignedInfo **/ - public static final String _TAG_SIGNEDINFO = "SignedInfo"; - /** Tag of Element Transform **/ - public static final String _TAG_TRANSFORM = "Transform"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element XPath **/ - public static final String _TAG_XPATH = "XPath"; - /** Tag of Element KeyInfo **/ - public static final String _TAG_KEYINFO = "KeyInfo"; - /** Tag of Element KeyName **/ - public static final String _TAG_KEYNAME = "KeyName"; - /** Tag of Element KeyValue **/ - public static final String _TAG_KEYVALUE = "KeyValue"; - /** Tag of Element RetrievalMethod **/ - public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; - /** Tag of Element X509Data **/ - public static final String _TAG_X509DATA = "X509Data"; - /** Tag of Element PGPData **/ - public static final String _TAG_PGPDATA = "PGPData"; - /** Tag of Element SPKIData **/ - public static final String _TAG_SPKIDATA = "SPKIData"; - /** Tag of Element MgmtData **/ - public static final String _TAG_MGMTDATA = "MgmtData"; - /** Tag of Element RSAKeyValue **/ - public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; - /** Tag of Element Exponent **/ - public static final String _TAG_EXPONENT = "Exponent"; - /** Tag of Element Modulus **/ - public static final String _TAG_MODULUS = "Modulus"; - /** Tag of Element DSAKeyValue **/ - public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; - /** Tag of Element P **/ - public static final String _TAG_P = "P"; - /** Tag of Element Q **/ - public static final String _TAG_Q = "Q"; - /** Tag of Element G **/ - public static final String _TAG_G = "G"; - /** Tag of Element Y **/ - public static final String _TAG_Y = "Y"; - /** Tag of Element J **/ - public static final String _TAG_J = "J"; - /** Tag of Element Seed **/ - public static final String _TAG_SEED = "Seed"; - /** Tag of Element PgenCounter **/ - public static final String _TAG_PGENCOUNTER = "PgenCounter"; - /** Tag of Element rawX509Certificate **/ - public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; - /** Tag of Element X509IssuerSerial **/ - public static final String _TAG_X509ISSUERSERIAL = "X509IssuerSerial"; - /** Tag of Element X509SKI **/ - public static final String _TAG_X509SKI = "X509SKI"; - /** Tag of Element X509SubjectName **/ - public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; - /** Tag of Element X509Certificate **/ - public static final String _TAG_X509CERTIFICATE = "X509Certificate"; - /** Tag of Element X509CRL **/ - public static final String _TAG_X509CRL = "X509CRL"; - /** Tag of Element X509IssuerName **/ - public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; - /** Tag of Element X509SerialNumber **/ - public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; - /** Tag of Element PGPKeyID **/ - public static final String _TAG_PGPKEYID = "PGPKeyID"; - /** Tag of Element PGPKeyPacket **/ - public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; - /** Tag of Element SPKISexp **/ - public static final String _TAG_SPKISEXP = "SPKISexp"; + /** The URL for more algorithms **/ + public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** Digest - Required SHA1 */ - public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + /** The URI for XML spec*/ + public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** - * @see - * draft-blake-wilson-xmldsig-ecdsa-02.txt - */ - public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; - //J+ + /** The URI for XMLNS spec*/ + public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; - private Constants() { - // we don't allow instantiation - } + /** Tag of Attr Algorithm**/ + public static final String _ATT_ALGORITHM = "Algorithm"; - /** - * Sets the namespace prefix which will be used to identify elements in the - * XML Signature Namespace. - * - *
    -    * Constants.setSignatureSpecNSprefix("dsig");
    -    * 
    - * - * @param newPrefix is the new namespace prefix. - * @throws XMLSecurityException - * @see com.sun.org.apache.xml.internal.security.utils.Constants#getSignatureSpecNSprefix - * $todo$ Add consistency checking for valid prefix - */ - public static void setSignatureSpecNSprefix(String newPrefix) throws XMLSecurityException { - ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, newPrefix); - } + /** Tag of Attr URI**/ + public static final String _ATT_URI = "URI"; + + /** Tag of Attr Type**/ + public static final String _ATT_TYPE = "Type"; + + /** Tag of Attr Id**/ + public static final String _ATT_ID = "Id"; + + /** Tag of Attr MimeType**/ + public static final String _ATT_MIMETYPE = "MimeType"; + + /** Tag of Attr Encoding**/ + public static final String _ATT_ENCODING = "Encoding"; + + /** Tag of Attr Target**/ + public static final String _ATT_TARGET = "Target"; + + // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) + // KeyValue (DSAKeyValue|RSAKeyValue) + // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) + // RSAKeyValue (Modulus, Exponent) + // RetrievalMethod (Transforms?) + // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) + // X509IssuerSerial (X509IssuerName, X509SerialNumber) + // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) + // SPKIData (SPKISexp) + + /** Tag of Element CanonicalizationMethod **/ + public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; + + /** Tag of Element DigestMethod **/ + public static final String _TAG_DIGESTMETHOD = "DigestMethod"; + + /** Tag of Element DigestValue **/ + public static final String _TAG_DIGESTVALUE = "DigestValue"; + + /** Tag of Element Manifest **/ + public static final String _TAG_MANIFEST = "Manifest"; + + /** Tag of Element Methods **/ + public static final String _TAG_METHODS = "Methods"; + + /** Tag of Element Object **/ + public static final String _TAG_OBJECT = "Object"; + + /** Tag of Element Reference **/ + public static final String _TAG_REFERENCE = "Reference"; + + /** Tag of Element Signature **/ + public static final String _TAG_SIGNATURE = "Signature"; + + /** Tag of Element SignatureMethod **/ + public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; + + /** Tag of Element HMACOutputLength **/ + public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; + + /** Tag of Element SignatureProperties **/ + public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; + + /** Tag of Element SignatureProperty **/ + public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; + + /** Tag of Element SignatureValue **/ + public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; + + /** Tag of Element SignedInfo **/ + public static final String _TAG_SIGNEDINFO = "SignedInfo"; + + /** Tag of Element Transform **/ + public static final String _TAG_TRANSFORM = "Transform"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element XPath **/ + public static final String _TAG_XPATH = "XPath"; + + /** Tag of Element KeyInfo **/ + public static final String _TAG_KEYINFO = "KeyInfo"; + + /** Tag of Element KeyName **/ + public static final String _TAG_KEYNAME = "KeyName"; + + /** Tag of Element KeyValue **/ + public static final String _TAG_KEYVALUE = "KeyValue"; + + /** Tag of Element RetrievalMethod **/ + public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; + + /** Tag of Element X509Data **/ + public static final String _TAG_X509DATA = "X509Data"; + + /** Tag of Element PGPData **/ + public static final String _TAG_PGPDATA = "PGPData"; + + /** Tag of Element SPKIData **/ + public static final String _TAG_SPKIDATA = "SPKIData"; + + /** Tag of Element MgmtData **/ + public static final String _TAG_MGMTDATA = "MgmtData"; + + /** Tag of Element RSAKeyValue **/ + public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; + + /** Tag of Element Exponent **/ + public static final String _TAG_EXPONENT = "Exponent"; + + /** Tag of Element Modulus **/ + public static final String _TAG_MODULUS = "Modulus"; + + /** Tag of Element DSAKeyValue **/ + public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; + + /** Tag of Element P **/ + public static final String _TAG_P = "P"; + + /** Tag of Element Q **/ + public static final String _TAG_Q = "Q"; + + /** Tag of Element G **/ + public static final String _TAG_G = "G"; + + /** Tag of Element Y **/ + public static final String _TAG_Y = "Y"; + + /** Tag of Element J **/ + public static final String _TAG_J = "J"; + + /** Tag of Element Seed **/ + public static final String _TAG_SEED = "Seed"; + + /** Tag of Element PgenCounter **/ + public static final String _TAG_PGENCOUNTER = "PgenCounter"; + + /** Tag of Element rawX509Certificate **/ + public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; + + /** Tag of Element X509IssuerSerial **/ + public static final String _TAG_X509ISSUERSERIAL= "X509IssuerSerial"; + + /** Tag of Element X509SKI **/ + public static final String _TAG_X509SKI = "X509SKI"; + + /** Tag of Element X509SubjectName **/ + public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; + + /** Tag of Element X509Certificate **/ + public static final String _TAG_X509CERTIFICATE = "X509Certificate"; + + /** Tag of Element X509CRL **/ + public static final String _TAG_X509CRL = "X509CRL"; + + /** Tag of Element X509IssuerName **/ + public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; + + /** Tag of Element X509SerialNumber **/ + public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; + + /** Tag of Element PGPKeyID **/ + public static final String _TAG_PGPKEYID = "PGPKeyID"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_DERENCODEDKEYVALUE = "DEREncodedKeyValue"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_KEYINFOREFERENCE = "KeyInfoReference"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_X509DIGEST = "X509Digest"; + + /** Tag of Element SPKISexp **/ + public static final String _TAG_SPKISEXP = "SPKISexp"; + + /** Digest - Required SHA1 */ + public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + + /** + * @see + * draft-blake-wilson-xmldsig-ecdsa-02.txt + */ + public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = + "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; + + private Constants() { + // we don't allow instantiation + } - /** - * Returns the XML namespace prefix which is used for elements in the XML - * Signature namespace. - * - * It is defaulted to dsig, but can be changed using the - * {@link #setSignatureSpecNSprefix} function. - * - * @return the current used namespace prefix - * @see #setSignatureSpecNSprefix - */ - public static String getSignatureSpecNSprefix() { - return ElementProxy.getDefaultPrefix(Constants.SignatureSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java new file mode 100644 index 00000000000..b4572b481ca --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java @@ -0,0 +1,79 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + */ +public class DOMNamespaceContext implements NamespaceContext { + + private Map namespaceMap = new HashMap(); + + public DOMNamespaceContext(Node contextNode) { + addNamespaces(contextNode); + } + + public String getNamespaceURI(String arg0) { + return namespaceMap.get(arg0); + } + + public String getPrefix(String arg0) { + for (String key : namespaceMap.keySet()) { + String value = namespaceMap.get(key); + if (value.equals(arg0)) { + return key; + } + } + return null; + } + + public Iterator getPrefixes(String arg0) { + return namespaceMap.keySet().iterator(); + } + + private void addNamespaces(Node element) { + if (element.getParentNode() != null) { + addNamespaces(element.getParentNode()); + } + if (element instanceof Element) { + Element el = (Element)element; + NamedNodeMap map = el.getAttributes(); + for (int x = 0; x < map.getLength(); x++) { + Attr attr = (Attr)map.item(x); + if ("xmlns".equals(attr.getPrefix())) { + namespaceMap.put(attr.getLocalName(), attr.getValue()); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java index bdf560dc78e..bd06b7d7c27 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -29,16 +31,16 @@ import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorith * */ public class DigesterOutputStream extends ByteArrayOutputStream { + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName()); + final MessageDigestAlgorithm mda; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (DigesterOutputStream.class.getName()); /** * @param mda */ public DigesterOutputStream(MessageDigestAlgorithm mda) { - this.mda=mda; + this.mda = mda; } /** @inheritDoc */ @@ -55,9 +57,9 @@ public class DigesterOutputStream extends ByteArrayOutputStream { public void write(byte[] arg0, int arg1, int arg2) { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } @@ -68,6 +70,6 @@ public class DigesterOutputStream extends ByteArrayOutputStream { * @return the digest value */ public byte[] getDigestValue() { - return mda.digest(); + return mda.digest(); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java index 9da45ce8cd1..618659c9f19 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java @@ -1,17 +1,41 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public interface ElementChecker { - /** - * Check that the elemnt is the one expect - * - * @throws XMLSecurityException - */ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) - throws XMLSecurityException; + /** + * Check that the element is the one expect + * + * @throws XMLSecurityException + */ + void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) + throws XMLSecurityException; - public boolean isNamespaceElement(Node el, String type, String ns); + boolean isNamespaceElement(Node el, String type, String ns); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java index 5a94927d1c6..d71fd100384 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java @@ -1,60 +1,90 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public abstract class ElementCheckerImpl implements ElementChecker { - public boolean isNamespaceElement(Node el, String type, String ns) { - if ((el == null) || - ns!=el.getNamespaceURI() || !el.getLocalName().equals(type)){ - return false; - } - return true; - } - /** A checker for DOM that interns NS */ - public static class InternedNsChecker extends ElementCheckerImpl{ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); - - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((namespaceSHOULDBE!=namespaceIS) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + public boolean isNamespaceElement(Node el, String type, String ns) { + if ((el == null) || + ns != el.getNamespaceURI() || !el.getLocalName().equals(type)){ + return false; } - /** A checker for DOM that interns NS */ - public static class FullChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { + return true; + } - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); + /** A checker for DOM that interns NS */ + public static class InternedNsChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((!namespaceSHOULDBE.equals(namespaceIS)) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((expectedNamespace != namespaceIS) || + !expectedLocalname.equals(localnameIS)) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } } + } - /** An empty checker if schema checking is used */ - public static class EmptyChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - } + /** A checker for DOM that interns NS */ + public static class FullChecker extends ElementCheckerImpl { + + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((!expectedNamespace.equals(namespaceIS)) || + !expectedLocalname.equals(localnameIS) ) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } } + } + + /** An empty checker if schema checking is used */ + public static class EmptyChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + // empty + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java index 2d2fdeb61bb..ac7a53eba4f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java @@ -45,13 +45,13 @@ public abstract class ElementProxy { java.util.logging.Logger.getLogger(ElementProxy.class.getName()); /** Field constructionElement */ - protected Element _constructionElement = null; + protected Element constructionElement = null; /** Field baseURI */ - protected String _baseURI = null; + protected String baseURI = null; /** Field doc */ - protected Document _doc = null; + protected Document doc = null; /** Field prefixMappings */ private static Map prefixMappings = new ConcurrentHashMap(); @@ -73,9 +73,9 @@ public abstract class ElementProxy { throw new RuntimeException("Document is null"); } - this._doc = doc; - this._constructionElement = - createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName()); + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal(this.doc, this.getBaseNamespace(), this.getBaseLocalName()); } /** @@ -94,9 +94,9 @@ public abstract class ElementProxy { log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")"); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; this.guaranteeThatElementInCorrectSpace(); } @@ -184,9 +184,9 @@ public abstract class ElementProxy { log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\""); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; } @@ -196,7 +196,7 @@ public abstract class ElementProxy { * @return the Element which was constructed by the Object. */ public final Element getElement() { - return this._constructionElement; + return this.constructionElement; } /** @@ -208,9 +208,9 @@ public abstract class ElementProxy { HelperNodeList nl = new HelperNodeList(); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); nl.appendChild(this.getElement()); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); return nl; } @@ -221,7 +221,7 @@ public abstract class ElementProxy { * @return the Document where this element is contained. */ public Document getDocument() { - return this._doc; + return this.doc; } /** @@ -230,7 +230,7 @@ public abstract class ElementProxy { * @return the base uri of the namespace of this element */ public String getBaseURI() { - return this._baseURI; + return this.baseURI; } /** @@ -243,8 +243,8 @@ public abstract class ElementProxy { String expectedLocalName = this.getBaseLocalName(); String expectedNamespaceUri = this.getBaseNamespace(); - String actualLocalName = this._constructionElement.getLocalName(); - String actualNamespaceUri = this._constructionElement.getNamespaceURI(); + String actualLocalName = this.constructionElement.getLocalName(); + String actualNamespaceUri = this.constructionElement.getNamespaceURI(); if(!expectedNamespaceUri.equals(actualNamespaceUri) && !expectedLocalName.equals(actualLocalName)) { @@ -262,11 +262,11 @@ public abstract class ElementProxy { */ public void addBigIntegerElement(BigInteger bi, String localname) { if (bi != null) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); Base64.fillElementWithBigInteger(e, bi); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -278,11 +278,11 @@ public abstract class ElementProxy { */ public void addBase64Element(byte[] bytes, String localname) { if (bytes != null) { - Element e = Base64.encodeToElement(this._doc, localname, bytes); + Element e = Base64.encodeToElement(this.doc, localname, bytes); - this._constructionElement.appendChild(e); + this.constructionElement.appendChild(e); if (!XMLUtils.ignoreLineBreaks()) { - this._constructionElement.appendChild(this._doc.createTextNode("\n")); + this.constructionElement.appendChild(this.doc.createTextNode("\n")); } } } @@ -294,12 +294,12 @@ public abstract class ElementProxy { * @param localname */ public void addTextElement(String text, String localname) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); - Text t = this._doc.createTextNode(text); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); + Text t = this.doc.createTextNode(text); e.appendChild(t); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -310,9 +310,9 @@ public abstract class ElementProxy { public void addBase64Text(byte[] bytes) { if (bytes != null) { Text t = XMLUtils.ignoreLineBreaks() - ? this._doc.createTextNode(Base64.encode(bytes)) - : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); - this._constructionElement.appendChild(t); + ? this.doc.createTextNode(Base64.encode(bytes)) + : this.doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); + this.constructionElement.appendChild(t); } } @@ -323,9 +323,9 @@ public abstract class ElementProxy { */ public void addText(String text) { if (text != null) { - Text t = this._doc.createTextNode(text); + Text t = this.doc.createTextNode(text); - this._constructionElement.appendChild(t); + this.constructionElement.appendChild(t); } } @@ -342,7 +342,7 @@ public abstract class ElementProxy { ) throws Base64DecodingException { return Base64.decodeBigIntegerFromText( XMLUtils.selectNodeText( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ) ); } @@ -360,7 +360,7 @@ public abstract class ElementProxy { throws XMLSecurityException { Element e = XMLUtils.selectNode( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ); return Base64.decode(e); @@ -375,7 +375,7 @@ public abstract class ElementProxy { */ public String getTextFromChildElement(String localname, String namespace) { return XMLUtils.selectNode( - this._constructionElement.getFirstChild(), + this.constructionElement.getFirstChild(), namespace, localname, 0).getTextContent(); @@ -388,7 +388,7 @@ public abstract class ElementProxy { * @throws XMLSecurityException */ public byte[] getBytesFromTextChild() throws XMLSecurityException { - return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement)); + return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this.constructionElement)); } /** @@ -398,7 +398,7 @@ public abstract class ElementProxy { * element */ public String getTextFromTextChild() { - return XMLUtils.getFullTextChildrenFromElement(this._constructionElement); + return XMLUtils.getFullTextChildrenFromElement(this.constructionElement); } /** @@ -410,7 +410,7 @@ public abstract class ElementProxy { */ public int length(String namespace, String localname) { int number = 0; - Node sibling = this._constructionElement.getFirstChild(); + Node sibling = this.constructionElement.getFirstChild(); while (sibling != null) { if (localname.equals(sibling.getLocalName()) && namespace.equals(sibling.getNamespaceURI())) { @@ -448,18 +448,18 @@ public abstract class ElementProxy { ns = "xmlns:" + prefix; } - Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); + Attr a = this.constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); if (a != null) { if (!a.getNodeValue().equals(uri)) { - Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) }; + Object exArgs[] = { ns, this.constructionElement.getAttributeNS(null, ns) }; throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs); } return; } - this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); + this.constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); } /** @@ -515,16 +515,4 @@ public abstract class ElementProxy { return prefixMappings.get(namespace); } - protected void setLocalIdAttribute(String attrName, String value) { - - if (value != null) { - Attr attr = getDocument().createAttributeNS(null, attrName); - attr.setValue(value); - getElement().setAttributeNodeNS(attr); - getElement().setIdAttributeNode(attr, true); - } - else { - getElement().removeAttributeNS(null, attrName); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java index e250bff2a16..175911e169f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java @@ -2,179 +2,238 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - - -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - - -/** - * - * @author $Author: mullan $ - */ public class EncryptionConstants { - //J- - // Attributes that exist in XML Signature in the same way + // Attributes that exist in XML Signature in the same way /** Tag of Attr Algorithm **/ - public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - /** Tag of Attr Id**/ - public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Attr Target **/ - public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Tag of Attr Type **/ - public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** Tag of Attr URI **/ - public static final String _ATT_URI = Constants._ATT_URI; + public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - // Attributes new in XML Encryption - /** Tag of Attr encoding **/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr recipient **/ - public static final String _ATT_RECIPIENT = "Recipient"; - /** Tag of Attr mimetype **/ - public static final String _ATT_MIMETYPE = "MimeType"; + /** Tag of Attr Id**/ + public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Element CarriedKeyName **/ - public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Tag of Element CipherData **/ - public static final String _TAG_CIPHERDATA = "CipherData"; - /** Tag of Element CipherReference **/ - public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Tag of Element CipherValue **/ - public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Tag of Element DataReference **/ - public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Tag of Element EncryptedData **/ - public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - /** Tag of Element EncryptedKey **/ - public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** Tag of Element EncryptionMethod **/ - public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; - /** Tag of Element EncryptionProperties **/ - public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; - /** Tag of Element EncryptionProperty **/ - public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; - /** Tag of Element KeyReference **/ - public static final String _TAG_KEYREFERENCE = "KeyReference"; - /** Tag of Element KeySize **/ - public static final String _TAG_KEYSIZE = "KeySize"; - /** Tag of Element OAEPparams **/ - public static final String _TAG_OAEPPARAMS = "OAEPparams"; - /** Tag of Element ReferenceList **/ - public static final String _TAG_REFERENCELIST = "ReferenceList"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element AgreementMethod **/ - public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; - /** Tag of Element KA-Nonce **/ - public static final String _TAG_KA_NONCE = "KA-Nonce"; - /** Tag of Element OriginatorKeyInfo **/ - public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; - /** Tag of Element RecipientKeyInfo **/ - public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + /** Tag of Attr Target **/ + public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Field ENCRYPTIONSPECIFICATION_URL */ - public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + /** Tag of Attr Type **/ + public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** The namespace of the XML Encryption Syntax and Processing */ - public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#"; + /** Tag of Attr URI **/ + public static final String _ATT_URI = Constants._ATT_URI; - /** URI for content*/ - public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; - /** URI for element*/ - public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; - /** URI for mediatype*/ - public static final String TYPE_MEDIATYPE = "http://www.isi.edu/in-notes/iana/assignments/media-types/"; // + "*/*"; + // Attributes new in XML Encryption + /** Tag of Attr encoding **/ + public static final String _ATT_ENCODING = "Encoding"; - /** Block Encryption - REQUIRED TRIPLEDES */ - public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; - /** Block Encryption - REQUIRED AES-128 */ - public static final String ALGO_ID_BLOCKCIPHER_AES128 = EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; - /** Block Encryption - REQUIRED AES-256 */ - public static final String ALGO_ID_BLOCKCIPHER_AES256 = EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; - /** Block Encryption - OPTIONAL AES-192 */ - public static final String ALGO_ID_BLOCKCIPHER_AES192 = EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + /** Tag of Attr recipient **/ + public static final String _ATT_RECIPIENT = "Recipient"; - /** Key Transport - REQUIRED RSA-v1.5*/ - public static final String ALGO_ID_KEYTRANSPORT_RSA15 = EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; - /** Key Transport - REQUIRED RSA-OAEP */ - public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + /** Tag of Attr mimetype **/ + public static final String _ATT_MIMETYPE = "MimeType"; - /** Key Agreement - OPTIONAL Diffie-Hellman */ - public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh"; + /** Tag of Element CarriedKeyName **/ + public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ - public static final String ALGO_ID_KEYWRAP_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; - /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES128 = EncryptionConstants.EncryptionSpecNS + "kw-aes128"; - /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES256 = EncryptionConstants.EncryptionSpecNS + "kw-aes256"; - /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES192 = EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + /** Tag of Element CipherData **/ + public static final String _TAG_CIPHERDATA = "CipherData"; - /* - // Message Digest - REQUIRED SHA1 - public static final String ALGO_ID_DIGEST_SHA160 = Constants.ALGO_ID_DIGEST_SHA1; - // Message Digest - RECOMMENDED SHA256 - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - // Message Digest - OPTIONAL SHA512 - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - // Message Digest - OPTIONAL RIPEMD-160 - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; - */ + /** Tag of Element CipherReference **/ + public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Message Authentication - RECOMMENDED XML Digital Signature */ - public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Tag of Element CipherValue **/ + public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Canonicalization - OPTIONAL Canonical XML with Comments */ - public static final String ALGO_ID_C14N_WITHCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ - public static final String ALGO_ID_C14N_OMITCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + /** Tag of Element DataReference **/ + public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Encoding - REQUIRED base64 */ - public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"; - //J+ + /** Tag of Element EncryptedData **/ + public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - private EncryptionConstants() { - // we don't allow instantiation - } + /** Tag of Element EncryptedKey **/ + public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** - * Method setEncryptionSpecNSprefix - * - * @param newPrefix - * @throws XMLSecurityException - */ - public static void setEncryptionSpecNSprefix(String newPrefix) - throws XMLSecurityException { - ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS, - newPrefix); - } + /** Tag of Element EncryptionMethod **/ + public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; + + /** Tag of Element EncryptionProperties **/ + public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; + + /** Tag of Element EncryptionProperty **/ + public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; + + /** Tag of Element KeyReference **/ + public static final String _TAG_KEYREFERENCE = "KeyReference"; + + /** Tag of Element KeySize **/ + public static final String _TAG_KEYSIZE = "KeySize"; + + /** Tag of Element OAEPparams **/ + public static final String _TAG_OAEPPARAMS = "OAEPparams"; + + /** Tag of Element MGF **/ + public static final String _TAG_MGF = "MGF"; + + /** Tag of Element ReferenceList **/ + public static final String _TAG_REFERENCELIST = "ReferenceList"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element AgreementMethod **/ + public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; + + /** Tag of Element KA-Nonce **/ + public static final String _TAG_KA_NONCE = "KA-Nonce"; + + /** Tag of Element OriginatorKeyInfo **/ + public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; + + /** Tag of Element RecipientKeyInfo **/ + public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + + /** Field ENCRYPTIONSPECIFICATION_URL */ + public static final String ENCRYPTIONSPECIFICATION_URL = + "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + + /** The namespace of the + * + * XML Encryption Syntax and Processing */ + public static final String EncryptionSpecNS = + "http://www.w3.org/2001/04/xmlenc#"; + + /** + * The namespace of the XML Encryption 1.1 specification + */ + public static final String EncryptionSpec11NS = + "http://www.w3.org/2009/xmlenc11#"; + + /** URI for content*/ + public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; + + /** URI for element*/ + public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; + + /** URI for mediatype*/ + public static final String TYPE_MEDIATYPE = + "http://www.isi.edu/in-notes/iana/assignments/media-types/"; + + /** Block Encryption - REQUIRED TRIPLEDES */ + public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; + + /** Block Encryption - REQUIRED AES-128 */ + public static final String ALGO_ID_BLOCKCIPHER_AES128 = + EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; + + /** Block Encryption - REQUIRED AES-256 */ + public static final String ALGO_ID_BLOCKCIPHER_AES256 = + EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; + + /** Block Encryption - OPTIONAL AES-192 */ + public static final String ALGO_ID_BLOCKCIPHER_AES192 = + EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + + /** Block Encryption - OPTIONAL AES-128-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES128_GCM = + "http://www.w3.org/2009/xmlenc11#aes128-gcm"; + + /** Block Encryption - OPTIONAL AES-192-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES192_GCM = + "http://www.w3.org/2009/xmlenc11#aes192-gcm"; + + /** Block Encryption - OPTIONAL AES-256-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES256_GCM = + "http://www.w3.org/2009/xmlenc11#aes256-gcm"; + + /** Key Transport - REQUIRED RSA-v1.5*/ + public static final String ALGO_ID_KEYTRANSPORT_RSA15 = + EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; + + /** Key Transport - REQUIRED RSA-OAEP */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = + EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + + /** Key Transport - OPTIONAL RSA-OAEP_11 */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP_11 = + EncryptionConstants.EncryptionSpec11NS + "rsa-oaep"; + + /** Key Agreement - OPTIONAL Diffie-Hellman */ + public static final String ALGO_ID_KEYAGREEMENT_DH = + EncryptionConstants.EncryptionSpecNS + "dh"; + + /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ + public static final String ALGO_ID_KEYWRAP_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; + + /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES128 = + EncryptionConstants.EncryptionSpecNS + "kw-aes128"; + + /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES256 = + EncryptionConstants.EncryptionSpecNS + "kw-aes256"; + + /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES192 = + EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + + /** Message Authentication - RECOMMENDED XML Digital Signature */ + public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + + /** Canonicalization - OPTIONAL Canonical XML with Comments */ + public static final String ALGO_ID_C14N_WITHCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; + + /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ + public static final String ALGO_ID_C14N_OMITCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + + /** Encoding - REQUIRED base64 */ + public static final String ALGO_ID_ENCODING_BASE64 = + "http://www.w3.org/2000/09/xmldsig#base64"; + + /** MGF1 with SHA-1 */ + public static final String MGF1_SHA1 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha1"; + + /** MGF1 with SHA-224 */ + public static final String MGF1_SHA224 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha224"; + + /** MGF1 with SHA-256 */ + public static final String MGF1_SHA256 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha256"; + + /** MGF1 with SHA-384 */ + public static final String MGF1_SHA384 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha384"; + + /** MGF1 with SHA-512 */ + public static final String MGF1_SHA512 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha512"; + + + private EncryptionConstants() { + // we don't allow instantiation + } - /** - * Method getEncryptionSpecNSprefix - * - * @return the prefix for this node. - */ - public static String getEncryptionSpecNSprefix() { - return ElementProxy - .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java index d6fd93d1aa7..53a5cc88c5e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java @@ -2,62 +2,62 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This is the base object for all objects which map directly to an Element from * the xenc spec. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class EncryptionElementProxy extends ElementProxy { - /** - * Constructor EncryptionElementProxy - * - * @param doc - */ - public EncryptionElementProxy(Document doc) { - super(doc); - } + /** + * Constructor EncryptionElementProxy + * + * @param doc + */ + public EncryptionElementProxy(Document doc) { + super(doc); + } - /** - * Constructor EncryptionElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public EncryptionElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor EncryptionElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public EncryptionElementProxy(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public final String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } + /** @inheritDoc */ + public final String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java index cd40b79d47a..8ba53a6153c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -28,75 +30,69 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** - * * @author Christian Geuer-Pollmann - * */ public class HelperNodeList implements NodeList { - /** Field nodes */ - List nodes = new ArrayList(20); - boolean _allNodesMustHaveSameParent = false; + /** Field nodes */ + List nodes = new ArrayList(); + boolean allNodesMustHaveSameParent = false; - /** - * - */ - public HelperNodeList() { - this(false); - } + /** + * + */ + public HelperNodeList() { + this(false); + } - /** - * @param allNodesMustHaveSameParent - */ - public HelperNodeList(boolean allNodesMustHaveSameParent) { - this._allNodesMustHaveSameParent = allNodesMustHaveSameParent; - } + /** + * @param allNodesMustHaveSameParent + */ + public HelperNodeList(boolean allNodesMustHaveSameParent) { + this.allNodesMustHaveSameParent = allNodesMustHaveSameParent; + } - /** - * Method item - * - * @param index - * @return node with inde i - */ - public Node item(int index) { + /** + * Method item + * + * @param index + * @return node with index i + */ + public Node item(int index) { + return nodes.get(index); + } - // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes"); + /** + * Method getLength + * + * @return length of the list + */ + public int getLength() { + return nodes.size(); + } - return nodes.get(index); - } - - /** - * Method getLength - * - * @return length of the list - */ - public int getLength() { - return nodes.size(); - } - - /** - * Method appendChild - * - * @param node - * @throws IllegalArgumentException - */ - public void appendChild(Node node) throws IllegalArgumentException { - if (this._allNodesMustHaveSameParent && this.getLength() > 0) { - if (this.item(0).getParentNode() != node.getParentNode()) { + /** + * Method appendChild + * + * @param node + * @throws IllegalArgumentException + */ + public void appendChild(Node node) throws IllegalArgumentException { + if (this.allNodesMustHaveSameParent && this.getLength() > 0 + && this.item(0).getParentNode() != node.getParentNode()) { throw new IllegalArgumentException("Nodes have not the same Parent"); - } - } - nodes.add(node); - } + } + nodes.add(node); + } - /** - * @return the document that contains this nodelist - */ - public Document getOwnerDocument() { - if (this.getLength() == 0) { - return null; - } - return XMLUtils.getOwnerDocument(this.item(0)); - } + /** + * @return the document that contains this nodelist + */ + public Document getOwnerDocument() { + if (this.getLength() == 0) { + return null; + } + return XMLUtils.getOwnerDocument(this.item(0)); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java index 4ee51ac92ab..ea9ec28d6e8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java @@ -2,85 +2,42 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.WeakHashMap; -import java.util.Map; - import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; /** * Purpose of this class is to enable the XML Parser to keep track of ID * attributes. This is done by 'registering' attributes of type ID at the - * IdResolver. This is necessary if we create a document from scratch and we - * sign some resources with a URI using a fragent identifier... - *
    - * The problem is that if you do not validate a document, you cannot use the - * getElementByID functionality. So this modules uses some implicit - * knowledge on selected Schemas and DTDs to pick the right Element for a given - * ID: We know that all @Id attributes in an Element from the XML - * Signature namespace are of type ID. - * - * @author $Author: mullan $ - * @see "Identity Crisis" on xml.com + * IdResolver. + * @deprecated */ +@Deprecated public class IdResolver { - /** {@link java.util.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IdResolver.class.getName()); - - private static Map>> docMap = - new WeakHashMap>>(); - - /** - * Constructor IdResolver - * - */ private IdResolver() { - // we don't allow instantiation - } - - /** - * Method registerElementById - * - * @param element the element to register - * @param idValue the value of the ID attribute - */ - public static void registerElementById(Element element, String idValue) { - Document doc = element.getOwnerDocument(); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - if (elementMap == null) { - elementMap = new WeakHashMap>(); - docMap.put(doc, elementMap); - } - } - elementMap.put(idValue, new WeakReference(element)); + // we don't allow instantiation } /** @@ -90,7 +47,7 @@ public class IdResolver { * @param id the ID attribute */ public static void registerElementById(Element element, Attr id) { - IdResolver.registerElementById(element, id.getNodeValue()); + element.setIdAttributeNode(id, true); } /** @@ -101,194 +58,7 @@ public class IdResolver { * @return the element obtained by the id, or null if it is not found. */ public static Element getElementById(Document doc, String id) { - - Element result = IdResolver.getElementByIdType(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdType method: " - + result.getTagName()); - - return result; - } - - result = IdResolver.getElementByIdUsingDOM(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdUsingDOM method: " - + result.getTagName()); - - return result; - } - // this must be done so that Xalan can catch ALL namespaces - //XMLUtils.circumventBug2650(doc); - result = IdResolver.getElementBySearching(doc, id); - - if (result != null) { - IdResolver.registerElementById(result, id); - - return result; - } - - return null; - } - - - /** - * Method getElementByIdUsingDOM - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdUsingDOM(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdUsingDOM() Search for ID " + id); return doc.getElementById(id); } - /** - * Method getElementByIdType - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdType(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdType() Search for ID " + id); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - } - if (elementMap != null) { - WeakReference weakReference = elementMap.get(id); - if (weakReference != null) { - return weakReference.get(); - } - } - return null; - } - - private static java.util.List names; - private static int namesLength; - static { - String namespaces[]={ - Constants.SignatureSpecNS, - EncryptionConstants.EncryptionSpecNS, - "http://schemas.xmlsoap.org/soap/security/2000-12", - "http://www.w3.org/2002/03/xkms#", - "urn:oasis:names:tc:SAML:1.0:assertion", - "urn:oasis:names:tc:SAML:1.0:protocol" - }; - names = Arrays.asList(namespaces); - namesLength = names.size(); - } - - - private static Element getElementBySearching(Node root,String id) { - Element []els=new Element[namesLength + 1]; - getEl(root,id,els); - for (int i=0;i2) - continue; - String value=n.getNodeValue(); - if (name.charAt(0)=='I') { - char ch=name.charAt(1); - if (ch=='d' && value.equals(id)) { - els[index]=el; - if (index==0) { - return 1; - } - } else if (ch=='D' &&value.endsWith(id)) { - if (index!=3) { - index=namesLength; - } - els[index]=el; - } - } else if ( "id".equals(name) && value.equals(id) ) { - if (index!=2) { - index=namesLength; - } - els[index]=el; - } - } - //For an element namespace search for importants - if ((elementIndex==3)&&( - el.getAttribute("OriginalRequestID").equals(id) || - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[3]=el; - } else if ((elementIndex==4)&&( - el.getAttribute("AssertionID").equals(id))) { - els[4]=el; - } else if ((elementIndex==5)&&( - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[5]=el; - } - return 0; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java index 6eae527a570..d06a41ffd20 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java @@ -2,82 +2,80 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; - /** - * This {@link org.xml.sax.ErrorHandler} does absulutely nothing but logging + * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but log * the events. * * @author Christian Geuer-Pollmann */ public class IgnoreAllErrorHandler implements ErrorHandler { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - IgnoreAllErrorHandler.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName()); - /** Field throwExceptions */ - static final boolean warnOnExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); + /** Field throwExceptions */ + private static final boolean warnOnExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); - /** Field throwExceptions */ - static final boolean throwExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); + /** Field throwExceptions */ + private static final boolean throwExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); - /** @inheritDoc */ - public void warning(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void warning(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); } - - - /** @inheritDoc */ - public void error(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.SEVERE, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; } + } - - /** @inheritDoc */ - public void fatalError(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void error(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.SEVERE, "", ex); } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } + + + /** @inheritDoc */ + public void fatalError(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); + } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java new file mode 100644 index 00000000000..242e80ff6e9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java @@ -0,0 +1,132 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.XMLConstants; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import javax.xml.xpath.XPathFactoryConfigurationException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation for XPath evaluation that uses the JDK API. + */ +public class JDKXPathAPI implements XPathAPI { + + private XPathFactory xpf; + + private String xpathStr; + + private XPathExpression xpathExpression; + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN); + return result.booleanValue(); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpathExpression = null; + xpf = null; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java new file mode 100644 index 00000000000..98c1872898a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java @@ -0,0 +1,37 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return a JDKXPathAPI instance. + */ +public class JDKXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new JDKXPathAPI(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java index 540c722f45c..cf55f4088ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -33,8 +35,8 @@ import java.io.InputStream; */ public class JavaUtils { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(JavaUtils.class.getName()); private JavaUtils() { @@ -45,7 +47,7 @@ public class JavaUtils { * Method getBytesFromFile * * @param fileName - * @return the bytes readed from the file + * @return the bytes read from the file * * @throws FileNotFoundException * @throws IOException @@ -55,9 +57,11 @@ public class JavaUtils { byte refBytes[] = null; - FileInputStream fisRef = new FileInputStream(fileName); + FileInputStream fisRef = null; + UnsyncByteArrayOutputStream baos = null; try { - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); + fisRef = new FileInputStream(fileName); + baos = new UnsyncByteArrayOutputStream(); byte buf[] = new byte[1024]; int len; @@ -67,7 +71,12 @@ public class JavaUtils { refBytes = baos.toByteArray(); } finally { - fisRef.close(); + if (baos != null) { + baos.close(); + } + if (fisRef != null) { + fisRef.close(); + } } return refBytes; @@ -80,7 +89,6 @@ public class JavaUtils { * @param bytes */ public static void writeBytesToFilename(String filename, byte[] bytes) { - FileOutputStream fos = null; try { if (filename != null && bytes != null) { @@ -91,13 +99,19 @@ public class JavaUtils { fos.write(bytes); fos.close(); } else { - log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + } } } catch (IOException ex) { if (fos != null) { try { fos.close(); - } catch (IOException ioe) {} + } catch (IOException ioe) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe); + } + } } } } @@ -107,25 +121,28 @@ public class JavaUtils { * returns them as a byte array. * * @param inputStream - * @return the bytes readed from the stream + * @return the bytes read from the stream * * @throws FileNotFoundException * @throws IOException */ - public static byte[] getBytesFromStream(InputStream inputStream) - throws IOException { + public static byte[] getBytesFromStream(InputStream inputStream) throws IOException { + UnsyncByteArrayOutputStream baos = null; - byte refBytes[] = null; + byte[] retBytes = null; + try { + baos = new UnsyncByteArrayOutputStream(); + byte buf[] = new byte[4 * 1024]; + int len; - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int len; - - while ((len = inputStream.read(buf)) > 0) { - baos.write(buf, 0, len); + while ((len = inputStream.read(buf)) > 0) { + baos.write(buf, 0, len); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); } - refBytes = baos.toByteArray(); - return refBytes; + return retBytes; } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java index 66a587511e8..1ab91701b6a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java @@ -2,573 +2,473 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - - import java.io.IOException; import java.io.StringReader; - -/** - * - * @author $Author: mullan $ - */ public class RFC2253Parser { + /** + * Method rfc2253toXMLdsig + * + * @param dn + * @return normalized string + */ + public static String rfc2253toXMLdsig(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, true); - /** {@link java.util.logging} logging facility */ - /* static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(RFC2253Parser.class.getName()); - */ + return rfctoXML(normalized); + } - static boolean _TOXML = true; + /** + * Method xmldsigtoRFC2253 + * + * @param dn + * @return normalized string + */ + public static String xmldsigtoRFC2253(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, false); - /** - * Method rfc2253toXMLdsig - * - * @param dn - * @return normalized string - * - */ - public static String rfc2253toXMLdsig(String dn) { + return xmltoRFC(normalized); + } - _TOXML = true; + /** + * Method normalize + * + * @param dn + * @return normalized string + */ + public static String normalize(String dn) { + return normalize(dn, true); + } - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); + /** + * Method normalize + * + * @param dn + * @param toXml + * @return normalized string + */ + public static String normalize(String dn, boolean toXml) { + //if empty string + if ((dn == null) || dn.equals("")) { + return ""; + } - return rfctoXML(normalized); - } + try { + String DN = semicolonToComma(dn); + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Method xmldsigtoRFC2253 - * - * @param dn - * @return normalized string - */ - public static String xmldsigtoRFC2253(String dn) { + //for name component + for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) { + l += countQuotes(DN, j, k); - _TOXML = false; + if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ","); - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); - - return xmltoRFC(normalized); - } - - /** - * Method normalize - * - * @param dn - * @return normalized string - */ - public static String normalize(String dn) { - - //if empty string - if ((dn == null) || dn.equals("")) { - return ""; - } - - try { - String _DN = semicolonToComma(dn); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; - - //for name component - for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) { - l += countQuotes(_DN, j, k); - - if ((k > 0) && (_DN.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseRDN(_DN.substring(i, k).trim()) + ","); - - i = k + 1; - l = 0; + i = k + 1; + l = 0; + } } - } - sb.append(parseRDN(trim(_DN.substring(i)))); + sb.append(parseRDN(trim(DN.substring(i)), toXml)); - return sb.toString(); - } catch (IOException ex) { - return dn; - } - } + return sb.toString(); + } catch (IOException ex) { + return dn; + } + } - /** - * Method parseRDN - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseRDN(String str) throws IOException { + /** + * Method parseRDN + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseRDN(String str, boolean toXml) throws IOException { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; + for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - for (int j = 0; (k = str.indexOf("+", j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+"); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseATAV(trim(str.substring(i, k))) + "+"); + i = k + 1; + l = 0; + } + } - i = k + 1; - l = 0; - } - } + sb.append(parseATAV(trim(str.substring(i)), toXml)); - sb.append(parseATAV(trim(str.substring(i)))); + return sb.toString(); + } - return sb.toString(); - } + /** + * Method parseATAV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseATAV(String str, boolean toXml) throws IOException { + int i = str.indexOf('='); - /** - * Method parseATAV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseATAV(String str) throws IOException { + if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { + return str; + } + String attrType = normalizeAT(str.substring(0, i)); + // only normalize if value is a String + String attrValue = null; + if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { + attrValue = str.substring(i + 1); + } else { + attrValue = normalizeV(str.substring(i + 1), toXml); + } - int i = str.indexOf("="); + return attrType + "=" + attrValue; - if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { - return str; - } - String attrType = normalizeAT(str.substring(0, i)); - // only normalize if value is a String - String attrValue = null; - if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { - attrValue = str.substring(i + 1); - } else { - attrValue = normalizeV(str.substring(i + 1)); - } + } - return attrType + "=" + attrValue; + /** + * Method normalizeAT + * + * @param str + * @return normalized string + */ + static String normalizeAT(String str) { - } + String at = str.toUpperCase().trim(); - /** - * Method normalizeAT - * - * @param str - * @return normalized string - */ - static String normalizeAT(String str) { + if (at.startsWith("OID")) { + at = at.substring(3); + } - String at = str.toUpperCase().trim(); + return at; + } - if (at.startsWith("OID")) { - at = at.substring(3); - } + /** + * Method normalizeV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String normalizeV(String str, boolean toXml) throws IOException { + String value = trim(str); - return at; - } + if (value.startsWith("\"")) { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(value.substring(1, value.length() - 1)); + int i = 0; + char c; - /** - * Method normalizeV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String normalizeV(String str) throws IOException { + while ((i = sr.read()) > -1) { + c = (char) i; - String value = trim(str); + //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 + if ((c == ',') || (c == '=') || (c == '+') || (c == '<') + || (c == '>') || (c == '#') || (c == ';')) { + sb.append('\\'); + } - if (value.startsWith("\"")) { - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(value.substring(1, - value.length() - 1)); - int i = 0; - char c; + sb.append(c); + } - for (; (i = sr.read()) > -1; ) { + value = trim(sb.toString()); + } + + if (toXml) { + if (value.startsWith("#")) { + value = '\\' + value; + } + } else { + if (value.startsWith("\\#")) { + value = value.substring(1); + } + } + + return value; + } + + /** + * Method rfctoXML + * + * @param string + * @return normalized string + */ + static String rfctoXML(String string) { + try { + String s = changeLess32toXML(string); + + return changeWStoXML(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method xmltoRFC + * + * @param string + * @return normalized string + */ + static String xmltoRFC(String string) { + try { + String s = changeLess32toRFC(string); + + return changeWStoRFC(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method changeLess32toRFC + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toRFC(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; + + while ((i = sr.read()) > -1) { c = (char) i; - //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 - if ((c == ',') || (c == '=') || (c == '+') || (c == '<') - || (c == '>') || (c == '#') || (c == ';')) { - sb.append('\\'); - } + if (c == '\\') { + sb.append(c); - sb.append(c); - } + char c1 = (char) sr.read(); + char c2 = (char) sr.read(); - value = trim(sb.toString()); - } - - if (_TOXML == true) { - if (value.startsWith("#")) { - value = '\\' + value; - } - } else { - if (value.startsWith("\\#")) { - value = value.substring(1); - } - } - - return value; - } - - /** - * Method rfctoXML - * - * @param string - * @return normalized string - */ - static String rfctoXML(String string) { - - try { - String s = changeLess32toXML(string); - - return changeWStoXML(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method xmltoRFC - * - * @param string - * @return normalized string - */ - static String xmltoRFC(String string) { - - try { - String s = changeLess32toRFC(string); - - return changeWStoRFC(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method changeLess32toRFC - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toRFC(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - sb.append(c); - - char c1 = (char) sr.read(); - char c2 = (char) sr.read(); - - //65 (A) 97 (a) - if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) + //65 (A) 97 (a) + if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) && (((c2 >= 48) && (c2 <= 57)) || ((c2 >= 65) && (c2 <= 70)) || ((c2 >= 97) && (c2 <= 102)))) { - char ch = (char) Byte.parseByte("" + c1 + c2, 16); + char ch = (char) Byte.parseByte("" + c1 + c2, 16); - sb.append(ch); + sb.append(ch); + } else { + sb.append(c1); + sb.append(c2); + } } else { - sb.append(c1); - sb.append(c2); + sb.append(c); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeLess32toXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toXML(String string) throws IOException { + /** + * Method changeLess32toXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - - for (; (i = sr.read()) > -1; ) { - if (i < 32) { - sb.append('\\'); - sb.append(Integer.toHexString(i)); - } else { - sb.append((char) i); - } - } - - return sb.toString(); - } - - /** - * Method changeWStoXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeWStoXML(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - char c1 = (char) sr.read(); - - if (c1 == ' ') { - sb.append('\\'); - - String s = "20"; - - sb.append(s); + while ((i = sr.read()) > -1) { + if (i < 32) { + sb.append('\\'); + sb.append(Integer.toHexString(i)); } else { - sb.append('\\'); - sb.append(c1); + sb.append((char) i); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeWStoRFC - * - * @param string - * @return normalized string - */ - static String changeWStoRFC(String string) { + /** + * Method changeWStoXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeWStoXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; - StringBuffer sb = new StringBuffer(); - int i = 0; - int k; + while ((i = sr.read()) > -1) { + c = (char) i; - for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { - sb.append(trim(string.substring(i, k)) + "\\ "); + if (c == '\\') { + char c1 = (char) sr.read(); - i = k + 3; - } + if (c1 == ' ') { + sb.append('\\'); - sb.append(string.substring(i)); + String s = "20"; - return sb.toString(); - } + sb.append(s); + } else { + sb.append('\\'); + sb.append(c1); + } + } else { + sb.append(c); + } + } - /** - * Method semicolonToComma - * - * @param str - * @return normalized string - */ - static String semicolonToComma(String str) { - return removeWSandReplace(str, ";", ","); - } + return sb.toString(); + } - /** - * Method removeWhiteSpace - * - * @param str - * @param symbol - * @return normalized string - */ - static String removeWhiteSpace(String str, String symbol) { - return removeWSandReplace(str, symbol, symbol); - } + /** + * Method changeWStoRFC + * + * @param string + * @return normalized string + */ + static String changeWStoRFC(String string) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int k; - /** - * Method removeWSandReplace - * - * @param str - * @param symbol - * @param replace - * @return normalized string - */ - static String removeWSandReplace(String str, String symbol, String replace) { + for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { + sb.append(trim(string.substring(i, k)) + "\\ "); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; + i = k + 3; + } - for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + sb.append(string.substring(i)); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(trim(str.substring(i, k)) + replace); + return sb.toString(); + } - i = k + 1; - l = 0; - } - } + /** + * Method semicolonToComma + * + * @param str + * @return normalized string + */ + static String semicolonToComma(String str) { + return removeWSandReplace(str, ";", ","); + } - sb.append(trim(str.substring(i))); + /** + * Method removeWhiteSpace + * + * @param str + * @param symbol + * @return normalized string + */ + static String removeWhiteSpace(String str, String symbol) { + return removeWSandReplace(str, symbol, symbol); + } - return sb.toString(); - } + /** + * Method removeWSandReplace + * + * @param str + * @param symbol + * @param replace + * @return normalized string + */ + static String removeWSandReplace(String str, String symbol, String replace) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Returns the number of Quotation from i to j - * - * @param s - * @param i - * @param j - * @return number of quotes - */ - private static int countQuotes(String s, int i, int j) { + for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - int k = 0; + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(trim(str.substring(i, k)) + replace); - for (int l = i; l < j; l++) { - if (s.charAt(l) == '"') { - k++; - } - } + i = k + 1; + l = 0; + } + } - return k; - } + sb.append(trim(str.substring(i))); - //only for the end of a space character occurring at the end of the string from rfc2253 + return sb.toString(); + } - /** - * Method trim - * - * @param str - * @return the string - */ - static String trim(String str) { + /** + * Returns the number of Quotation from i to j + * + * @param s + * @param i + * @param j + * @return number of quotes + */ + private static int countQuotes(String s, int i, int j) { + int k = 0; - String trimed = str.trim(); - int i = str.indexOf(trimed) + trimed.length(); + for (int l = i; l < j; l++) { + if (s.charAt(l) == '"') { + k++; + } + } - if ((str.length() > i) && trimed.endsWith("\\") - &&!trimed.endsWith("\\\\")) { - if (str.charAt(i) == ' ') { + return k; + } + + //only for the end of a space character occurring at the end of the string from rfc2253 + + /** + * Method trim + * + * @param str + * @return the string + */ + static String trim(String str) { + + String trimed = str.trim(); + int i = str.indexOf(trimed) + trimed.length(); + + if ((str.length() > i) && trimed.endsWith("\\") + && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) { trimed = trimed + " "; - } - } + } - return trimed; - } + return trimed; + } - /** - * Method main - * - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - - testToXML("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToXML("CN=Steve Kille , O=Isode Limited,C=GB"); - testToXML("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ "); - testToXML("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToXML("CN=Before\\0DAfter,O=Test,C=GB"); - testToXML("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToXML("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToXML(test7); - } - - testToRFC("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToRFC("CN=Steve Kille , O=Isode Limited,C=GB"); - testToRFC("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 "); - testToRFC("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToRFC("CN=Before\\12After,O=Test,C=GB"); - testToRFC("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToRFC("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToRFC(test7); - } - } - - /** Field i */ - static int counter = 0; - - /** - * Method test - * - * @param st - */ - static void testToXML(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + rfc2253toXMLdsig(st)); - System.out.println(""); - } - - /** - * Method testToRFC - * - * @param st - */ - static void testToRFC(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + xmldsigtoRFC2253(st)); - System.out.println(""); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java new file mode 100644 index 00000000000..dffcd89f47b --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java @@ -0,0 +1,70 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Class SignatureElementProxy + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public abstract class Signature11ElementProxy extends ElementProxy { + + protected Signature11ElementProxy() { + }; + + /** + * Constructor Signature11ElementProxy + * + * @param doc + */ + public Signature11ElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignature11Space(this.doc, this.getBaseLocalName()); + } + + /** + * Constructor Signature11ElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Signature11ElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpec11NS; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java index d49cc676acf..3a97bd3d411 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java @@ -2,70 +2,69 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * Class SignatureElementProxy * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ + * @author $Author: coheigea $ */ public abstract class SignatureElementProxy extends ElementProxy { - protected SignatureElementProxy() { - }; - /** - * Constructor SignatureElementProxy - * - * @param doc - */ - public SignatureElementProxy(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - this._doc = doc; - this._constructionElement = XMLUtils.createElementInSignatureSpace(this._doc, - this.getBaseLocalName()); - } + protected SignatureElementProxy() { + }; - /** - * Constructor SignatureElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SignatureElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); + /** + * Constructor SignatureElementProxy + * + * @param doc + */ + public SignatureElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - } + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName()); + } - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } + /** + * Constructor SignatureElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java index 068d523bd64..c8f5747d396 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -30,53 +32,50 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; * */ public class SignerOutputStream extends ByteArrayOutputStream { + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignerOutputStream.class.getName()); + final SignatureAlgorithm sa; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (SignerOutputStream.class.getName()); /** * @param sa */ public SignerOutputStream(SignatureAlgorithm sa) { - this.sa=sa; + this.sa = sa; } /** @inheritDoc */ public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); try { sa.update(arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(int arg0) { - super.write(arg0); try { sa.update((byte)arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(byte[] arg0, int arg1, int arg2) { - super.write(arg0, arg1, arg2); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } try { - sa.update(arg0,arg1,arg2); + sa.update(arg0, arg1, arg2); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java index e9a7935e7ea..f424dd51b74 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -24,75 +26,73 @@ import java.io.IOException; import java.io.OutputStream; /** - * A class that buffers writte without synchronize its methods + * A class that buffers without synchronizing its methods * @author raul - * */ public class UnsyncBufferedOutputStream extends OutputStream { - final OutputStream out; + static final int size = 8*1024; - final byte[] buf; - static final int size=8*1024; - private static ThreadLocal bufCahce = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[size]; + private int pointer = 0; + private final OutputStream out; + + private final byte[] buf; + + /** + * Creates a buffered output stream without synchronization + * @param out the outputstream to buffer + */ + public UnsyncBufferedOutputStream(OutputStream out) { + buf = new byte[size]; + this.out = out; + } + + /** @inheritDoc */ + public void write(byte[] arg0) throws IOException { + write(arg0, 0, arg0.length); + } + + /** @inheritDoc */ + public void write(byte[] arg0, int arg1, int len) throws IOException { + int newLen = pointer+len; + if (newLen > size) { + flushBuffer(); + if (len > size) { + out.write(arg0, arg1,len); + return; + } + newLen = len; } - }; - int pointer=0; - /** - * Creates a buffered output stream without synchronization - * @param out the outputstream to buffer - */ - public UnsyncBufferedOutputStream(OutputStream out) { - buf=bufCahce.get(); - this.out=out; + System.arraycopy(arg0, arg1, buf, pointer, len); + pointer = newLen; + } + + private void flushBuffer() throws IOException { + if (pointer > 0) { + out.write(buf, 0, pointer); } + pointer = 0; - /** @inheritDoc */ - public void write(byte[] arg0) throws IOException { - write(arg0,0,arg0.length); + } + + /** @inheritDoc */ + public void write(int arg0) throws IOException { + if (pointer >= size) { + flushBuffer(); } + buf[pointer++] = (byte)arg0; - /** @inheritDoc */ - public void write(byte[] arg0, int arg1, int len) throws IOException { - int newLen=pointer+len; - if (newLen> size) { - flushBuffer(); - if (len>size) { - out.write(arg0,arg1,len); - return; - } - newLen=len; - } - System.arraycopy(arg0,arg1,buf,pointer,len); - pointer=newLen; - } + } - private final void flushBuffer() throws IOException { - if (pointer>0) - out.write(buf,0,pointer); - pointer=0; + /** @inheritDoc */ + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } - } - - /** @inheritDoc */ - public void write(int arg0) throws IOException { - if (pointer>= size) { - flushBuffer(); - } - buf[pointer++]=(byte)arg0; - - } - - /** @inheritDoc */ - public void flush() throws IOException { - flushBuffer(); - out.flush(); - } - - /** @inheritDoc */ - public void close() throws IOException { - flush(); - } + /** @inheritDoc */ + public void close() throws IOException { + flush(); + out.close(); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java index 2a2f7ddbd03..e6f3ea7c258 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2010 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -28,22 +30,21 @@ import java.io.OutputStream; * */ public class UnsyncByteArrayOutputStream extends OutputStream { + private static final int INITIAL_SIZE = 8192; - private static ThreadLocal bufCache = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[INITIAL_SIZE]; - } - }; private byte[] buf; private int size = INITIAL_SIZE; private int pos = 0; public UnsyncByteArrayOutputStream() { - buf = bufCache.get(); + buf = new byte[INITIAL_SIZE]; } public void write(byte[] arg0) { + if ((Integer.MAX_VALUE - pos) < arg0.length) { + throw new OutOfMemoryError(); + } int newPos = pos + arg0.length; if (newPos > size) { expandSize(newPos); @@ -53,6 +54,9 @@ public class UnsyncByteArrayOutputStream extends OutputStream { } public void write(byte[] arg0, int arg1, int arg2) { + if ((Integer.MAX_VALUE - pos) < arg2) { + throw new OutOfMemoryError(); + } int newPos = pos + arg2; if (newPos > size) { expandSize(newPos); @@ -62,6 +66,9 @@ public class UnsyncByteArrayOutputStream extends OutputStream { } public void write(int arg0) { + if ((Integer.MAX_VALUE - pos) == 0) { + throw new OutOfMemoryError(); + } int newPos = pos + 1; if (newPos > size) { expandSize(newPos); @@ -82,7 +89,11 @@ public class UnsyncByteArrayOutputStream extends OutputStream { private void expandSize(int newPos) { int newSize = size; while (newPos > newSize) { - newSize = newSize<<2; + newSize = newSize << 1; + // Deal with overflow + if (newSize < 0) { + newSize = Integer.MAX_VALUE; + } } byte newBuf[] = new byte[newSize]; System.arraycopy(buf, 0, newBuf, 0, pos); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java index dc01897cca5..620b6735b8f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java @@ -2,35 +2,34 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Set; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -42,10 +41,9 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; - - /** * DOM and XML accessibility and comfort functions. * @@ -53,28 +51,31 @@ import org.w3c.dom.Text; */ public class XMLUtils { - private static boolean ignoreLineBreaks = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"); - } - }); + private static boolean ignoreLineBreaks = + AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks")); + } + }).booleanValue(); private static volatile String dsPrefix = "ds"; + private static volatile String ds11Prefix = "dsig11"; private static volatile String xencPrefix = "xenc"; + private static volatile String xenc11Prefix = "xenc11"; - private static final java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLUtils.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLUtils.class.getName()); - /** - * Constructor XMLUtils - * - */ - private XMLUtils() { - // we don't allow instantiation - } + /** + * Constructor XMLUtils + * + */ + private XMLUtils() { + // we don't allow instantiation + } /** * Set the prefix for the digital signature namespace @@ -84,6 +85,14 @@ public class XMLUtils { dsPrefix = prefix; } + /** + * Set the prefix for the digital signature 1.1 namespace + * @param prefix the new prefix for the digital signature 1.1 namespace + */ + public static void setDs11Prefix(String prefix) { + ds11Prefix = prefix; + } + /** * Set the prefix for the encryption namespace * @param prefix the new prefix for the encryption namespace @@ -92,197 +101,256 @@ public class XMLUtils { xencPrefix = prefix; } - public static Element getNextElement(Node el) { - while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) { - el=el.getNextSibling(); - } - return (Element)el; + /** + * Set the prefix for the encryption namespace 1.1 + * @param prefix the new prefix for the encryption namespace 1.1 + */ + public static void setXenc11Prefix(String prefix) { + xenc11Prefix = prefix; + } - } + public static Element getNextElement(Node el) { + Node node = el; + while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) { + node = node.getNextSibling(); + } + return (Element)node; + } - /** - * @param rootNode - * @param result - * @param exclude - * @param com wheather comments or not - */ - public static void getSet(Node rootNode,Set result,Node exclude ,boolean com) { - if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){ - return; - } - getSetRec(rootNode,result,exclude,com); - } + /** + * @param rootNode + * @param result + * @param exclude + * @param com whether comments or not + */ + public static void getSet(Node rootNode, Set result, Node exclude, boolean com) { + if ((exclude != null) && isDescendantOrSelf(exclude, rootNode)) { + return; + } + getSetRec(rootNode, result, exclude, com); + } - @SuppressWarnings("fallthrough") - static final void getSetRec(final Node rootNode,final Set result, - final Node exclude ,final boolean com) { - //Set result = new HashSet(); - if (rootNode==exclude) { - return; - } - switch (rootNode.getNodeType()) { - case Node.ELEMENT_NODE: - result.add(rootNode); - Element el=(Element)rootNode; - if (el.hasAttributes()) { - NamedNodeMap nl = ((Element)rootNode).getAttributes(); - for (int i=0;i result, + final Node exclude, final boolean com) { + if (rootNode == exclude) { + return; + } + switch (rootNode.getNodeType()) { + case Node.ELEMENT_NODE: + result.add(rootNode); + Element el = (Element)rootNode; + if (el.hasAttributes()) { + NamedNodeMap nl = el.getAttributes(); + for (int i = 0;i < nl.getLength(); i++) { + result.add(nl.item(i)); } - //no return keep working - ignore fallthrough warning - case Node.DOCUMENT_NODE: - for (Node r=rootNode.getFirstChild();r!=null;r=r.getNextSibling()){ - if (r.getNodeType()==Node.TEXT_NODE) { - result.add(r); - while ((r!=null) && (r.getNodeType()==Node.TEXT_NODE)) { - r=r.getNextSibling(); - } - if (r==null) - return; - } - getSetRec(r,result,exclude,com); - } - return; - case Node.COMMENT_NODE: - if (com) { - result.add(rootNode); - } - return; - case Node.DOCUMENT_TYPE_NODE: - return; - default: - result.add(rootNode); - } - return; - } + } + //no return keep working + case Node.DOCUMENT_NODE: + for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) { + if (r.getNodeType() == Node.TEXT_NODE) { + result.add(r); + while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) { + r = r.getNextSibling(); + } + if (r == null) { + return; + } + } + getSetRec(r, result, exclude, com); + } + return; + case Node.COMMENT_NODE: + if (com) { + result.add(rootNode); + } + return; + case Node.DOCUMENT_TYPE_NODE: + return; + default: + result.add(rootNode); + } + } - /** - * Outputs a DOM tree to an {@link OutputStream}. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - */ - public static void outputDOM(Node contextNode, OutputStream os) { - XMLUtils.outputDOM(contextNode, os, false); - } + /** + * Outputs a DOM tree to an {@link OutputStream}. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + */ + public static void outputDOM(Node contextNode, OutputStream os) { + XMLUtils.outputDOM(contextNode, os, false); + } - /** - * Outputs a DOM tree to an {@link OutputStream}. If an Exception is - * thrown during execution, it's StackTrace is output to System.out, but the - * Exception is not re-thrown. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - * @param addPreamble - */ - public static void outputDOM(Node contextNode, OutputStream os, - boolean addPreamble) { + /** + * Outputs a DOM tree to an {@link OutputStream}. If an Exception is + * thrown during execution, it's StackTrace is output to System.out, but the + * Exception is not re-thrown. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + * @param addPreamble + */ + public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) { + try { + if (addPreamble) { + os.write("\n".getBytes("UTF-8")); + } - try { - if (addPreamble) { - os.write("\n".getBytes()); - } + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) {} - catch (InvalidCanonicalizerException ex) { - ex.printStackTrace(); - } catch (CanonicalizationException ex) { - ex.printStackTrace(); - } - } + /** + * Serializes the contextNode into the OutputStream, but + * suppresses all Exceptions. + *
    + * NOTE: This should only be used for debugging purposes, + * NOT in a production environment; this method ignores all exceptions, + * so you won't notice if something goes wrong. If you're asking what is to + * be used in a production environment, simply use the code inside the + * try{} statement, but handle the Exceptions appropriately. + * + * @param contextNode + * @param os + */ + public static void outputDOMc14nWithComments(Node contextNode, OutputStream os) { + try { + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } + } - /** - * Serializes the contextNode into the OutputStream, but - * supresses all Exceptions. - *
    - * NOTE: This should only be used for debugging purposes, - * NOT in a production environment; this method ignores all exceptions, - * so you won't notice if something goes wrong. If you're asking what is to - * be used in a production environment, simply use the code inside the - * try{} statement, but handle the Exceptions appropriately. - * - * @param contextNode - * @param os - */ - public static void outputDOMc14nWithComments(Node contextNode, - OutputStream os) { + /** + * Method getFullTextChildrenFromElement + * + * @param element + * @return the string of children + */ + public static String getFullTextChildrenFromElement(Element element) { + StringBuilder sb = new StringBuilder(); - try { - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) { + Node child = element.getFirstChild(); + while (child != null) { + if (child.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text)child).getData()); + } + child = child.getNextSibling(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (InvalidCanonicalizerException ex) { + return sb.toString(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (CanonicalizationException ex) { + /** + * Creates an Element in the XML Signature specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignatureSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - // throw new RuntimeException(ex.getMessage()); - } - } + if ((dsPrefix == null) || (dsPrefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpecNS, elementName); + } + return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName); + } + /** + * Creates an Element in the XML Signature 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignature11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - /** - * Method getFullTextChildrenFromElement - * - * @param element - * @return the string of chi;ds - */ - public static String getFullTextChildrenFromElement(Element element) { + if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpec11NS, elementName); + } + return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName); + } - StringBuffer sb = new StringBuffer(); - NodeList children = element.getChildNodes(); - int iMax = children.getLength(); + /** + * Creates an Element in the XML Encryption specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryptionSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - for (int i = 0; i < iMax; i++) { - Node curr = children.item(i); + if ((xencPrefix == null) || (xencPrefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName + ); + } - if (curr.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) curr).getData()); - } - } + /** + * Creates an Element in the XML Encryption 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryption11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - return sb.toString(); - } - - static Map namePrefixes=new HashMap(); - - /** - * Creates an Element in the XML Signature specification namespace. - * - * @param doc the factory Document - * @param elementName the local name of the Element - * @return the Element - */ - public static Element createElementInSignatureSpace(Document doc, - String elementName) { - - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - if ((dsPrefix == null) || (dsPrefix.length() == 0)) { - return doc.createElementNS(Constants.SignatureSpecNS, elementName); - } - String namePrefix= namePrefixes.get(elementName); - if (namePrefix==null) { - StringBuffer tag=new StringBuffer(dsPrefix); - tag.append(':'); - tag.append(elementName); - namePrefix=tag.toString(); - namePrefixes.put(elementName,namePrefix); - } - return doc.createElementNS(Constants.SignatureSpecNS, namePrefix); - } + if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName + ); + } /** * Returns true if the element is in XML Signature namespace and the local @@ -290,10 +358,11 @@ public class XMLUtils { * * @param element * @param localName - * @return true if the element is in XML Signature namespace and the local name equals the supplied one + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one */ public static boolean elementIsInSignatureSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } @@ -301,48 +370,82 @@ public class XMLUtils { && element.getLocalName().equals(localName); } + /** + * Returns true if the element is in XML Signature 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one + */ + public static boolean elementIsInSignature11Space(Element element, String localName) { + if (element == null) { + return false; + } + + return Constants.SignatureSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } + /** * Returns true if the element is in XML Encryption namespace and the local * name equals the supplied one. * * @param element * @param localName - * @return true if the element is in XML Encryption namespace and the local name equals the supplied one + * @return true if the element is in XML Encryption namespace and the local name + * equals the supplied one */ public static boolean elementIsInEncryptionSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI()) && element.getLocalName().equals(localName); } - /** - * This method returns the owner document of a particular node. - * This method is necessary because it always returns a - * {@link Document}. {@link Node#getOwnerDocument} returns null - * if the {@link Node} is a {@link Document}. - * - * @param node - * @return the owner document of the node - */ - public static Document getOwnerDocument(Node node) { + /** + * Returns true if the element is in XML Encryption 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Encryption 1.1 namespace and the local name + * equals the supplied one + */ + public static boolean elementIsInEncryption11Space(Element element, String localName) { + if (element == null){ + return false; + } + return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } - if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { + /** + * This method returns the owner document of a particular node. + * This method is necessary because it always returns a + * {@link Document}. {@link Node#getOwnerDocument} returns null + * if the {@link Node} is a {@link Document}. + * + * @param node + * @return the owner document of the node + */ + public static Document getOwnerDocument(Node node) { + if (node.getNodeType() == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { return node.getOwnerDocument(); - } catch (NullPointerException npe) { + } catch (NullPointerException npe) { throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + npe.getMessage() + "\""); - } - - } + } + } /** - * This method returns the first non-null owner document of the Node's in this Set. + * This method returns the first non-null owner document of the Nodes in this Set. * This method is necessary because it always returns a * {@link Document}. {@link Node#getOwnerDocument} returns null * if the {@link Node} is a {@link Document}. @@ -351,23 +454,23 @@ public class XMLUtils { * @return the owner document */ public static Document getOwnerDocument(Set xpathNodeSet) { - NullPointerException npe = null; - for (Node node : xpathNodeSet) { - int nodeType =node.getNodeType(); - if (nodeType == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { - if (nodeType==Node.ATTRIBUTE_NODE) { + NullPointerException npe = null; + for (Node node : xpathNodeSet) { + int nodeType = node.getNodeType(); + if (nodeType == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { + if (nodeType == Node.ATTRIBUTE_NODE) { return ((Attr)node).getOwnerElement().getOwnerDocument(); - } - return node.getOwnerDocument(); - } catch (NullPointerException e) { - npe = e; - } + } + return node.getOwnerDocument(); + } catch (NullPointerException e) { + npe = e; + } + } - } - throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + (npe == null ? "" : npe.getMessage()) + "\""); } @@ -380,165 +483,161 @@ public class XMLUtils { * @param namespace * @return the element. */ - public static Element createDSctx(Document doc, String prefix, - String namespace) { + public static Element createDSctx(Document doc, String prefix, String namespace) { + if ((prefix == null) || (prefix.trim().length() == 0)) { + throw new IllegalArgumentException("You must supply a prefix"); + } - if ((prefix == null) || (prefix.trim().length() == 0)) { - throw new IllegalArgumentException("You must supply a prefix"); - } + Element ctx = doc.createElementNS(null, "namespaceContext"); - Element ctx = doc.createElementNS(null, "namespaceContext"); + ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace); - ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), - namespace); - - return ctx; + return ctx; } - /** - * Method addReturnToElement - * - * @param e - */ - public static void addReturnToElement(Element e) { + /** + * Method addReturnToElement + * + * @param e + */ + public static void addReturnToElement(Element e) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.appendChild(doc.createTextNode("\n")); + } + } - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.appendChild(doc.createTextNode("\n")); - } - } + public static void addReturnToElement(Document doc, HelperNodeList nl) { + if (!ignoreLineBreaks) { + nl.appendChild(doc.createTextNode("\n")); + } + } - public static void addReturnToElement(Document doc, HelperNodeList nl) { - if (!ignoreLineBreaks) { - nl.appendChild(doc.createTextNode("\n")); - } - } + public static void addReturnBeforeChild(Element e, Node child) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.insertBefore(doc.createTextNode("\n"), child); + } + } - public static void addReturnBeforeChild(Element e, Node child) { - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.insertBefore(doc.createTextNode("\n"), child); - } - } + /** + * Method convertNodelistToSet + * + * @param xpathNodeSet + * @return the set with the nodelist + */ + public static Set convertNodelistToSet(NodeList xpathNodeSet) { + if (xpathNodeSet == null) { + return new HashSet(); + } - /** - * Method convertNodelistToSet - * - * @param xpathNodeSet - * @return the set with the nodelist - */ - public static Set convertNodelistToSet(NodeList xpathNodeSet) { + int length = xpathNodeSet.getLength(); + Set set = new HashSet(length); - if (xpathNodeSet == null) { - return new HashSet(); - } + for (int i = 0; i < length; i++) { + set.add(xpathNodeSet.item(i)); + } - int length = xpathNodeSet.getLength(); - Set set = new HashSet(length); + return set; + } - for (int i = 0; i < length; i++) { - set.add(xpathNodeSet.item(i)); - } + /** + * This method spreads all namespace attributes in a DOM document to their + * children. This is needed because the XML Signature XPath transform + * must evaluate the XPath against all nodes in the input, even against + * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are + * not fully visible in the Xalan XPath model, so we have to do this by + * hand in DOM spaces so that the nodes become visible in XPath space. + * + * @param doc + * @see + * Namespace axis resolution is not XPath compliant + */ + public static void circumventBug2650(Document doc) { - return set; - } + Element documentElement = doc.getDocumentElement(); + // if the document element has no xmlns definition, we add xmlns="" + Attr xmlnsAttr = + documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - /** - * This method spreads all namespace attributes in a DOM document to their - * children. This is needed because the XML Signature XPath transform - * must evaluate the XPath against all nodes in the input, even against - * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are - * not fully visible in the Xalan XPath model, so we have to do this by - * hand in DOM spaces so that the nodes become visible in XPath space. - * - * @param doc - * @see Namespace axis resolution is not XPath compliant - */ - public static void circumventBug2650(Document doc) { + if (xmlnsAttr == null) { + documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); + } - Element documentElement = doc.getDocumentElement(); + XMLUtils.circumventBug2650internal(doc); + } - // if the document element has no xmlns definition, we add xmlns="" - Attr xmlnsAttr = - documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - - if (xmlnsAttr == null) { - documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); - } - - XMLUtils.circumventBug2650internal(doc); - } - - /** - * This is the work horse for {@link #circumventBug2650}. - * - * @param node - * @see Namespace axis resolution is not XPath compliant - */ - @SuppressWarnings("fallthrough") - private static void circumventBug2650internal(Node node) { - Node parent=null; - Node sibling=null; - final String namespaceNs=Constants.NamespaceSpecNS; - do { - switch (node.getNodeType()) { - case Node.ELEMENT_NODE : - Element element = (Element) node; - if (!element.hasChildNodes()) - break; - if (element.hasAttributes()) { - NamedNodeMap attributes = element.getAttributes(); - int attributesLength = attributes.getLength(); - - for (Node child = element.getFirstChild(); child!=null; - child=child.getNextSibling()) { - - if (child.getNodeType() != Node.ELEMENT_NODE) { - continue; + /** + * This is the work horse for {@link #circumventBug2650}. + * + * @param node + * @see + * Namespace axis resolution is not XPath compliant + */ + @SuppressWarnings("fallthrough") + private static void circumventBug2650internal(Node node) { + Node parent = null; + Node sibling = null; + final String namespaceNs = Constants.NamespaceSpecNS; + do { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + Element element = (Element) node; + if (!element.hasChildNodes()) { + break; } - Element childElement = (Element) child; + if (element.hasAttributes()) { + NamedNodeMap attributes = element.getAttributes(); + int attributesLength = attributes.getLength(); - for (int i = 0; i < attributesLength; i++) { - Attr currentAttr = (Attr) attributes.item(i); - if (namespaceNs!=currentAttr.getNamespaceURI()) - continue; - if (childElement.hasAttributeNS(namespaceNs, - currentAttr.getLocalName())) { - continue; + for (Node child = element.getFirstChild(); child!=null; + child = child.getNextSibling()) { + + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; } - childElement.setAttributeNS(namespaceNs, - currentAttr.getName(), - currentAttr.getNodeValue()); - + Element childElement = (Element) child; + for (int i = 0; i < attributesLength; i++) { + Attr currentAttr = (Attr) attributes.item(i); + if (!namespaceNs.equals(currentAttr.getNamespaceURI())) { + continue; + } + if (childElement.hasAttributeNS(namespaceNs, + currentAttr.getLocalName())) { + continue; + } + childElement.setAttributeNS(namespaceNs, + currentAttr.getName(), + currentAttr.getNodeValue()); + } + } } - } - } - case Node.ENTITY_REFERENCE_NODE : - case Node.DOCUMENT_NODE : - parent=node; - sibling=node.getFirstChild(); - break; - } - while ((sibling==null) && (parent!=null)) { - sibling=parent.getNextSibling(); - parent=parent.getParentNode(); - }; - if (sibling==null) { - return; - } + case Node.ENTITY_REFERENCE_NODE : + case Node.DOCUMENT_NODE : + parent = node; + sibling = node.getFirstChild(); + break; + } + while ((sibling == null) && (parent != null)) { + sibling = parent.getNextSibling(); + parent = parent.getParentNode(); + } + if (sibling == null) { + return; + } - node=sibling; - sibling=node.getNextSibling(); - } while (true); - } + node = sibling; + sibling = node.getNextSibling(); + } while (true); + } /** * @param sibling * @param nodeName * @param number - * @return nodes with the constrain + * @return nodes with the constraint */ public static Element selectDsNode(Node sibling, String nodeName, int number) { while (sibling != null) { @@ -554,6 +653,26 @@ public class XMLUtils { return null; } + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constraint + */ + public static Element selectDs11Node(Node sibling, String nodeName, int number) { + while (sibling != null) { + if (Constants.SignatureSpec11NS.equals(sibling.getNamespaceURI()) + && sibling.getLocalName().equals(nodeName)) { + if (number == 0){ + return (Element)sibling; + } + number--; + } + sibling = sibling.getNextSibling(); + } + return null; + } + /** * @param sibling * @param nodeName @@ -574,42 +693,61 @@ public class XMLUtils { return null; } - /** - * @param sibling - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectDsNodeText(Node sibling, String nodeName, int number) { - Node n=selectDsNode(sibling,nodeName,number); - if (n==null) { - return null; + + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDsNodeText(Node sibling, String nodeName, int number) { + Node n = selectDsNode(sibling,nodeName,number); + if (n == null) { + return null; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); } return (Text)n; - } + } - /** - * @param sibling - * @param uri - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { - Node n=selectNode(sibling,uri,nodeName,number); - if (n==null) { - return null; + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDs11NodeText(Node sibling, String nodeName, int number) { + Node n = selectDs11Node(sibling,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + + /** + * @param sibling + * @param uri + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { + Node n = selectNode(sibling,uri,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - return (Text)n; - } /** * @param sibling @@ -638,16 +776,25 @@ public class XMLUtils { * @return nodes with the constrain */ public static Element[] selectDsNodes(Node sibling, String nodeName) { - return selectNodes(sibling,Constants.SignatureSpecNS, nodeName); + return selectNodes(sibling, Constants.SignatureSpecNS, nodeName); + } + + /** + * @param sibling + * @param nodeName + * @return nodes with the constrain + */ + public static Element[] selectDs11Nodes(Node sibling, String nodeName) { + return selectNodes(sibling, Constants.SignatureSpec11NS, nodeName); } /** * @param sibling * @param uri * @param nodeName - * @return nodes with the constrain + * @return nodes with the constraint */ - public static Element[] selectNodes(Node sibling, String uri, String nodeName) { + public static Element[] selectNodes(Node sibling, String uri, String nodeName) { List list = new ArrayList(); while (sibling != null) { if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) @@ -659,73 +806,117 @@ public class XMLUtils { return list.toArray(new Element[list.size()]); } - /** - * @param signatureElement - * @param inputSet - * @return nodes with the constrain - */ + /** + * @param signatureElement + * @param inputSet + * @return nodes with the constrain + */ public static Set excludeNodeFromSet(Node signatureElement, Set inputSet) { - Set resultSet = new HashSet(); - Iterator iterator = inputSet.iterator(); + Set resultSet = new HashSet(); + Iterator iterator = inputSet.iterator(); - while (iterator.hasNext()) { + while (iterator.hasNext()) { Node inputNode = iterator.next(); - if (!XMLUtils - .isDescendantOrSelf(signatureElement, inputNode)) { - resultSet.add(inputNode); + if (!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)) { + resultSet.add(inputNode); } - } - return resultSet; - } + } + return resultSet; + } - /** - * Returns true if the descendantOrSelf is on the descendant-or-self axis - * of the context node. - * - * @param ctx - * @param descendantOrSelf - * @return true if the node is descendant - */ - static public boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + /** + * Method getStrFromNode + * + * @param xpathnode + * @return the string for the node. + */ + public static String getStrFromNode(Node xpathnode) { + if (xpathnode.getNodeType() == Node.TEXT_NODE) { + // we iterate over all siblings of the context node because eventually, + // the text is "polluted" with pi's or comments + StringBuilder sb = new StringBuilder(); - if (ctx == descendantOrSelf) { - return true; - } + for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); + currentSibling != null; + currentSibling = currentSibling.getNextSibling()) { + if (currentSibling.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text) currentSibling).getData()); + } + } - Node parent = descendantOrSelf; + return sb.toString(); + } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { + return ((Attr) xpathnode).getNodeValue(); + } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + return ((ProcessingInstruction) xpathnode).getNodeValue(); + } - while (true) { - if (parent == null) { - return false; - } + return null; + } - if (parent == ctx) { + /** + * Returns true if the descendantOrSelf is on the descendant-or-self axis + * of the context node. + * + * @param ctx + * @param descendantOrSelf + * @return true if the node is descendant + */ + public static boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + if (ctx == descendantOrSelf) { return true; - } + } - if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { - parent = ((Attr) parent).getOwnerElement(); - } else { - parent = parent.getParentNode(); - } - } - } + Node parent = descendantOrSelf; + + while (true) { + if (parent == null) { + return false; + } + + if (parent == ctx) { + return true; + } + + if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { + parent = ((Attr) parent).getOwnerElement(); + } else { + parent = parent.getParentNode(); + } + } + } public static boolean ignoreLineBreaks() { return ignoreLineBreaks; } /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no two Elements have ID Attributes that match the "value" - * argument, if this is the case then "false" is returned. Note that a - * return value of "true" does not necessarily mean that a matching Element - * has been found, just that no wrapping attack has been detected. + * Returns the attribute value for the attribute with the specified name. + * Returns null if there is no such attribute, or + * the empty string if the attribute value is empty. + * + *

    This works around a limitation of the DOM + * Element.getAttributeNode method, which does not distinguish + * between an unspecified attribute and an attribute with a value of + * "" (it returns "" for both cases). + * + * @param elem the element containing the attribute + * @param name the name of the attribute + * @return the attribute value (may be null if unspecified) */ - public static boolean protectAgainstWrappingAttack(Node startNode, - String value) - { + public static String getAttributeValue(Element elem, String name) { + Attr attr = elem.getAttributeNodeNS(null, name); + return (attr == null) ? null : attr.getValue(); + } + + /** + * This method is a tree-search to help prevent against wrapping attacks. It checks that no + * two Elements have ID Attributes that match the "value" argument, if this is the case then + * "false" is returned. Note that a return value of "true" does not necessarily mean that + * a matching Element has been found, just that no wrapping attack has been detected. + */ + public static boolean protectAgainstWrappingAttack(Node startNode, String value) { Node startParent = startNode.getParentNode(); Node processedNode = null; Element foundElement = null; @@ -780,15 +971,13 @@ public class XMLUtils { } /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no other Element than the given "knownElement" argument - * has an ID attribute that matches the "value" argument, which is the ID - * value of "knownElement". If this is the case then "false" is returned. + * This method is a tree-search to help prevent against wrapping attacks. It checks that no other + * Element than the given "knownElement" argument has an ID attribute that matches the "value" + * argument, which is the ID value of "knownElement". If this is the case then "false" is returned. */ - public static boolean protectAgainstWrappingAttack(Node startNode, - Element knownElement, - String value) - { + public static boolean protectAgainstWrappingAttack( + Node startNode, Element knownElement, String value + ) { Node startParent = startNode.getParentNode(); Node processedNode = null; @@ -805,9 +994,7 @@ public class XMLUtils { if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr)attributes.item(i); - if (attr.isId() && id.equals(attr.getValue()) - && se != knownElement) - { + if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) { log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!"); return false; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java new file mode 100644 index 00000000000..d5b55bac3f8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java @@ -0,0 +1,66 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.transform.TransformerException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An interface to abstract XPath evaluation + */ +public interface XPathAPI { + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException; + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException; + + /** + * Clear any context information from this object + */ + void clear(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java new file mode 100644 index 00000000000..3de6129b935 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java @@ -0,0 +1,71 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return an XPathAPI instance. If Xalan is available it returns XalanXPathAPI. If not, then + * it returns JDKXPathAPI. + */ +public abstract class XPathFactory { + + private static boolean xalanInstalled; + + static { + try { + Class funcTableClass = + ClassLoaderUtils.loadClass("com.sun.org.apache.xpath.internal.compiler.FunctionTable", XPathFactory.class); + if (funcTableClass != null) { + xalanInstalled = true; + } + } catch (Exception e) { + //ignore + } + } + + protected synchronized static boolean isXalanInstalled() { + return xalanInstalled; + } + + /** + * Get a new XPathFactory instance + */ + public static XPathFactory newInstance() { + if (!isXalanInstalled()) { + return new JDKXPathFactory(); + } + // Xalan is available + if (XalanXPathAPI.isInstalled()) { + return new XalanXPathFactory(); + } + // Some problem was encountered in fixing up the Xalan FunctionTable so fall back to the + // JDK implementation + return new JDKXPathFactory(); + } + + /** + * Get a new XPathAPI instance + */ + public abstract XPathAPI newXPathAPI(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java deleted file mode 100644 index dbee521c11e..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.utils; - - - -import javax.xml.transform.TransformerException; - -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.traversal.NodeIterator; - - - - -/** - * This class does the same as {@link com.sun.org.apache.xpath.internal.XPathAPI} except that the XPath strings - * are not supplied as Strings but as {@link Text}, {@link Attr}ibute or - * {ProcessingInstruction} nodes which contain the XPath string. This enables - * us to use the here() function. - *
    - * The methods in this class are convenience methods into the low-level XPath API. - * These functions tend to be a little slow, since a number of objects must be - * created for each evaluation. A faster way is to precompile the - * XPaths using the low-level API, and then just use the XPaths - * over and over. - * - * @author $Author: mullan $ - * @see XPath Specification - */ -public class XPathFuncHereAPI { - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode) throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - String str = getStrFromNode(xpathnode); - - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, PrefixResolver prefixResolver) - throws TransformerException { - - String str = getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string from the node - */ - private static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - return ((Text) xpathnode).getData(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return ""; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java new file mode 100644 index 00000000000..f9fab3033d8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java @@ -0,0 +1,210 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.SourceLocator; +import javax.xml.transform.TransformerException; + +import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; +import com.sun.org.apache.xml.internal.utils.PrefixResolver; +import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; +import com.sun.org.apache.xpath.internal.Expression; +import com.sun.org.apache.xpath.internal.XPath; +import com.sun.org.apache.xpath.internal.XPathContext; +import com.sun.org.apache.xpath.internal.compiler.FunctionTable; +import com.sun.org.apache.xpath.internal.objects.XObject; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation of XPathAPI using Xalan. This supports the "here()" function defined in the digital + * signature spec. + */ +public class XalanXPathAPI implements XPathAPI { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName()); + + private String xpathStr = null; + + private XPath xpath = null; + + private static FunctionTable funcTable = null; + + private static boolean installed; + + private XPathContext context; + + static { + fixupFunctionTable(); + } + + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + + // Execute the XPath, and have it return the result + XObject list = eval(contextNode, xpathnode, str, namespaceNode); + + // Return a NodeList. + return list.nodelist(); + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + XObject object = eval(contextNode, xpathnode, str, namespaceNode); + return object.bool(); + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpath = null; + context = null; + } + + public synchronized static boolean isInstalled() { + return installed; + } + + private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (context == null) { + context = new XPathContext(xpathnode); + context.setSecureProcessing(true); + } + + // Create an object to resolve namespace prefixes. + // XPath namespaces are resolved from the input context node's document element + // if it is a root node, or else the current context node (for lack of a better + // resolution space, given the simplicity of this sample code). + Node resolverNode = + (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) + ? ((Document) namespaceNode).getDocumentElement() : namespaceNode; + PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode); + + if (!str.equals(xpathStr)) { + if (str.indexOf("here()") > 0) { + context.reset(); + } + xpath = createXPath(str, prefixResolver); + xpathStr = str; + } + + // Execute the XPath, and have it return the result + int ctxtNode = context.getDTMHandleFromNode(contextNode); + + return xpath.execute(context, ctxtNode, prefixResolver); + } + + private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { + XPath xpath = null; + Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, + ErrorListener.class, FunctionTable.class}; + Object[] objects = + new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable}; + try { + Constructor constructor = XPath.class.getConstructor(classes); + xpath = (XPath) constructor.newInstance(objects); + } catch (Exception ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + if (xpath == null) { + xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); + } + return xpath; + } + + private synchronized static void fixupFunctionTable() { + installed = false; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Registering Here function"); + } + /** + * Try to register our here() implementation as internal function. + */ + try { + Class[] args = {String.class, Expression.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { + Object[] params = {"here", new FuncHere()}; + installFunction.invoke(null, params); + installed = true; + } + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + if (!installed) { + try { + funcTable = new FunctionTable(); + Class[] args = {String.class, Class.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + Object[] params = {"here", FuncHere.class}; + installFunction.invoke(funcTable, params); + installed = true; + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + if (installed) { + log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } else { + log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java new file mode 100644 index 00000000000..e6ee959d750 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java @@ -0,0 +1,37 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return a XalanXPathAPI instance. + */ +public class XalanXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new XalanXPathAPI(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java index 67d635cb847..7570a019064 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java @@ -85,8 +85,14 @@ public class ResourceResolver { * @throws ResourceResolverException */ public static final ResourceResolver getInstance( - Attr uri, String baseURI, boolean secureValidation + Attr uriAttr, String baseURI, boolean secureValidation ) throws ResourceResolverException { + ResourceResolverContext context = new ResourceResolverContext(uriAttr, baseURI, secureValidation); + return internalGetInstance(context); + } + + private static ResourceResolver internalGetInstance(ResourceResolverContext context) + throws ResourceResolverException { synchronized (resolverList) { for (ResourceResolver resolver : resolverList) { ResourceResolver resolverTmp = resolver; @@ -95,9 +101,9 @@ public class ResourceResolver { resolverTmp = new ResourceResolver(resolver.resolverSpi.getClass().newInstance()); } catch (InstantiationException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } catch (IllegalAccessException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } } @@ -107,15 +113,14 @@ public class ResourceResolver { ); } - resolverTmp.resolverSpi.secureValidation = secureValidation; - if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) { + if ((resolverTmp != null) && resolverTmp.canResolve(context)) { // Check to see whether the Resolver is allowed - if (secureValidation + if (context.secureValidation && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) { Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() }; throw new ResourceResolverException( - "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI + "signature.Reference.ForbiddenResolver", exArgs, context.attr, context.baseUri ); } return resolverTmp; @@ -123,9 +128,10 @@ public class ResourceResolver { } } - Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI }; + Object exArgs[] = { ((context.uriToResolve != null) + ? context.uriToResolve : "null"), context.baseUri }; - throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI); + throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.attr, context.baseUri); } /** @@ -165,6 +171,8 @@ public class ResourceResolver { ); } + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + // first check the individual Resolvers if (individualResolvers != null) { for (int i = 0; i < individualResolvers.size(); i++) { @@ -176,15 +184,14 @@ public class ResourceResolver { log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass); } - resolver.resolverSpi.secureValidation = secureValidation; - if (resolver.canResolve(uri, baseURI)) { + if (resolver.canResolve(context)) { return resolver; } } } } - return getInstance(uri, baseURI, secureValidation); + return internalGetInstance(context); } /** @@ -269,6 +276,15 @@ public class ResourceResolver { } } + /** + * @deprecated New clients should use {@link #resolve(Attr, String, boolean)} + */ + @Deprecated + public XMLSignatureInput resolve(Attr uri, String baseURI) + throws ResourceResolverException { + return resolve(uri, baseURI, true); + } + /** * Method resolve * @@ -278,9 +294,10 @@ public class ResourceResolver { * * @throws ResourceResolverException */ - public XMLSignatureInput resolve(Attr uri, String baseURI) + public XMLSignatureInput resolve(Attr uri, String baseURI, boolean secureValidation) throws ResourceResolverException { - return resolverSpi.engineResolve(uri, baseURI); + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + return resolverSpi.engineResolveURI(context); } /** @@ -338,7 +355,7 @@ public class ResourceResolver { * @param baseURI * @return true if it can resolve the uri */ - private boolean canResolve(Attr uri, String baseURI) { - return resolverSpi.engineCanResolve(uri, baseURI); + private boolean canResolve(ResourceResolverContext context) { + return this.resolverSpi.engineCanResolveURI(context); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java new file mode 100644 index 00000000000..5b8a9ce13f6 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java @@ -0,0 +1,43 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils.resolver; + +import org.w3c.dom.Attr; + +public class ResourceResolverContext { + + public ResourceResolverContext(Attr attr, String baseUri, boolean secureValidation) { + this.attr = attr; + this.baseUri = baseUri; + this.secureValidation = secureValidation; + this.uriToResolve = attr != null ? attr.getValue() : null; + } + + public final String uriToResolve; + + public final boolean secureValidation; + + public final String baseUri; + + public final Attr attr; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java index 5fa9ea35787..cf5c8d12ea2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java @@ -2,144 +2,137 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Attr; - /** * This Exception is thrown if something related to the * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResourceResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Attr uri, String BaseURI) { + private static final long serialVersionUID = 1L; - super(_msgID); + private Attr uri = null; - this._uri = uri; - this._BaseURI = BaseURI; - } + private String baseURI = null; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], Attr uri, - String BaseURI) { + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Attr uri, String baseURI) { + super(msgID); - super(_msgID, exArgs); + this.uri = uri; + this.baseURI = baseURI; + } - this._uri = uri; - this._BaseURI = BaseURI; - } + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], Attr uri, + String baseURI) { + super(msgID, exArgs); - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Exception _originalException, - Attr uri, String BaseURI) { + this.uri = uri; + this.baseURI = baseURI; + } - super(_msgID, _originalException); + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Exception originalException, + Attr uri, String baseURI) { + super(msgID, originalException); - this._uri = uri; - this._BaseURI = BaseURI; - } + this.uri = uri; + this.baseURI = baseURI; + } - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], - Exception _originalException, Attr uri, - String BaseURI) { + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], + Exception originalException, Attr uri, + String baseURI) { + super(msgID, exArgs, originalException); - super(_msgID, exArgs, _originalException); + this.uri = uri; + this.baseURI = baseURI; + } - this._uri = uri; - this._BaseURI = BaseURI; - } + /** + * + * @param uri + */ + public void setURI(Attr uri) { + this.uri = uri; + } - //J- - Attr _uri = null; - /** - * - * @param uri - */ - public void setURI(Attr uri) { - this._uri = uri; - } + /** + * + * @return the uri + */ + public Attr getURI() { + return this.uri; + } - /** - * - * @return the uri - */ - public Attr getURI() { - return this._uri; - } + /** + * + * @param baseURI + */ + public void setbaseURI(String baseURI) { + this.baseURI = baseURI; + } - String _BaseURI; + /** + * + * @return the baseURI + */ + public String getbaseURI() { + return this.baseURI; + } - /** - * - * @param BaseURI - */ - public void setBaseURI(String BaseURI) { - this._BaseURI = BaseURI; - } - - /** - * - * @return the basUri - */ - public String getBaseURI() { - return this._BaseURI; - } - //J+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java index e9ba6d13171..0ca4523600d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java @@ -2,192 +2,239 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver; - import java.util.HashMap; import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import org.w3c.dom.Attr; - /** * During reference validation, we have to retrieve resources from somewhere. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResourceResolverSpi.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResourceResolverSpi.class.getName()); - /** Field _properties */ - protected java.util.Map _properties = null; + /** Field properties */ + protected java.util.Map properties = null; - protected boolean secureValidation; + /** + * Deprecated - used to carry state about whether resolution was being done in a secure fashion, + * but was not thread safe, so the resolution information is now passed as parameters to methods. + * + * @deprecated Secure validation flag is now passed to methods. + */ + @Deprecated + protected final boolean secureValidation = true; - /** - * This is the workhorse method used to resolve resources. - * - * @param uri - * @param BaseURI - * @return the resource wrapped arround a XMLSignatureInput - * - * @throws ResourceResolverException - */ - public abstract XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException; + /** + * This is the workhorse method used to resolve resources. + * + * @param uri + * @param BaseURI + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + * + * @deprecated New clients should override {@link #engineResolveURI(ResourceResolverContext)} + */ + @Deprecated + public XMLSignatureInput engineResolve(Attr uri, String BaseURI) + throws ResourceResolverException { + throw new UnsupportedOperationException(); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.put(key, value); - } + /** + * This is the workhorse method used to resolve resources. + * @param context Context to use to resolve resources. + * + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + // The default implementation, to preserve backwards compatibility in the + // test cases, calls the old resolver API. + return engineResolve(context.attr, context.baseUri); + } - /** - * Method engineGetProperty - * - * @param key - * @return the value of the property - */ - public String engineGetProperty(String key) { - if (_properties==null) { - return null; - } - return this._properties.get(key); - } + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * - * @param properties - */ - public void engineAddProperies(Map properties) { - if (properties!=null) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.putAll(properties); - } - } - /** - * Tells if the implementation does can be reused by several threads safely. - * It normally means that the implemantation does not have any member, or there is - * member change betwen engineCanResolve & engineResolve invocations. Or it mantians all - * member info in ThreadLocal methods. - */ - public boolean engineIsThreadSafe() { - return false; - } - /** - * This method helps the {@link ResourceResolver} to decide whether a - * {@link ResourceResolverSpi} is able to perform the requested action. - * - * @param uri - * @param BaseURI - * @return true if the engine can resolve the uri - */ - public abstract boolean engineCanResolve(Attr uri, String BaseURI); + /** + * Method engineGetProperty + * + * @param key + * @return the value of the property + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } + return properties.get(key); + } - /** - * Method engineGetPropertyKeys - * - * @return the property keys - */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } - - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understands the property - */ - public boolean understandsProperty(String propertyToTest) { - - String[] understood = this.engineGetPropertyKeys(); - - if (understood != null) { - for (int i = 0; i < understood.length; i++) { - if (understood[i].equals(propertyToTest)) { - return true; + /** + * + * @param newProperties + */ + public void engineAddProperies(Map newProperties) { + if (newProperties != null && !newProperties.isEmpty()) { + if (properties == null) { + properties = new HashMap(); } - } - } + properties.putAll(newProperties); + } + } - return false; - } + /** + * Tells if the implementation does can be reused by several threads safely. + * It normally means that the implementation does not have any member, or there is + * member change between engineCanResolve & engineResolve invocations. Or it maintains all + * member info in ThreadLocal methods. + */ + public boolean engineIsThreadSafe() { + return false; + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + * @param uri + * @param BaseURI + * @return true if the engine can resolve the uri + * + * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)} + */ + @Deprecated + public boolean engineCanResolve(Attr uri, String BaseURI) { + // This method used to be abstract, so any calls to "super" are bogus. + throw new UnsupportedOperationException(); + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + *

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

    + * @param context Context in which to do resolution. + * @return true if the engine can resolve the uri + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + // To preserve backward compatibility with existing resolvers that might override the old method, + // call the old deprecated API. + return engineCanResolve( context.attr, context.baseUri ); + } + + /** + * Method engineGetPropertyKeys + * + * @return the property keys + */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } + + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understands the property + */ + public boolean understandsProperty(String propertyToTest) { + String[] understood = this.engineGetPropertyKeys(); + + if (understood != null) { + for (int i = 0; i < understood.length; i++) { + if (understood[i].equals(propertyToTest)) { + return true; + } + } + } + + return false; + } - /** - * Fixes a platform dependent filename to standard URI form. - * - * @param str The string to fix. - * - * @return Returns the fixed URI string. - */ - public static String fixURI(String str) { + /** + * Fixes a platform dependent filename to standard URI form. + * + * @param str The string to fix. + * + * @return Returns the fixed URI string. + */ + public static String fixURI(String str) { - // handle platform dependent strings - str = str.replace(java.io.File.separatorChar, '/'); + // handle platform dependent strings + str = str.replace(java.io.File.separatorChar, '/'); - if (str.length() >= 4) { + if (str.length() >= 4) { - // str =~ /^\W:\/([^/])/ # to speak perl ;-)) - char ch0 = Character.toUpperCase(str.charAt(0)); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - char ch3 = str.charAt(3); - boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) - && (ch1 == ':') && (ch2 == '/') - && (ch3 != '/')); - - if (isDosFilename) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); - } - } - - // Windows fix - if (str.length() >= 2) { - char ch1 = str.charAt(1); - - if (ch1 == ':') { + // str =~ /^\W:\/([^/])/ # to speak perl ;-)) char ch0 = Character.toUpperCase(str.charAt(0)); + char ch1 = str.charAt(1); + char ch2 = str.charAt(2); + char ch3 = str.charAt(3); + boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) + && (ch1 == ':') && (ch2 == '/') + && (ch3 != '/')); - if (('A' <= ch0) && (ch0 <= 'Z')) { - str = "/" + str; + if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); } - } - } + } - // done - return str; - } + // Windows fix + if (str.length() >= 2) { + char ch1 = str.charAt(1); + + if (ch1 == ':') { + char ch0 = Character.toUpperCase(str.charAt(0)); + + if (('A' <= ch0) && (ch0 <= 'Z')) { + str = "/" + str; + } + } + } + + // done + return str; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java index 0bd0c59120b..22aba4083b8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java @@ -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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; @@ -27,51 +29,56 @@ import java.io.IOException; import java.io.InputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ - public class ResolverAnonymous extends ResourceResolverSpi { - private XMLSignatureInput _input = null; + private InputStream inStream = null; - /** - * @param filename + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * @param filename * @throws FileNotFoundException * @throws IOException */ - public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { - this._input = new XMLSignatureInput(new FileInputStream(filename)); - } + public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { + inStream = new FileInputStream(filename); + } - /** - * @param is + /** + * @param is */ - public ResolverAnonymous(InputStream is) { - this._input = new XMLSignatureInput(is); - } + public ResolverAnonymous(InputStream is) { + inStream = is; + } - /** @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) { - return this._input; - } + /** @inheritDoc */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) { + return new XMLSignatureInput(inStream); + } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - return true; - } - return false; - } + /** + * @inheritDoc + */ + @Override + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return true; + } + return false; + } - /** @inheritDoc */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } + /** @inheritDoc */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java index 706cccc6a4d..cd0967215a7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java @@ -2,38 +2,42 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.net.InetSocketAddress; import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URISyntaxException; +import java.net.URI; import java.net.URL; import java.net.URLConnection; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.Base64; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; - /** * A simple ResourceResolver for HTTP requests. This class handles only 'pure' @@ -51,253 +55,219 @@ import org.w3c.dom.Attr; * resourceResolver.setProperty("http.proxy.password", "secretca"); *
    * - * - * @author $Author: mullan $ * @see Java Tip 42: Write Java apps that work with proxy-based firewalls * @see SUN J2SE docs for network properties * @see The JAVA FAQ Question 9.5: How do I make Java work with a proxy server? - * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!? */ public class ResolverDirectHTTP extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverDirectHTTP.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName()); - /** Field properties[] */ - private static final String properties[] = - { "http.proxy.host", "http.proxy.port", - "http.proxy.username", - "http.proxy.password", - "http.basic.username", - "http.basic.password" }; + /** Field properties[] */ + private static final String properties[] = { + "http.proxy.host", "http.proxy.port", + "http.proxy.username", "http.proxy.password", + "http.basic.username", "http.basic.password" + }; - /** Field HttpProxyHost */ - private static final int HttpProxyHost = 0; + /** Field HttpProxyHost */ + private static final int HttpProxyHost = 0; - /** Field HttpProxyPort */ - private static final int HttpProxyPort = 1; + /** Field HttpProxyPort */ + private static final int HttpProxyPort = 1; - /** Field HttpProxyUser */ - private static final int HttpProxyUser = 2; + /** Field HttpProxyUser */ + private static final int HttpProxyUser = 2; - /** Field HttpProxyPass */ - private static final int HttpProxyPass = 3; + /** Field HttpProxyPass */ + private static final int HttpProxyPass = 3; - /** Field HttpProxyUser */ - private static final int HttpBasicUser = 4; + /** Field HttpProxyUser */ + private static final int HttpBasicUser = 4; - /** Field HttpProxyPass */ - private static final int HttpBasicPass = 5; + /** Field HttpProxyPass */ + private static final int HttpBasicPass = 5; - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method resolve - * - * @param uri - * @param BaseURI - * - * @throws ResourceResolverException - * @return - * $todo$ calculate the correct URI from the attribute and the BaseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + @Override + public boolean engineIsThreadSafe() { + return true; + } - try { - boolean useProxy = false; - String proxyHost = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyHost]); - String proxyPort = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPort]); + /** + * Method resolve + * + * @param uri + * @param baseURI + * + * @throws ResourceResolverException + * @return + * $todo$ calculate the correct URI from the attribute and the baseURI + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { - if ((proxyHost != null) && (proxyPort != null)) { - useProxy = true; - } - - String oldProxySet = null; - String oldProxyHost = null; - String oldProxyPort = null; - // switch on proxy usage - if (useProxy) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Use of HTTP proxy enabled: " + proxyHost + ":" - + proxyPort); - } - oldProxySet = System.getProperty("http.proxySet"); - oldProxyHost = System.getProperty("http.proxyHost"); - oldProxyPort = System.getProperty("http.proxyPort"); - System.setProperty("http.proxySet", "true"); - System.setProperty("http.proxyHost", proxyHost); - System.setProperty("http.proxyPort", proxyPort); - } - - boolean switchBackProxy = ((oldProxySet != null) - && (oldProxyHost != null) - && (oldProxyPort != null)); - - // calculate new URI - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); - - // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - URL url = new URL(uriNewNoFrag.toString()); - URLConnection urlConnection = url.openConnection(); - - { - - // set proxy pass - String proxyUser = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyUser]); - String proxyPass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPass]); - - if ((proxyUser != null) && (proxyPass != null)) { - String password = proxyUser + ":" + proxyPass; - String encodedPassword = Base64.encode(password.getBytes()); - - // or was it Proxy-Authenticate ? - urlConnection.setRequestProperty("Proxy-Authorization", - encodedPassword); - } - } - - { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + URL url = uriNew.toURL(); + URLConnection urlConnection; + urlConnection = openConnection(url); // check if Basic authentication is required String auth = urlConnection.getHeaderField("WWW-Authenticate"); - if (auth != null) { + if (auth != null && auth.startsWith("Basic")) { + // do http basic authentication + String user = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]); + String pass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]); - // do http basic authentication - if (auth.startsWith("Basic")) { - String user = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicUser]); - String pass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicPass]); + if ((user != null) && (pass != null)) { + urlConnection = openConnection(url); - if ((user != null) && (pass != null)) { - urlConnection = url.openConnection(); + String password = user + ":" + pass; + String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1")); - String password = user + ":" + pass; - String encodedPassword = - Base64.encode(password.getBytes()); - - // set authentication property in the http header - urlConnection.setRequestProperty("Authorization", - "Basic " - + encodedPassword); - } - } + // set authentication property in the http header + urlConnection.setRequestProperty("Authorization", + "Basic " + encodedPassword); + } } - } - String mimeType = urlConnection.getHeaderField("Content-Type"); - InputStream inputStream = urlConnection.getInputStream(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte buf[] = new byte[4096]; - int read = 0; - int summarized = 0; + String mimeType = urlConnection.getHeaderField("Content-Type"); + InputStream inputStream = urlConnection.getInputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte buf[] = new byte[4096]; + int read = 0; + int summarized = 0; - while ((read = inputStream.read(buf)) >= 0) { - baos.write(buf, 0, read); + while ((read = inputStream.read(buf)) >= 0) { + baos.write(buf, 0, read); + summarized += read; + } - summarized += read; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString()); + } - log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " - + uriNew.toString()); + XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); - XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); + result.setSourceURI(uriNew.toString()); + result.setMIMEType(mimeType); - // XMLSignatureInput result = new XMLSignatureInput(inputStream); - result.setSourceURI(uriNew.toString()); - result.setMIMEType(mimeType); + return result; + } catch (URISyntaxException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (MalformedURLException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IOException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IllegalArgumentException e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } - // switch off proxy usage - if (useProxy && switchBackProxy) { - System.setProperty("http.proxySet", oldProxySet); - System.setProperty("http.proxyHost", oldProxyHost); - System.setProperty("http.proxyPort", oldProxyPort); - } + private URLConnection openConnection(URL url) throws IOException { - return result; - } catch (MalformedURLException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } catch (IOException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } - } + String proxyHostProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]); + String proxyPortProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]); + String proxyUser = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]); + String proxyPass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]); - /** - * We resolve http URIs without fragment... - * - * @param uri - * @param BaseURI - * @return true if can be resolved - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + Proxy proxy = null; + if ((proxyHostProp != null) && (proxyPortProp != null)) { + int port = Integer.parseInt(proxyPortProp); + proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port)); + } - return false; - } + URLConnection urlConnection; + if (proxy != null) { + urlConnection = url.openConnection(proxy); - String uriNodeValue = uri.getNodeValue(); + if ((proxyUser != null) && (proxyPass != null)) { + String password = proxyUser + ":" + proxyPass; + String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1")); - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) { - log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + urlConnection.setRequestProperty("Proxy-Authorization", authString); + } + } else { + urlConnection = url.openConnection(); + } - return false; - } + return urlConnection; + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue); - } + /** + * We resolve http URIs without fragment... + * + * @param uri + * @param baseURI + * @return true if can be resolved + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + } + return false; + } - if ( uriNodeValue.startsWith("http:") || - (BaseURI!=null && BaseURI.startsWith("http:") )) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue); - } + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + } + return false; + } - return true; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue); - } + if (context.uriToResolve.startsWith("http:") || + (context.baseUri != null && context.baseUri.startsWith("http:") )) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } - return false; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve); + } - /** - * @inheritDoc - */ - public String[] engineGetPropertyKeys() { - return ResolverDirectHTTP.properties.clone(); - } + return false; + } - private URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { + /** + * @inheritDoc + */ + public String[] engineGetPropertyKeys() { + return ResolverDirectHTTP.properties.clone(); + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } + + // if the URI contains a fragment, ignore it + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; + } + return newUri; + } - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java index d2750c84903..49eb0407382 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java @@ -2,148 +2,148 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * This resolver is used for resolving same-document URIs like URI="" of URI="#id". * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see The Reference processing model in the XML Signature spec * @see Same-Document URI-References in the XML Signature spec * @see Section 4.2 of RFC 2396 */ public class ResolverFragment extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverFragment.class.getName()); - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method engineResolve - * - * @inheritDoc - * @param uri - * @param baseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException - { - String uriNodeValue = uri.getNodeValue(); - Document doc = uri.getOwnerElement().getOwnerDocument(); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverFragment.class.getName()); + + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * Method engineResolve + * + * @inheritDoc + * @param uri + * @param baseURI + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + + Document doc = context.attr.getOwnerElement().getOwnerDocument(); Node selectedElem = null; - if (uriNodeValue.equals("")) { - - /* - * Identifies the node-set (minus any comment nodes) of the XML - * resource containing the signature - */ - - log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + if (context.uriToResolve.equals("")) { + /* + * Identifies the node-set (minus any comment nodes) of the XML + * resource containing the signature + */ + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + } selectedElem = doc; } else { - /* * URI="#chapter1" * Identifies a node-set containing the element with ID attribute * value 'chapter1' of the XML resource containing the signature. * XML Signature (and its applications) modify this node-set to - * include the element plus all descendents including namespaces and + * include the element plus all descendants including namespaces and * attributes -- but not comments. */ - String id = uriNodeValue.substring(1); + String id = context.uriToResolve.substring(1); selectedElem = doc.getElementById(id); if (selectedElem == null) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Try to catch an Element with ID " + id + " and Element was " + selectedElem + ); + } } XMLSignatureInput result = new XMLSignatureInput(selectedElem); result.setExcludeComments(true); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * Method engineCanResolve - * @inheritDoc - * @param uri - * @param BaseURI - * - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { + /** + * Method engineCanResolve + * @inheritDoc + * @param uri + * @param baseURI + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); + } + return false; + } - if (uri == null) { - log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || - ( - (uriNodeValue.charAt(0)=='#') - && !((uriNodeValue.charAt(1)=='x') && uriNodeValue.startsWith("#xpointer(")) - ) - ){ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + uriNodeValue + "\""); - return true; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + uriNodeValue + "\""); - return false; - } + if (context.uriToResolve.equals("") || + ((context.uriToResolve.charAt(0) == '#') && !context.uriToResolve.startsWith("#xpointer(")) + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + context.uriToResolve + "\""); + } + return true; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + context.uriToResolve + "\""); + } + return false; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java index 07af53db296..c526286462d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java @@ -2,156 +2,160 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; import java.io.FileInputStream; +import java.net.URI; +import java.net.URISyntaxException; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** * A simple ResourceResolver for requests into the local filesystem. - * - * @author $Author: mullan $ */ public class ResolverLocalFilesystem extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverLocalFilesystem.class.getName()); + private static final int FILE_URI_LENGTH = "file:/".length(); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverLocalFilesystem.class.getName()); + + @Override public boolean engineIsThreadSafe() { - return true; - } - /** - * @inheritDoc - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + return true; + } - try { - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); + /** + * @inheritDoc + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + + String fileName = + ResolverLocalFilesystem.translateUriToFilename(uriNew.toString()); + FileInputStream inputStream = new FileInputStream(fileName); + XMLSignatureInput result = new XMLSignatureInput(inputStream); + + result.setSourceURI(uriNew.toString()); + + return result; + } catch (Exception e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } + + /** + * Method translateUriToFilename + * + * @param uri + * @return the string of the filename + */ + private static String translateUriToFilename(String uri) { + + String subStr = uri.substring(FILE_URI_LENGTH); + + if (subStr.indexOf("%20") > -1) { + int offset = 0; + int index = 0; + StringBuilder temp = new StringBuilder(subStr.length()); + do { + index = subStr.indexOf("%20",offset); + if (index == -1) { + temp.append(subStr.substring(offset)); + } else { + temp.append(subStr.substring(offset, index)); + temp.append(' '); + offset = index + 3; + } + } while(index != -1); + subStr = temp.toString(); + } + + if (subStr.charAt(1) == ':') { + // we're running M$ Windows, so this works fine + return subStr; + } + // we're running some UNIX, so we have to prepend a slash + return "/" + subStr; + } + + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#') || + context.uriToResolve.startsWith("http:")) { + return false; + } + + try { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } + + if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "But I can't"); + } + + return false; + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - String fileName = - ResolverLocalFilesystem - .translateUriToFilename(uriNewNoFrag.toString()); - FileInputStream inputStream = new FileInputStream(fileName); - XMLSignatureInput result = new XMLSignatureInput(inputStream); - - result.setSourceURI(uriNew.toString()); - - return result; - } catch (Exception e) { - throw new ResourceResolverException("generic.EmptyMessage", e, uri, - BaseURI); - } - } - - private static int FILE_URI_LENGTH="file:/".length(); - /** - * Method translateUriToFilename - * - * @param uri - * @return the string of the filename - */ - private static String translateUriToFilename(String uri) { - - String subStr = uri.substring(FILE_URI_LENGTH); - - if (subStr.indexOf("%20") > -1) - { - int offset = 0; - int index = 0; - StringBuffer temp = new StringBuffer(subStr.length()); - do - { - index = subStr.indexOf("%20",offset); - if (index == -1) temp.append(subStr.substring(offset)); - else - { - temp.append(subStr.substring(offset,index)); - temp.append(' '); - offset = index+3; - } + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; } - while(index != -1); - subStr = temp.toString(); - } - - if (subStr.charAt(1) == ':') { - // we're running M$ Windows, so this works fine - return subStr; - } - // we're running some UNIX, so we have to prepend a slash - return "/" + subStr; - } - - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#') || - uriNodeValue.startsWith("http:")) { - return false; - } - - try { - //URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue()); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue/*uriNew.toString()*/); - - if ( uriNodeValue.startsWith("file:") || - BaseURI.startsWith("file:")/*uriNew.getScheme().equals("file")*/) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue/*uriNew.toString()*/); - - return true; - } - } catch (Exception e) {} - - log.log(java.util.logging.Level.FINE, "But I can't"); - - return false; - } - - private static URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { - - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } + return newUri; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java index 0f931f44193..345087bbcec 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java @@ -2,36 +2,35 @@ * 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 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Handles barename XPointer Reference URIs. *
    @@ -45,15 +44,18 @@ import org.w3c.dom.Node; * nodes of the parse tree (all descendants, plus all attributes, * plus all namespaces nodes). * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResolverXPointer extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverXPointer.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverXPointer.class.getName()); + private static final String XP = "#xpointer(id("; + private static final int XP_LENGTH = XP.length(); + + @Override public boolean engineIsThreadSafe() { return true; } @@ -61,139 +63,118 @@ public class ResolverXPointer extends ResourceResolverSpi { /** * @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException { + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { Node resultNode = null; - Document doc = uri.getOwnerElement().getOwnerDocument(); + Document doc = context.attr.getOwnerElement().getOwnerDocument(); - String uriStr = uri.getNodeValue(); - if (isXPointerSlash(uriStr)) { + if (isXPointerSlash(context.uriToResolve)) { resultNode = doc; - - } else if (isXPointerId(uriStr)) { - String id = getXPointerId(uriStr); + } else if (isXPointerId(context.uriToResolve)) { + String id = getXPointerId(context.uriToResolve); resultNode = doc.getElementById(id); - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } if (resultNode == null) { - Object exArgs[] = { id }; + Object exArgs[] = { id }; - throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + throw new ResourceResolverException( + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } } XMLSignatureInput result = new XMLSignatureInput(resultNode); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - String uriStr =uri.getNodeValue(); - if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) { - return true; - } - - return false; - } - - /** - * Method isXPointerSlash - * - * @param uri - * @return true if begins with xpointer - */ - private static boolean isXPointerSlash(String uri) { - - if (uri.equals("#xpointer(/)")) { - return true; - } - - return false; - } - - - private static final String XP="#xpointer(id("; - private static final int XP_LENGTH=XP.length(); - /** - * Method isXPointerId - * - * @param uri - * @return it it has an xpointer id - * - */ - private static boolean isXPointerId(String uri) { - - - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH, - uri.length() - - 2); - - // log.log(java.util.logging.Level.FINE, "idPlusDelim=" + idPlusDelim); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Id=" - + idPlusDelim.substring(1, idLen)); - + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) { return true; - } - } + } - return false; - } + return false; + } - /** - * Method getXPointerId - * - * @param uri - * @return xpointerId to search. - */ - private static String getXPointerId(String uri) { + /** + * Method isXPointerSlash + * + * @param uri + * @return true if begins with xpointer + */ + private static boolean isXPointerSlash(String uri) { + if (uri.equals("#xpointer(/)")) { + return true; + } + return false; + } - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - - 2); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - return idPlusDelim.substring(1, idLen); - } - } + /** + * Method isXPointerId + * + * @param uri + * @return whether it has an xpointer id + */ + private static boolean isXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2); - return null; - } + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Id = " + idPlusDelim.substring(1, idLen)); + } + return true; + } + } + + return false; + } + + /** + * Method getXPointerId + * + * @param uri + * @return xpointerId to search. + */ + private static String getXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - 2); + + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + return idPlusDelim.substring(1, idLen); + } + } + + return null; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java index c6f9d9c1c70..859b43183b4 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java @@ -2,36 +2,37 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DigesterOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $ + * $Id: DigesterOutputStream.java,v 1.5 2005/12/20 20:02:39 mullan Exp $ */ package org.jcp.xml.dsig.internal; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; -import java.util.logging.Logger; -import java.util.logging.Level; import com.sun.org.apache.xml.internal.security.utils.UnsyncByteArrayOutputStream; @@ -45,10 +46,12 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncByteArrayOutputStrea * @author Sean Mullan */ public class DigesterOutputStream extends OutputStream { - private boolean buffer = false; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal"); + + private final boolean buffer; private UnsyncByteArrayOutputStream bos; private final MessageDigest md; - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal"); /** * Creates a DigesterOutputStream. @@ -73,12 +76,6 @@ public class DigesterOutputStream extends OutputStream { } } - /** @inheritDoc */ - public void write(byte[] input) { - write(input, 0, input.length); - } - - /** @inheritDoc */ public void write(int input) { if (buffer) { bos.write(input); @@ -86,18 +83,18 @@ public class DigesterOutputStream extends OutputStream { md.update((byte)input); } - /** @inheritDoc */ + @Override public void write(byte[] input, int offset, int len) { if (buffer) { bos.write(input, offset, len); } - if (log.isLoggable(Level.FINER)) { - log.log(Level.FINER, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(len); - for (int i=offset; i<(offset+len); i++) { - sb.append((char) input[i]); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Pre-digested input:"); + StringBuilder sb = new StringBuilder(len); + for (int i = offset; i < (offset + len); i++) { + sb.append((char)input[i]); } - log.log(Level.FINER, sb.toString()); + log.log(java.util.logging.Level.FINE, sb.toString()); } md.update(input, offset, len); } @@ -120,4 +117,11 @@ public class DigesterOutputStream extends OutputStream { return null; } } + + @Override + public void close() throws IOException { + if (buffer) { + bos.close(); + } + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java index 3309215bb96..ac3a3997c42 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.jcp.xml.dsig.internal; @@ -38,19 +40,13 @@ public class MacOutputStream extends ByteArrayOutputStream { this.mac = mac; } - /** @inheritDoc */ - public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); - mac.update(arg0); - } - - /** @inheritDoc */ + @Override public void write(int arg0) { super.write(arg0); mac.update((byte) arg0); } - /** @inheritDoc */ + @Override public void write(byte[] arg0, int arg1, int arg2) { super.write(arg0, arg1, arg2); mac.update(arg0, arg1, arg2); diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java index 09a25290852..6cfcf0e5e45 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: SignerOutputStream.java,v 1.2 2008/07/24 15:20:31 mullan Exp $ + * $Id: SignerOutputStream.java,v 1.2 2005/09/15 14:29:02 mullan Exp $ */ package org.jcp.xml.dsig.internal; @@ -32,8 +34,8 @@ import java.security.SignatureException; /** * Derived from Apache sources and changed to use java.security.Signature - * objects as input instead of com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm - * objects. + * objects as input instead of + * com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm objects. * * @author raul * @author Sean Mullan @@ -42,36 +44,26 @@ public class SignerOutputStream extends ByteArrayOutputStream { private final Signature sig; public SignerOutputStream(Signature sig) { - this.sig=sig; + this.sig = sig; } - /** @inheritDoc */ - public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); - try { - sig.update(arg0); - } catch (SignatureException e) { - throw new RuntimeException(""+e); - } - } - - /** @inheritDoc */ + @Override public void write(int arg0) { super.write(arg0); try { sig.update((byte)arg0); } catch (SignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException(e); } } - /** @inheritDoc */ + @Override public void write(byte[] arg0, int arg1, int arg2) { super.write(arg0, arg1, arg2); try { - sig.update(arg0,arg1,arg2); + sig.update(arg0, arg1, arg2); } catch (SignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException(e); } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java new file mode 100644 index 00000000000..de620ae759a --- /dev/null +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java @@ -0,0 +1,218 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jcp.xml.dsig.internal.dom; + +import java.security.Key; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; +import javax.xml.crypto.MarshalException; +import javax.xml.crypto.dom.DOMCryptoContext; +import javax.xml.crypto.dsig.SignatureMethod; +import javax.xml.crypto.dsig.SignedInfo; +import javax.xml.crypto.dsig.XMLSignature; +import javax.xml.crypto.dsig.XMLSignatureException; +import javax.xml.crypto.dsig.XMLSignContext; +import javax.xml.crypto.dsig.XMLValidateContext; +import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * An abstract class representing a SignatureMethod. Subclasses implement + * a specific XML DSig signature algorithm. + */ +abstract class AbstractDOMSignatureMethod extends DOMStructure + implements SignatureMethod { + + // denotes the type of signature algorithm + enum Type { DSA, RSA, ECDSA, HMAC } + + /** + * Verifies the passed-in signature with the specified key, using the + * underlying Signature or Mac algorithm. + * + * @param key the verification key + * @param si the SignedInfo + * @param sig the signature bytes to be verified + * @param context the XMLValidateContext + * @return true if the signature verified successfully, + * false if not + * @throws NullPointerException if key, si or + * sig are null + * @throws InvalidKeyException if the key is improperly encoded, of + * the wrong type, or parameters are missing, etc + * @throws SignatureException if an unexpected error occurs, such + * as the passed in signature is improperly encoded + * @throws XMLSignatureException if an unexpected error occurs + */ + abstract boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException; + + /** + * Signs the bytes with the specified key, using the underlying + * Signature or Mac algorithm. + * + * @param key the signing key + * @param si the SignedInfo + * @param context the XMLSignContext + * @return the signature + * @throws NullPointerException if key or + * si are null + * @throws InvalidKeyException if the key is improperly encoded, of + * the wrong type, or parameters are missing, etc + * @throws XMLSignatureException if an unexpected error occurs + */ + abstract byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException; + + /** + * Returns the java.security.Signature or javax.crypto.Mac standard + * algorithm name. + */ + abstract String getJCAAlgorithm(); + + /** + * Returns the type of signature algorithm. + */ + abstract Type getAlgorithmType(); + + /** + * This method invokes the {@link #marshalParams marshalParams} + * method to marshal any algorithm-specific parameters. + */ + public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) + throws MarshalException + { + Document ownerDoc = DOMUtils.getOwnerDocument(parent); + + Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod", + XMLSignature.XMLNS, dsPrefix); + DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm()); + + if (getParameterSpec() != null) { + marshalParams(smElem, dsPrefix); + } + + parent.appendChild(smElem); + } + + /** + * Marshals the algorithm-specific parameters to an Element and + * appends it to the specified parent element. By default, this method + * throws an exception since most SignatureMethod algorithms do not have + * parameters. Subclasses should override it if they have parameters. + * + * @param parent the parent element to append the parameters to + * @param paramsPrefix the algorithm parameters prefix to use + * @throws MarshalException if the parameters cannot be marshalled + */ + void marshalParams(Element parent, String paramsPrefix) + throws MarshalException + { + throw new MarshalException("no parameters should " + + "be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + + /** + * Unmarshals SignatureMethodParameterSpec from the specified + * Element. By default, this method throws an exception since + * most SignatureMethod algorithms do not have parameters. Subclasses should + * override it if they have parameters. + * + * @param paramsElem the Element holding the input params + * @return the algorithm-specific SignatureMethodParameterSpec + * @throws MarshalException if the parameters cannot be unmarshalled + */ + SignatureMethodParameterSpec unmarshalParams(Element paramsElem) + throws MarshalException + { + throw new MarshalException("no parameters should " + + "be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + + /** + * Checks if the specified parameters are valid for this algorithm. By + * default, this method throws an exception if parameters are specified + * since most SignatureMethod algorithms do not have parameters. Subclasses + * should override it if they have parameters. + * + * @param params the algorithm-specific params (may be null) + * @throws InvalidAlgorithmParameterException if the parameters are not + * appropriate for this signature method + */ + void checkParams(SignatureMethodParameterSpec params) + throws InvalidAlgorithmParameterException + { + if (params != null) { + throw new InvalidAlgorithmParameterException("no parameters " + + "should be specified for the " + getAlgorithm() + + " SignatureMethod algorithm"); + } + } + + @Override + public boolean equals(Object o) + { + if (this == o) { + return true; + } + + if (!(o instanceof SignatureMethod)) { + return false; + } + SignatureMethod osm = (SignatureMethod)o; + + return (getAlgorithm().equals(osm.getAlgorithm()) && + paramsEqual(osm.getParameterSpec())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + + /** + * Returns true if parameters are equal; false otherwise. + * + * Subclasses should override this method to compare algorithm-specific + * parameters. + */ + boolean paramsEqual(AlgorithmParameterSpec spec) + { + return (getParameterSpec() == spec); + } +} diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java index fac4024f8a4..97554e4d200 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java @@ -2,44 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheCanonicalizer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheCanonicalizer.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.OutputStream; import java.security.spec.AlgorithmParameterSpec; import java.security.InvalidAlgorithmParameterException; import java.util.Set; -import java.util.logging.Logger; -import java.util.logging.Level; import javax.xml.crypto.*; import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.TransformException; import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.XMLSignatureException; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; @@ -48,7 +46,7 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; +import org.w3c.dom.Node; public abstract class ApacheCanonicalizer extends TransformService { @@ -56,7 +54,8 @@ public abstract class ApacheCanonicalizer extends TransformService { com.sun.org.apache.xml.internal.security.Init.init(); } - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); protected Canonicalizer apacheCanonicalizer; private Transform apacheTransform; protected String inclusiveNamespaces; @@ -64,51 +63,60 @@ public abstract class ApacheCanonicalizer extends TransformService { protected Document ownerDoc; protected Element transformElem; - public final AlgorithmParameterSpec getParameterSpec() { + public final AlgorithmParameterSpec getParameterSpec() + { return params; } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) - ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public Data canonicalize(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return canonicalize(data, xc, null); } public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - + throws TransformException + { if (apacheCanonicalizer == null) { try { apacheCanonicalizer = Canonicalizer.getInstance(getAlgorithm()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created canonicalizer for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created canonicalizer for algorithm: " + getAlgorithm()); } } catch (InvalidCanonicalizerException ice) { throw new TransformException ("Couldn't find Canonicalizer for: " + getAlgorithm() + - ": " + ice.getMessage(), ice); + ": " + ice.getMessage(), ice); } } @@ -119,10 +127,10 @@ public abstract class ApacheCanonicalizer extends TransformService { } try { - Set nodeSet = null; + Set nodeSet = null; if (data instanceof ApacheData) { XMLSignatureInput in = - ((ApacheData) data).getXMLSignatureInput(); + ((ApacheData)data).getXMLSignatureInput(); if (in.isElement()) { if (inclusiveNamespaces != null) { return new OctetStreamData(new ByteArrayInputStream @@ -141,7 +149,7 @@ public abstract class ApacheCanonicalizer extends TransformService { Utils.readBytesFromStream(in.getOctetStream())))); } } else if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; if (inclusiveNamespaces != null) { return new OctetStreamData(new ByteArrayInputStream (apacheCanonicalizer.canonicalizeSubtree @@ -152,12 +160,13 @@ public abstract class ApacheCanonicalizer extends TransformService { (subTree.getRoot()))); } } else if (data instanceof NodeSetData) { - NodeSetData nsd = (NodeSetData) data; + NodeSetData nsd = (NodeSetData)data; // convert Iterator to Set - nodeSet = Utils.toNodeSet(nsd.iterator()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Canonicalizing " + nodeSet.size() - + " nodes"); + @SuppressWarnings("unchecked") + Set ns = Utils.toNodeSet(nsd.iterator()); + nodeSet = ns; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Canonicalizing " + nodeSet.size() + " nodes"); } } else { return new OctetStreamData(new ByteArrayInputStream( @@ -179,7 +188,8 @@ public abstract class ApacheCanonicalizer extends TransformService { } public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } @@ -193,12 +203,11 @@ public abstract class ApacheCanonicalizer extends TransformService { if (apacheTransform == null) { try { - apacheTransform = new Transform - (ownerDoc, getAlgorithm(), transformElem.getChildNodes()); + apacheTransform = + new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); apacheTransform.setElement(transformElem, xc.getBaseURI()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created transform for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + getAlgorithm()); } } catch (Exception ex) { throw new TransformException @@ -208,26 +217,27 @@ public abstract class ApacheCanonicalizer extends TransformService { XMLSignatureInput in; if (data instanceof ApacheData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "ApacheData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ApacheData = true"); } - in = ((ApacheData) data).getXMLSignatureInput(); + in = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof NodeSetData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = true"); } if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; in = new XMLSignatureInput(subTree.getRoot()); in.setExcludeComments(subTree.excludeComments()); } else { - Set nodeSet = - Utils.toNodeSet(((NodeSetData) data).iterator()); + @SuppressWarnings("unchecked") + Set nodeSet = + Utils.toNodeSet(((NodeSetData)data).iterator()); in = new XMLSignatureInput(nodeSet); } } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = false"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = false"); } try { in = new XMLSignatureInput diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java index 52c5d40274e..add556470bd 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheData.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -39,5 +41,5 @@ public interface ApacheData extends Data { /** * Returns the XMLSignatureInput. */ - public XMLSignatureInput getXMLSignatureInput(); + XMLSignatureInput getXMLSignatureInput(); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java index 2d9d2e090e8..7f12cf4a38c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheNodeSetData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheNodeSetData.java 1203890 2011-11-18 22:47:56Z mullan $ */ package org.jcp.xml.dsig.internal.dom; import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; @@ -65,24 +66,22 @@ public class ApacheNodeSetData implements ApacheData, NodeSetData { return xi; } - private Set getNodeSet(List nodeFilters) { + private Set getNodeSet(List nodeFilters) { if (xi.isNeedsToBeExpanded()) { XMLUtils.circumventBug2650 (XMLUtils.getOwnerDocument(xi.getSubNode())); } - Set inputSet = new LinkedHashSet(); - XMLUtils.getSet - (xi.getSubNode(), inputSet, null, !xi.isExcludeComments()); - Set nodeSet = new LinkedHashSet(); - Iterator i = inputSet.iterator(); - while (i.hasNext()) { - Node currentNode = (Node) i.next(); - Iterator it = nodeFilters.iterator(); + Set inputSet = new LinkedHashSet(); + XMLUtils.getSet(xi.getSubNode(), inputSet, + null, !xi.isExcludeComments()); + Set nodeSet = new LinkedHashSet(); + for (Node currentNode : inputSet) { + Iterator it = nodeFilters.iterator(); boolean skipNode = false; while (it.hasNext() && !skipNode) { - NodeFilter nf = (NodeFilter) it.next(); - if (nf.isNodeInclude(currentNode)!=1) { + NodeFilter nf = it.next(); + if (nf.isNodeInclude(currentNode) != 1) { skipNode = true; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java index 719f3358de2..713934d04b9 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheOctetStreamData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheOctetStreamData.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -37,7 +39,8 @@ public class ApacheOctetStreamData extends OctetStreamData private XMLSignatureInput xi; public ApacheOctetStreamData(XMLSignatureInput xi) - throws CanonicalizationException, IOException { + throws CanonicalizationException, IOException + { super(xi.getOctetStream(), xi.getSourceURI(), xi.getMIMEType()); this.xi = xi; } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java index b1d9c04686a..7df11e6204a 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: ApacheTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -30,11 +32,9 @@ import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.spec.AlgorithmParameterSpec; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NodeList; +import org.w3c.dom.Node; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -58,7 +58,8 @@ public abstract class ApacheTransform extends TransformService { com.sun.org.apache.xml.internal.security.Init.init(); } - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Transform apacheTransform; protected Document ownerDoc; protected Element transformElem; @@ -69,37 +70,47 @@ public abstract class ApacheTransform extends TransformService { } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (context != null && !(context instanceof DOMCryptoContext)) { throw new ClassCastException ("context must be of type DOMCryptoContext"); } + if (parent == null || !(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } transformElem = (Element) ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); ownerDoc = DOMUtils.getOwnerDocument(transformElem); } public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } - return transformIt(data, xc, (OutputStream) null); + return transformIt(data, xc, (OutputStream)null); } public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { if (data == null) { throw new NullPointerException("data must not be null"); } @@ -110,24 +121,24 @@ public abstract class ApacheTransform extends TransformService { } private Data transformIt(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { - + throws TransformException + { if (ownerDoc == null) { throw new TransformException("transform must be marshalled"); } if (apacheTransform == null) { try { - apacheTransform = new Transform - (ownerDoc, getAlgorithm(), transformElem.getChildNodes()); + apacheTransform = + new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes()); apacheTransform.setElement(transformElem, xc.getBaseURI()); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Created transform for algorithm: " - + getAlgorithm()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + + getAlgorithm()); } } catch (Exception ex) { - throw new TransformException - ("Couldn't find Transform for: " + getAlgorithm(), ex); + throw new TransformException("Couldn't find Transform for: " + + getAlgorithm(), ex); } } @@ -135,36 +146,37 @@ public abstract class ApacheTransform extends TransformService { String algorithm = getAlgorithm(); if (Transforms.TRANSFORM_XSLT.equals(algorithm)) { throw new TransformException( - "Transform " + algorithm + - " is forbidden when secure validation is enabled"); + "Transform " + algorithm + " is forbidden when secure validation is enabled" + ); } } XMLSignatureInput in; if (data instanceof ApacheData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "ApacheData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ApacheData = true"); } - in = ((ApacheData) data).getXMLSignatureInput(); + in = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof NodeSetData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = true"); } if (data instanceof DOMSubTreeData) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "DOMSubTreeData = true"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "DOMSubTreeData = true"); } - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; in = new XMLSignatureInput(subTree.getRoot()); in.setExcludeComments(subTree.excludeComments()); } else { - Set nodeSet = - Utils.toNodeSet(((NodeSetData) data).iterator()); + @SuppressWarnings("unchecked") + Set nodeSet = + Utils.toNodeSet(((NodeSetData)data).iterator()); in = new XMLSignatureInput(nodeSet); } } else { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "isNodeSet() = false"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "isNodeSet() = false"); } try { in = new XMLSignatureInput diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java index 8348b45ece4..3fdf0c88240 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java @@ -2,33 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMBase64Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMBase64Transform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.security.InvalidAlgorithmParameterException; -import javax.xml.crypto.XMLStructure; import javax.xml.crypto.dsig.spec.TransformParameterSpec; /** diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java index 08c3edc16a6..1338ea6e720 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalXMLC14N11Method.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id$ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java index 0d37632b769..6e0ff530121 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalXMLC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCanonicalXMLC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java index 700694e2dd6..82b7c7608b6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java @@ -2,33 +2,36 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCanonicalizationMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCanonicalizationMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.io.OutputStream; import java.security.InvalidAlgorithmParameterException; import java.security.Provider; +import java.security.spec.AlgorithmParameterSpec; import org.w3c.dom.Element; @@ -49,7 +52,8 @@ public class DOMCanonicalizationMethod extends DOMTransform * @param spi TransformService */ public DOMCanonicalizationMethod(TransformService spi) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { super(spi); if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) { @@ -66,7 +70,9 @@ public class DOMCanonicalizationMethod extends DOMTransform * @param cmElem a CanonicalizationMethod element */ public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { super(cmElem, context, provider); if (!(spi instanceof ApacheCanonicalizer) && !isC14Nalg(spi.getAlgorithm())) { @@ -88,15 +94,18 @@ public class DOMCanonicalizationMethod extends DOMTransform * canonicalizing the data */ public Data canonicalize(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return transform(data, xc); } public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { return transform(data, xc, os); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -105,12 +114,24 @@ public class DOMCanonicalizationMethod extends DOMTransform if (!(o instanceof CanonicalizationMethod)) { return false; } - CanonicalizationMethod ocm = (CanonicalizationMethod) o; + CanonicalizationMethod ocm = (CanonicalizationMethod)o; return (getAlgorithm().equals(ocm.getAlgorithm()) && DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec())); } + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; + } + private static boolean isC14Nalg(String alg) { return (alg.equals(CanonicalizationMethod.INCLUSIVE) || alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) || diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java index 3b963b2a058..f5ff15e2dcd 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java @@ -2,34 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMCryptoBinary.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMCryptoBinary.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import java.math.BigInteger; import javax.xml.crypto.*; import javax.xml.crypto.dom.DOMCryptoContext; -import javax.xml.crypto.dsig.*; import org.w3c.dom.Node; import org.w3c.dom.Text; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java index e6f81b71e24..06c7bbf7d2c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMDigestMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMDigestMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -45,7 +47,7 @@ import org.w3c.dom.Node; public abstract class DOMDigestMethod extends DOMStructure implements DigestMethod { - final static String SHA384 = + static final String SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384"; // see RFC 4051 private DigestMethodParameterSpec params; @@ -57,13 +59,14 @@ public abstract class DOMDigestMethod extends DOMStructure * appropriate for this digest method */ DOMDigestMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null && !(params instanceof DigestMethodParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type DigestMethodParameterSpec"); } - checkParams((DigestMethodParameterSpec) params); - this.params = (DigestMethodParameterSpec) params; + checkParams((DigestMethodParameterSpec)params); + this.params = (DigestMethodParameterSpec)params; } /** @@ -96,8 +99,8 @@ public abstract class DOMDigestMethod extends DOMStructure } else if (alg.equals(DigestMethod.SHA512)) { return new SHA512(dmElem); } else { - throw new MarshalException - ("unsupported DigestMethod algorithm: " + alg); + throw new MarshalException("unsupported DigestMethod algorithm: " + + alg); } } @@ -112,11 +115,12 @@ public abstract class DOMDigestMethod extends DOMStructure * appropriate for this digest method */ void checkParams(DigestMethodParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { throw new InvalidAlgorithmParameterException("no parameters " + - "should be specified for the " + getMessageDigestAlgorithm() - + " DigestMethod algorithm"); + "should be specified for the " + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } } @@ -134,11 +138,13 @@ public abstract class DOMDigestMethod extends DOMStructure * @return the algorithm-specific DigestMethodParameterSpec * @throws MarshalException if the parameters cannot be unmarshalled */ - DigestMethodParameterSpec - unmarshalParams(Element paramsElem) throws MarshalException { + DigestMethodParameterSpec unmarshalParams(Element paramsElem) + throws MarshalException + { throw new MarshalException("no parameters should " + - "be specified for the " + getMessageDigestAlgorithm() + - " DigestMethod algorithm"); + "be specified for the " + + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } /** @@ -146,11 +152,12 @@ public abstract class DOMDigestMethod extends DOMStructure * method to marshal any algorithm-specific parameters. */ public void marshal(Node parent, String prefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element dmElem = DOMUtils.createElement - (ownerDoc, "DigestMethod", XMLSignature.XMLNS, prefix); + Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod", + XMLSignature.XMLNS, prefix); DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm()); if (params != null) { @@ -160,6 +167,7 @@ public abstract class DOMDigestMethod extends DOMStructure parent.appendChild(dmElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -168,7 +176,7 @@ public abstract class DOMDigestMethod extends DOMStructure if (!(o instanceof DigestMethod)) { return false; } - DigestMethod odm = (DigestMethod) o; + DigestMethod odm = (DigestMethod)o; boolean paramsEqual = (params == null ? odm.getParameterSpec() == null : params.equals(odm.getParameterSpec())); @@ -176,6 +184,17 @@ public abstract class DOMDigestMethod extends DOMStructure return (getAlgorithm().equals(odm.getAlgorithm()) && paramsEqual); } + @Override + public int hashCode() { + int result = 17; + if (params != null) { + result = 31 * result + params.hashCode(); + } + result = 31 * result + getAlgorithm().hashCode(); + + return result; + } + /** * Marshals the algorithm-specific parameters to an Element and * appends it to the specified parent element. By default, this method @@ -187,10 +206,12 @@ public abstract class DOMDigestMethod extends DOMStructure * @throws MarshalException if the parameters cannot be marshalled */ void marshalParams(Element parent, String prefix) - throws MarshalException { + throws MarshalException + { throw new MarshalException("no parameters should " + - "be specified for the " + getMessageDigestAlgorithm() + - " DigestMethod algorithm"); + "be specified for the " + + getMessageDigestAlgorithm() + + " DigestMethod algorithm"); } /** diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java index 0f0917ecd7a..163cd6804a6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMEnvelopedTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMEnvelopedTransform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java index 12d709117df..46943881fb3 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMExcC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMExcC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -50,18 +52,20 @@ import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerExcepti public final class DOMExcC14NMethod extends ApacheCanonicalizer { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { if (!(params instanceof ExcC14NParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type ExcC14NParameterSpec"); } - this.params = (C14NMethodParameterSpec) params; + this.params = (C14NMethodParameterSpec)params; } } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { super.init(parent, context); Element paramsElem = DOMUtils.getFirstChildElement(transformElem); if (paramsElem == null) { @@ -77,7 +81,7 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { this.inclusiveNamespaces = prefixListAttr; int begin = 0; int end = prefixListAttr.indexOf(' '); - List prefixList = new ArrayList(); + List prefixList = new ArrayList(); while (end != -1) { prefixList.add(prefixListAttr.substring(begin, end)); begin = end + 1; @@ -90,39 +94,42 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); AlgorithmParameterSpec spec = getParameterSpec(); if (spec == null) { return; } - String prefix = - DOMUtils.getNSPrefix(context, CanonicalizationMethod.EXCLUSIVE); - Element excElem = DOMUtils.createElement - (ownerDoc, "InclusiveNamespaces", - CanonicalizationMethod.EXCLUSIVE, prefix); + String prefix = DOMUtils.getNSPrefix(context, + CanonicalizationMethod.EXCLUSIVE); + Element eElem = DOMUtils.createElement(ownerDoc, + "InclusiveNamespaces", + CanonicalizationMethod.EXCLUSIVE, + prefix); if (prefix == null || prefix.length() == 0) { - excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", - CanonicalizationMethod.EXCLUSIVE); + eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", + CanonicalizationMethod.EXCLUSIVE); } else { - excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", - "xmlns:" + prefix, CanonicalizationMethod.EXCLUSIVE); + eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns:" + prefix, + CanonicalizationMethod.EXCLUSIVE); } - ExcC14NParameterSpec params = (ExcC14NParameterSpec) spec; + ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec; StringBuffer prefixListAttr = new StringBuffer(""); - List prefixList = params.getPrefixList(); + @SuppressWarnings("unchecked") + List prefixList = params.getPrefixList(); for (int i = 0, size = prefixList.size(); i < size; i++) { - prefixListAttr.append((String) prefixList.get(i)); + prefixListAttr.append(prefixList.get(i)); if (i < size - 1) { prefixListAttr.append(" "); } } - DOMUtils.setAttribute(excElem, "PrefixList", prefixListAttr.toString()); + DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString()); this.inclusiveNamespaces = prefixListAttr.toString(); - transformElem.appendChild(excElem); + transformElem.appendChild(eElem); } public String getParamsNSURI() { @@ -130,13 +137,13 @@ public final class DOMExcC14NMethod extends ApacheCanonicalizer { } public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { - + throws TransformException + { // ignore comments if dereferencing same-document URI that require // you to omit comments, even if the Transform says otherwise - // this is to be compliant with section 4.3.3.3 of W3C Rec. if (data instanceof DOMSubTreeData) { - DOMSubTreeData subTree = (DOMSubTreeData) data; + DOMSubTreeData subTree = (DOMSubTreeData)data; if (subTree.excludeComments()) { try { apacheCanonicalizer = Canonicalizer.getInstance diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java index b72d788633d..d193fa214e4 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMHMACSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMHMACSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -38,8 +40,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.security.spec.AlgorithmParameterSpec; -import java.util.logging.Level; -import java.util.logging.Logger; import javax.crypto.Mac; import javax.crypto.SecretKey; import org.w3c.dom.Document; @@ -52,13 +52,23 @@ import org.jcp.xml.dsig.internal.MacOutputStream; * * @author Sean Mullan */ -public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { +public abstract class DOMHMACSignatureMethod extends AbstractDOMSignatureMethod { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + + // see RFC 4051 for these algorithm definitions + static final String HMAC_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; + static final String HMAC_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; + static final String HMAC_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; - private static Logger log = - Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private Mac hmac; private int outputLength; private boolean outputLengthSet; + private SignatureMethodParameterSpec params; /** * Creates a DOMHMACSignatureMethod with the specified params @@ -67,8 +77,10 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { * @throws InvalidAlgorithmParameterException if params are inappropriate */ DOMHMACSignatureMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { - super(params); + throws InvalidAlgorithmParameterException + { + checkParams((SignatureMethodParameterSpec)params); + this.params = (SignatureMethodParameterSpec)params; } /** @@ -77,54 +89,64 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { * @param smElem a SignatureMethod element */ DOMHMACSignatureMethod(Element smElem) throws MarshalException { - super(smElem); + Element paramsElem = DOMUtils.getFirstChildElement(smElem); + if (paramsElem != null) { + params = unmarshalParams(paramsElem); + } + try { + checkParams(params); + } catch (InvalidAlgorithmParameterException iape) { + throw new MarshalException(iape); + } } void checkParams(SignatureMethodParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null) { if (!(params instanceof HMACParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type HMACParameterSpec"); } - outputLength = ((HMACParameterSpec) params).getOutputLength(); + outputLength = ((HMACParameterSpec)params).getOutputLength(); outputLengthSet = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, - "Setting outputLength from HMACParameterSpec to: " - + outputLength); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Setting outputLength from HMACParameterSpec to: " + outputLength); } - } else { - outputLength = -1; } } + public final AlgorithmParameterSpec getParameterSpec() { + return params; + } + SignatureMethodParameterSpec unmarshalParams(Element paramsElem) - throws MarshalException { - outputLength = new Integer - (paramsElem.getFirstChild().getNodeValue()).intValue(); + throws MarshalException + { + outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue(); outputLengthSet = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "unmarshalled outputLength: " + outputLength); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "unmarshalled outputLength: " + outputLength); } return new HMACParameterSpec(outputLength); } void marshalParams(Element parent, String prefix) - throws MarshalException { - + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength", - XMLSignature.XMLNS, prefix); + XMLSignature.XMLNS, prefix); hmacElem.appendChild(ownerDoc.createTextNode (String.valueOf(outputLength))); parent.appendChild(hmacElem); } - boolean verify(Key key, DOMSignedInfo si, byte[] sig, - XMLValidateContext context) - throws InvalidKeyException, SignatureException, XMLSignatureException { + boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException + { if (key == null || si == null || sig == null) { throw new NullPointerException(); } @@ -133,7 +155,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { } if (hmac == null) { try { - hmac = Mac.getInstance(getSignatureAlgorithm()); + hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -142,15 +164,16 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throw new XMLSignatureException ("HMACOutputLength must not be less than " + getDigestLength()); } - hmac.init((SecretKey) key); - si.canonicalize(context, new MacOutputStream(hmac)); + hmac.init((SecretKey)key); + ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac)); byte[] result = hmac.doFinal(); return MessageDigest.isEqual(sig, result); } - byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context) - throws InvalidKeyException, XMLSignatureException { + byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException + { if (key == null || si == null) { throw new NullPointerException(); } @@ -159,7 +182,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { } if (hmac == null) { try { - hmac = Mac.getInstance(getSignatureAlgorithm()); + hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -168,8 +191,8 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { throw new XMLSignatureException ("HMACOutputLength must not be less than " + getDigestLength()); } - hmac.init((SecretKey) key); - si.canonicalize(context, new MacOutputStream(hmac)); + hmac.init((SecretKey)key); + ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac)); return hmac.doFinal(); } @@ -180,11 +203,15 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { if (!(spec instanceof HMACParameterSpec)) { return false; } - HMACParameterSpec ospec = (HMACParameterSpec) spec; + HMACParameterSpec ospec = (HMACParameterSpec)spec; return (outputLength == ospec.getOutputLength()); } + Type getAlgorithmType() { + return Type.HMAC; + } + /** * Returns the output length of the hash/digest. */ @@ -201,7 +228,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return SignatureMethod.HMAC_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA1"; } int getDigestLength() { @@ -220,7 +247,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return HMAC_SHA256; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA256"; } int getDigestLength() { @@ -239,7 +266,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return HMAC_SHA384; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA384"; } int getDigestLength() { @@ -258,7 +285,7 @@ public abstract class DOMHMACSignatureMethod extends DOMSignatureMethod { public String getAlgorithm() { return HMAC_SHA512; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "HmacSHA512"; } int getDigestLength() { diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java index e9a3f1eca03..a7e70c07fc0 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java @@ -2,38 +2,40 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyInfo.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; -import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; import javax.xml.crypto.dom.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -48,7 +50,7 @@ import org.w3c.dom.NodeList; public final class DOMKeyInfo extends DOMStructure implements KeyInfo { private final String id; - private final List keyInfoTypes; + private final List keyInfoTypes; /** * Creates a DOMKeyInfo. @@ -62,21 +64,21 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { * @throws ClassCastException if content contains any entries * that are not of type {@link XMLStructure} */ - public DOMKeyInfo(List content, String id) { + public DOMKeyInfo(List content, String id) { if (content == null) { throw new NullPointerException("content cannot be null"); } - List typesCopy = new ArrayList(content); - if (typesCopy.isEmpty()) { + this.keyInfoTypes = + Collections.unmodifiableList(new ArrayList(content)); + if (this.keyInfoTypes.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } - for (int i = 0, size = typesCopy.size(); i < size; i++) { - if (!(typesCopy.get(i) instanceof XMLStructure)) { + for (int i = 0, size = this.keyInfoTypes.size(); i < size; i++) { + if (!(this.keyInfoTypes.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid KeyInfo type"); } } - this.keyInfoTypes = Collections.unmodifiableList(typesCopy); this.id = id; } @@ -86,7 +88,9 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { * @param kiElem KeyInfo element */ public DOMKeyInfo(Element kiElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // get Id attribute, if specified Attr attr = kiElem.getAttributeNodeNS(null, "Id"); if (attr != null) { @@ -103,24 +107,24 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { throw new MarshalException ("KeyInfo must contain at least one type"); } - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nl.item(i); // ignore all non-Element nodes if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } - Element childElem = (Element) child; + Element childElem = (Element)child; String localName = childElem.getLocalName(); if (localName.equals("X509Data")) { content.add(new DOMX509Data(childElem)); } else if (localName.equals("KeyName")) { content.add(new DOMKeyName(childElem)); } else if (localName.equals("KeyValue")) { - content.add(new DOMKeyValue(childElem)); + content.add(DOMKeyValue.unmarshal(childElem)); } else if (localName.equals("RetrievalMethod")) { - content.add - (new DOMRetrievalMethod(childElem, context, provider)); + content.add(new DOMRetrievalMethod(childElem, + context, provider)); } else if (localName.equals("PGPData")) { content.add(new DOMPGPData(childElem)); } else { //may be MgmtData, SPKIData or element from other namespace @@ -139,51 +143,58 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { } public void marshal(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { + throws MarshalException + { if (parent == null) { throw new NullPointerException("parent is null"); } + if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("parent must be of type DOMStructure"); + } - Node pNode = ((javax.xml.crypto.dom.DOMStructure) parent).getNode(); + Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode(); String dsPrefix = DOMUtils.getSignaturePrefix(context); Element kiElem = DOMUtils.createElement (DOMUtils.getOwnerDocument(pNode), "KeyInfo", XMLSignature.XMLNS, dsPrefix); if (dsPrefix == null || dsPrefix.length() == 0) { - kiElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); + kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns", XMLSignature.XMLNS); } else { - kiElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, - XMLSignature.XMLNS); + kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + "xmlns:" + dsPrefix, XMLSignature.XMLNS); } - marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext) context); + marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context); } public void marshal(Node parent, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { marshal(parent, null, dsPrefix, context); } public void marshal(Node parent, Node nextSibling, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element kiElem = DOMUtils.createElement - (ownerDoc, "KeyInfo", XMLSignature.XMLNS, dsPrefix); + Element kiElem = DOMUtils.createElement(ownerDoc, "KeyInfo", + XMLSignature.XMLNS, dsPrefix); marshal(parent, kiElem, nextSibling, dsPrefix, context); } private void marshal(Node parent, Element kiElem, Node nextSibling, - String dsPrefix, DOMCryptoContext context) throws MarshalException { + String dsPrefix, DOMCryptoContext context) + throws MarshalException + { // create and append KeyInfoType elements - for (int i = 0, size = keyInfoTypes.size(); i < size; i++) { - XMLStructure kiType = (XMLStructure) keyInfoTypes.get(i); + for (XMLStructure kiType : keyInfoTypes) { if (kiType instanceof DOMStructure) { - ((DOMStructure) kiType).marshal(kiElem, dsPrefix, context); + ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context); } else { DOMUtils.appendChild(kiElem, - ((javax.xml.crypto.dom.DOMStructure) kiType).getNode()); + ((javax.xml.crypto.dom.DOMStructure)kiType).getNode()); } } @@ -193,6 +204,7 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { parent.insertBefore(kiElem, nextSibling); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -201,11 +213,22 @@ public final class DOMKeyInfo extends DOMStructure implements KeyInfo { if (!(o instanceof KeyInfo)) { return false; } - KeyInfo oki = (KeyInfo) o; + KeyInfo oki = (KeyInfo)o; - boolean idsEqual = (id == null ? oki.getId() == null : - id.equals(oki.getId())); + boolean idsEqual = (id == null ? oki.getId() == null + : id.equals(oki.getId())); return (keyInfoTypes.equals(oki.getContent()) && idsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + keyInfoTypes.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java index 4db8575c792..33f2a227c7c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyInfoFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyInfoFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,8 +33,7 @@ import java.security.KeyException; import java.security.PublicKey; import java.util.List; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.*; -import javax.xml.crypto.dom.*; +import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.keyinfo.*; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -51,6 +52,7 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { return newKeyInfo(content, null); } + @SuppressWarnings("unchecked") public KeyInfo newKeyInfo(List content, String id) { return new DOMKeyInfo(content, id); } @@ -60,17 +62,28 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { } public KeyValue newKeyValue(PublicKey key) throws KeyException { - return new DOMKeyValue(key); + String algorithm = key.getAlgorithm(); + if (algorithm.equals("DSA")) { + return new DOMKeyValue.DSA(key); + } else if (algorithm.equals("RSA")) { + return new DOMKeyValue.RSA(key); + } else if (algorithm.equals("EC")) { + return new DOMKeyValue.EC(key); + } else { + throw new KeyException("unsupported key algorithm: " + algorithm); + } } public PGPData newPGPData(byte[] keyId) { return newPGPData(keyId, null, null); } + @SuppressWarnings("unchecked") public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) { return new DOMPGPData(keyId, keyPacket, other); } + @SuppressWarnings("unchecked") public PGPData newPGPData(byte[] keyPacket, List other) { return new DOMPGPData(keyPacket, other); } @@ -79,6 +92,7 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { return newRetrievalMethod(uri, null, null); } + @SuppressWarnings("unchecked") public RetrievalMethod newRetrievalMethod(String uri, String type, List transforms) { if (uri == null) { @@ -87,6 +101,7 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { return new DOMRetrievalMethod(uri, type, transforms); } + @SuppressWarnings("unchecked") public X509Data newX509Data(List content) { return new DOMX509Data(content); } @@ -113,6 +128,9 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { if (xmlStructure == null) { throw new NullPointerException("xmlStructure cannot be null"); } + if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("xmlStructure must be of type DOMStructure"); + } Node node = ((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(); node.normalize(); @@ -134,9 +152,14 @@ public final class DOMKeyInfoFactory extends KeyInfoFactory { "support DOM Level 2 and be namespace aware"); } if (tag.equals("KeyInfo")) { - return new DOMKeyInfo(element, null, getProvider()); + return new DOMKeyInfo(element, new UnmarshalContext(), getProvider()); } else { throw new MarshalException("invalid KeyInfo tag: " + tag); } } + + private static class UnmarshalContext extends DOMCryptoContext { + UnmarshalContext() {} + } + } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java index 55d4b881bc6..41db19aa725 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyName.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyName.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -71,15 +73,17 @@ public final class DOMKeyName extends DOMStructure implements KeyName { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); // prepend namespace prefix, if necessary - Element knElem = DOMUtils.createElement - (ownerDoc, "KeyName", XMLSignature.XMLNS, dsPrefix); + Element knElem = DOMUtils.createElement(ownerDoc, "KeyName", + XMLSignature.XMLNS, dsPrefix); knElem.appendChild(ownerDoc.createTextNode(name)); parent.appendChild(knElem); } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -87,7 +91,15 @@ public final class DOMKeyName extends DOMStructure implements KeyName { if (!(obj instanceof KeyName)) { return false; } - KeyName okn = (KeyName) obj; + KeyName okn = (KeyName)obj; return name.equals(okn.getName()); } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + name.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java index 6ff3eb79d04..9ebf06c2afb 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMKeyValue.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMKeyValue.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,14 +33,25 @@ import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.keyinfo.KeyValue; +// import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; import java.security.KeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPublicKey; +import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPublicKeySpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.EllipticCurve; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; @@ -46,59 +59,46 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; +import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; +import com.sun.org.apache.xml.internal.security.utils.Base64; + /** * DOM-based implementation of KeyValue. * * @author Sean Mullan */ -public final class DOMKeyValue extends DOMStructure implements KeyValue { +public abstract class DOMKeyValue extends DOMStructure implements KeyValue { - private KeyFactory rsakf, dsakf; - private PublicKey publicKey; - private javax.xml.crypto.dom.DOMStructure externalPublicKey; + private static final String XMLDSIG_11_XMLNS + = "http://www.w3.org/2009/xmldsig11#"; + private final PublicKey publicKey; - // DSAKeyValue CryptoBinaries - private DOMCryptoBinary p, q, g, y, j, seed, pgen; - - // RSAKeyValue CryptoBinaries - private DOMCryptoBinary modulus, exponent; - - public DOMKeyValue(PublicKey key) throws KeyException { + public DOMKeyValue(PublicKey key) throws KeyException { if (key == null) { throw new NullPointerException("key cannot be null"); } this.publicKey = key; - if (key instanceof DSAPublicKey) { - DSAPublicKey dkey = (DSAPublicKey) key; - DSAParams params = dkey.getParams(); - p = new DOMCryptoBinary(params.getP()); - q = new DOMCryptoBinary(params.getQ()); - g = new DOMCryptoBinary(params.getG()); - y = new DOMCryptoBinary(dkey.getY()); - } else if (key instanceof RSAPublicKey) { - RSAPublicKey rkey = (RSAPublicKey) key; - exponent = new DOMCryptoBinary(rkey.getPublicExponent()); - modulus = new DOMCryptoBinary(rkey.getModulus()); - } else { - throw new KeyException("unsupported key algorithm: " + - key.getAlgorithm()); - } } /** * Creates a DOMKeyValue from an element. * - * @param kvElem a KeyValue element + * @param kvtElem a KeyValue child element */ - public DOMKeyValue(Element kvElem) throws MarshalException { + public DOMKeyValue(Element kvtElem) throws MarshalException { + this.publicKey = unmarshalKeyValue(kvtElem); + } + + static KeyValue unmarshal(Element kvElem) throws MarshalException { Element kvtElem = DOMUtils.getFirstChildElement(kvElem); if (kvtElem.getLocalName().equals("DSAKeyValue")) { - publicKey = unmarshalDSAKeyValue(kvtElem); + return new DSA(kvtElem); } else if (kvtElem.getLocalName().equals("RSAKeyValue")) { - publicKey = unmarshalRSAKeyValue(kvtElem); + return new RSA(kvtElem); + } else if (kvtElem.getLocalName().equals("ECKeyValue")) { + return new EC(kvtElem); } else { - publicKey = null; - externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvtElem); + return new Unknown(kvtElem); } } @@ -111,133 +111,25 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); // create KeyValue element - Element kvElem = DOMUtils.createElement - (ownerDoc, "KeyValue", XMLSignature.XMLNS, dsPrefix); + Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue", + XMLSignature.XMLNS, dsPrefix); marshalPublicKey(kvElem, ownerDoc, dsPrefix, context); parent.appendChild(kvElem); } - private void marshalPublicKey(Node parent, Document doc, String dsPrefix, - DOMCryptoContext context) throws MarshalException { - if (publicKey != null) { - if (publicKey instanceof DSAPublicKey) { - // create and append DSAKeyValue element - marshalDSAPublicKey(parent, doc, dsPrefix, context); - } else if (publicKey instanceof RSAPublicKey) { - // create and append RSAKeyValue element - marshalRSAPublicKey(parent, doc, dsPrefix, context); - } else { - throw new MarshalException(publicKey.getAlgorithm() + - " public key algorithm not supported"); - } - } else { - parent.appendChild(externalPublicKey.getNode()); - } - } + abstract void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) throws MarshalException; - private void marshalDSAPublicKey(Node parent, Document doc, - String dsPrefix, DOMCryptoContext context) throws MarshalException { - Element dsaElem = DOMUtils.createElement - (doc, "DSAKeyValue", XMLSignature.XMLNS, dsPrefix); - // parameters J, Seed & PgenCounter are not included - Element pElem = DOMUtils.createElement - (doc, "P", XMLSignature.XMLNS, dsPrefix); - Element qElem = DOMUtils.createElement - (doc, "Q", XMLSignature.XMLNS, dsPrefix); - Element gElem = DOMUtils.createElement - (doc, "G", XMLSignature.XMLNS, dsPrefix); - Element yElem = DOMUtils.createElement - (doc, "Y", XMLSignature.XMLNS, dsPrefix); - p.marshal(pElem, dsPrefix, context); - q.marshal(qElem, dsPrefix, context); - g.marshal(gElem, dsPrefix, context); - y.marshal(yElem, dsPrefix, context); - dsaElem.appendChild(pElem); - dsaElem.appendChild(qElem); - dsaElem.appendChild(gElem); - dsaElem.appendChild(yElem); - parent.appendChild(dsaElem); - } + abstract PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException; - private void marshalRSAPublicKey(Node parent, Document doc, - String dsPrefix, DOMCryptoContext context) throws MarshalException { - Element rsaElem = DOMUtils.createElement - (doc, "RSAKeyValue", XMLSignature.XMLNS, dsPrefix); - Element modulusElem = DOMUtils.createElement - (doc, "Modulus", XMLSignature.XMLNS, dsPrefix); - Element exponentElem = DOMUtils.createElement - (doc, "Exponent", XMLSignature.XMLNS, dsPrefix); - modulus.marshal(modulusElem, dsPrefix, context); - exponent.marshal(exponentElem, dsPrefix, context); - rsaElem.appendChild(modulusElem); - rsaElem.appendChild(exponentElem); - parent.appendChild(rsaElem); - } - - private DSAPublicKey unmarshalDSAKeyValue(Element kvtElem) - throws MarshalException { - if (dsakf == null) { - try { - dsakf = KeyFactory.getInstance("DSA"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("unable to create DSA KeyFactory: " + - e.getMessage()); - } - } - Element curElem = DOMUtils.getFirstChildElement(kvtElem); - // check for P and Q - if (curElem.getLocalName().equals("P")) { - p = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - q = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - if (curElem.getLocalName().equals("G")) { - g = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - y = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - if (curElem != null && curElem.getLocalName().equals("J")) { - j = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - } - if (curElem != null) { - seed = new DOMCryptoBinary(curElem.getFirstChild()); - curElem = DOMUtils.getNextSiblingElement(curElem); - pgen = new DOMCryptoBinary(curElem.getFirstChild()); - } - //@@@ do we care about j, pgenCounter or seed? - DSAPublicKeySpec spec = new DSAPublicKeySpec - (y.getBigNum(), p.getBigNum(), q.getBigNum(), g.getBigNum()); - return (DSAPublicKey) generatePublicKey(dsakf, spec); - } - - private RSAPublicKey unmarshalRSAKeyValue(Element kvtElem) - throws MarshalException { - if (rsakf == null) { - try { - rsakf = KeyFactory.getInstance("RSA"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("unable to create RSA KeyFactory: " + - e.getMessage()); - } - } - Element modulusElem = DOMUtils.getFirstChildElement(kvtElem); - modulus = new DOMCryptoBinary(modulusElem.getFirstChild()); - Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem); - exponent = new DOMCryptoBinary(exponentElem.getFirstChild()); - RSAPublicKeySpec spec = new RSAPublicKeySpec - (modulus.getBigNum(), exponent.getBigNum()); - return (RSAPublicKey) generatePublicKey(rsakf, spec); - } - - private PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) { + private static PublicKey generatePublicKey(KeyFactory kf, KeySpec keyspec) { try { return kf.generatePublic(keyspec); } catch (InvalidKeySpecException e) { @@ -246,6 +138,7 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { } } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -254,7 +147,7 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { return false; } try { - KeyValue kv = (KeyValue) obj; + KeyValue kv = (KeyValue)obj; if (publicKey == null ) { if (kv.getPublicKey() != null) { return false; @@ -269,4 +162,340 @@ public final class DOMKeyValue extends DOMStructure implements KeyValue { return true; } + + @Override + public int hashCode() { + int result = 17; + if (publicKey != null) { + result = 31 * result + publicKey.hashCode(); + } + + return result; + } + + static final class RSA extends DOMKeyValue { + // RSAKeyValue CryptoBinaries + private DOMCryptoBinary modulus, exponent; + private KeyFactory rsakf; + + RSA(PublicKey key) throws KeyException { + super(key); + RSAPublicKey rkey = (RSAPublicKey)key; + exponent = new DOMCryptoBinary(rkey.getPublicExponent()); + modulus = new DOMCryptoBinary(rkey.getModulus()); + } + + RSA(Element elem) throws MarshalException { + super(elem); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) throws MarshalException { + Element rsaElem = DOMUtils.createElement(doc, "RSAKeyValue", + XMLSignature.XMLNS, + dsPrefix); + Element modulusElem = DOMUtils.createElement(doc, "Modulus", + XMLSignature.XMLNS, + dsPrefix); + Element exponentElem = DOMUtils.createElement(doc, "Exponent", + XMLSignature.XMLNS, + dsPrefix); + modulus.marshal(modulusElem, dsPrefix, context); + exponent.marshal(exponentElem, dsPrefix, context); + rsaElem.appendChild(modulusElem); + rsaElem.appendChild(exponentElem); + parent.appendChild(rsaElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (rsakf == null) { + try { + rsakf = KeyFactory.getInstance("RSA"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create RSA KeyFactory: " + e.getMessage()); + } + } + Element modulusElem = DOMUtils.getFirstChildElement(kvtElem); + modulus = new DOMCryptoBinary(modulusElem.getFirstChild()); + Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem); + exponent = new DOMCryptoBinary(exponentElem.getFirstChild()); + RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(), + exponent.getBigNum()); + return generatePublicKey(rsakf, spec); + } + } + + static final class DSA extends DOMKeyValue { + // DSAKeyValue CryptoBinaries + private DOMCryptoBinary p, q, g, y, j; //, seed, pgen; + private KeyFactory dsakf; + + DSA(PublicKey key) throws KeyException { + super(key); + DSAPublicKey dkey = (DSAPublicKey) key; + DSAParams params = dkey.getParams(); + p = new DOMCryptoBinary(params.getP()); + q = new DOMCryptoBinary(params.getQ()); + g = new DOMCryptoBinary(params.getG()); + y = new DOMCryptoBinary(dkey.getY()); + } + + DSA(Element elem) throws MarshalException { + super(elem); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue", + XMLSignature.XMLNS, + dsPrefix); + // parameters J, Seed & PgenCounter are not included + Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS, + dsPrefix); + Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS, + dsPrefix); + Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS, + dsPrefix); + Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS, + dsPrefix); + p.marshal(pElem, dsPrefix, context); + q.marshal(qElem, dsPrefix, context); + g.marshal(gElem, dsPrefix, context); + y.marshal(yElem, dsPrefix, context); + dsaElem.appendChild(pElem); + dsaElem.appendChild(qElem); + dsaElem.appendChild(gElem); + dsaElem.appendChild(yElem); + parent.appendChild(dsaElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (dsakf == null) { + try { + dsakf = KeyFactory.getInstance("DSA"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create DSA KeyFactory: " + e.getMessage()); + } + } + Element curElem = DOMUtils.getFirstChildElement(kvtElem); + // check for P and Q + if (curElem.getLocalName().equals("P")) { + p = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + q = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + } + if (curElem.getLocalName().equals("G")) { + g = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + } + y = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + if (curElem != null && curElem.getLocalName().equals("J")) { + j = new DOMCryptoBinary(curElem.getFirstChild()); + // curElem = DOMUtils.getNextSiblingElement(curElem); + } + /* + if (curElem != null) { + seed = new DOMCryptoBinary(curElem.getFirstChild()); + curElem = DOMUtils.getNextSiblingElement(curElem); + pgen = new DOMCryptoBinary(curElem.getFirstChild()); + } + */ + //@@@ do we care about j, pgenCounter or seed? + DSAPublicKeySpec spec = new DSAPublicKeySpec(y.getBigNum(), + p.getBigNum(), + q.getBigNum(), + g.getBigNum()); + return generatePublicKey(dsakf, spec); + } + } + + static final class EC extends DOMKeyValue { + // ECKeyValue CryptoBinaries + private byte[] ecPublicKey; + private KeyFactory eckf; + private ECParameterSpec ecParams; + private Method encodePoint, decodePoint, getCurveName, + getECParameterSpec; + + EC(PublicKey key) throws KeyException { + super(key); + ECPublicKey ecKey = (ECPublicKey)key; + ECPoint ecPoint = ecKey.getW(); + ecParams = ecKey.getParams(); + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws + ClassNotFoundException, NoSuchMethodException + { + getMethods(); + return null; + } + } + ); + } catch (PrivilegedActionException pae) { + throw new KeyException("ECKeyValue not supported", + pae.getException()); + } + Object[] args = new Object[] { ecPoint, ecParams.getCurve() }; + try { + ecPublicKey = (byte[])encodePoint.invoke(null, args); + } catch (IllegalAccessException iae) { + throw new KeyException(iae); + } catch (InvocationTargetException ite) { + throw new KeyException(ite); + } + } + + EC(Element dmElem) throws MarshalException { + super(dmElem); + } + + void getMethods() throws ClassNotFoundException, NoSuchMethodException { + Class c = Class.forName("sun.security.ec.ECParameters"); + Class[] params = new Class[] { ECPoint.class, EllipticCurve.class }; + encodePoint = c.getMethod("encodePoint", params); + params = new Class[] { ECParameterSpec.class }; + getCurveName = c.getMethod("getCurveName", params); + params = new Class[] { byte[].class, EllipticCurve.class }; + decodePoint = c.getMethod("decodePoint", params); + c = Class.forName("sun.security.ec.NamedCurve"); + params = new Class[] { String.class }; + getECParameterSpec = c.getMethod("getECParameterSpec", params); + } + + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + String prefix = DOMUtils.getNSPrefix(context, XMLDSIG_11_XMLNS); + Element ecKeyValueElem = DOMUtils.createElement(doc, "ECKeyValue", + XMLDSIG_11_XMLNS, + prefix); + Element namedCurveElem = DOMUtils.createElement(doc, "NamedCurve", + XMLDSIG_11_XMLNS, + prefix); + Element publicKeyElem = DOMUtils.createElement(doc, "PublicKey", + XMLDSIG_11_XMLNS, + prefix); + Object[] args = new Object[] { ecParams }; + try { + String oid = (String) getCurveName.invoke(null, args); + DOMUtils.setAttribute(namedCurveElem, "URI", "urn:oid:" + oid); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } + String qname = (prefix == null || prefix.length() == 0) + ? "xmlns" : "xmlns:" + prefix; + namedCurveElem.setAttributeNS("http://www.w3.org/2000/xmlns/", + qname, XMLDSIG_11_XMLNS); + ecKeyValueElem.appendChild(namedCurveElem); + String encoded = Base64.encode(ecPublicKey); + publicKeyElem.appendChild + (DOMUtils.getOwnerDocument(publicKeyElem).createTextNode(encoded)); + ecKeyValueElem.appendChild(publicKeyElem); + parent.appendChild(ecKeyValueElem); + } + + PublicKey unmarshalKeyValue(Element kvtElem) + throws MarshalException + { + if (eckf == null) { + try { + eckf = KeyFactory.getInstance("EC"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException + ("unable to create EC KeyFactory: " + e.getMessage()); + } + } + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws + ClassNotFoundException, NoSuchMethodException + { + getMethods(); + return null; + } + } + ); + } catch (PrivilegedActionException pae) { + throw new MarshalException("ECKeyValue not supported", + pae.getException()); + } + ECParameterSpec ecParams = null; + Element curElem = DOMUtils.getFirstChildElement(kvtElem); + if (curElem.getLocalName().equals("ECParameters")) { + throw new UnsupportedOperationException + ("ECParameters not supported"); + } else if (curElem.getLocalName().equals("NamedCurve")) { + String uri = DOMUtils.getAttributeValue(curElem, "URI"); + // strip off "urn:oid" + if (uri.startsWith("urn:oid:")) { + String oid = uri.substring(8); + try { + Object[] args = new Object[] { oid }; + ecParams = (ECParameterSpec) + getECParameterSpec.invoke(null, args); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } + } else { + throw new MarshalException("Invalid NamedCurve URI"); + } + } else { + throw new MarshalException("Invalid ECKeyValue"); + } + curElem = DOMUtils.getNextSiblingElement(curElem); + ECPoint ecPoint = null; + try { + Object[] args = new Object[] { Base64.decode(curElem), + ecParams.getCurve() }; + ecPoint = (ECPoint)decodePoint.invoke(null, args); + } catch (Base64DecodingException bde) { + throw new MarshalException("Invalid EC PublicKey", bde); + } catch (IllegalAccessException iae) { + throw new MarshalException(iae); + } catch (InvocationTargetException ite) { + throw new MarshalException(ite); + } +/* + ecPoint = sun.security.ec.ECParameters.decodePoint( + Base64.decode(curElem), ecParams.getCurve()); +*/ + ECPublicKeySpec spec = new ECPublicKeySpec(ecPoint, ecParams); + return generatePublicKey(eckf, spec); + } + } + + static final class Unknown extends DOMKeyValue { + private javax.xml.crypto.dom.DOMStructure externalPublicKey; + Unknown(Element elem) throws MarshalException { + super(elem); + } + PublicKey unmarshalKeyValue(Element kvElem) throws MarshalException { + externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvElem); + return null; + } + void marshalPublicKey(Node parent, Document doc, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { + parent.appendChild(externalPublicKey.getNode()); + } + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java index 0da7241ec59..e8f41ef4e06 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMManifest.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -32,6 +34,7 @@ import javax.xml.crypto.dsig.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -44,7 +47,7 @@ import org.w3c.dom.Node; */ public final class DOMManifest extends DOMStructure implements Manifest { - private final List references; + private final List references; private final String id; /** @@ -60,22 +63,22 @@ public final class DOMManifest extends DOMStructure implements Manifest { * @throws ClassCastException if references contains any * entries that are not of type {@link Reference} */ - public DOMManifest(List references, String id) { + public DOMManifest(List references, String id) { if (references == null) { throw new NullPointerException("references cannot be null"); } - List refCopy = new ArrayList(references); - if (refCopy.isEmpty()) { + this.references = + Collections.unmodifiableList(new ArrayList(references)); + if (this.references.isEmpty()) { throw new IllegalArgumentException("list of references must " + "contain at least one entry"); } - for (int i = 0, size = refCopy.size(); i < size; i++) { - if (!(refCopy.get(i) instanceof Reference)) { + for (int i = 0, size = this.references.size(); i < size; i++) { + if (!(this.references.get(i) instanceof Reference)) { throw new ClassCastException ("references["+i+"] is not a valid type"); } } - this.references = Collections.unmodifiableList(refCopy); this.id = id; } @@ -85,7 +88,9 @@ public final class DOMManifest extends DOMStructure implements Manifest { * @param manElem a Manifest element */ public DOMManifest(Element manElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { Attr attr = manElem.getAttributeNodeNS(null, "Id"); if (attr != null) { this.id = attr.getValue(); @@ -95,8 +100,10 @@ public final class DOMManifest extends DOMStructure implements Manifest { } boolean secVal = Utils.secureValidation(context); + Element refElem = DOMUtils.getFirstChildElement(manElem); - List refs = new ArrayList(); + List refs = new ArrayList(); + int refCount = 0; while (refElem != null) { refs.add(new DOMReference(refElem, context, provider)); @@ -104,10 +111,8 @@ public final class DOMManifest extends DOMStructure implements Manifest { refCount++; if (secVal && (refCount > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) { - String error = "A maxiumum of " + - DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + - " references per Manifest are allowed with" + - " secure validation"; + String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " " + + "references per Manifest are allowed with secure validation"; throw new MarshalException(error); } } @@ -123,22 +128,22 @@ public final class DOMManifest extends DOMStructure implements Manifest { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element manElem = DOMUtils.createElement - (ownerDoc, "Manifest", XMLSignature.XMLNS, dsPrefix); + Element manElem = DOMUtils.createElement(ownerDoc, "Manifest", + XMLSignature.XMLNS, dsPrefix); DOMUtils.setAttributeID(manElem, "Id", id); // add references - for (int i = 0, size = references.size(); i < size; i++) { - DOMReference ref = (DOMReference) references.get(i); - ref.marshal(manElem, dsPrefix, context); + for (Reference ref : references) { + ((DOMReference)ref).marshal(manElem, dsPrefix, context); } parent.appendChild(manElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -147,11 +152,22 @@ public final class DOMManifest extends DOMStructure implements Manifest { if (!(o instanceof Manifest)) { return false; } - Manifest oman = (Manifest) o; + Manifest oman = (Manifest)o; - boolean idsEqual = (id == null ? oman.getId() == null : - id.equals(oman.getId())); + boolean idsEqual = (id == null ? oman.getId() == null + : id.equals(oman.getId())); return (idsEqual && references.equals(oman.getReferences())); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + references.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java index b8a65ce2aa2..d37cb62880c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMPGPData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMPGPData.java 1203846 2011-11-18 21:18:17Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -48,7 +50,7 @@ public final class DOMPGPData extends DOMStructure implements PGPData { private final byte[] keyId; private final byte[] keyPacket; - private final List externalElements; + private final List externalElements; /** * Creates a DOMPGPData containing the specified key packet. @@ -67,23 +69,23 @@ public final class DOMPGPData extends DOMStructure implements PGPData { * @throws ClassCastException if other contains any * entries that are not of type {@link XMLStructure} */ - public DOMPGPData(byte[] keyPacket, List other) { + public DOMPGPData(byte[] keyPacket, List other) { if (keyPacket == null) { throw new NullPointerException("keyPacket cannot be null"); } if (other == null || other.isEmpty()) { - this.externalElements = Collections.EMPTY_LIST; + this.externalElements = Collections.emptyList(); } else { - List otherCopy = new ArrayList(other); - for (int i = 0, size = otherCopy.size(); i < size; i++) { - if (!(otherCopy.get(i) instanceof XMLStructure)) { + this.externalElements = + Collections.unmodifiableList(new ArrayList(other)); + for (int i = 0, size = this.externalElements.size(); i < size; i++) { + if (!(this.externalElements.get(i) instanceof XMLStructure)) { throw new ClassCastException ("other["+i+"] is not a valid PGPData type"); } } - this.externalElements = Collections.unmodifiableList(otherCopy); } - this.keyPacket = (byte []) keyPacket.clone(); + this.keyPacket = (byte[])keyPacket.clone(); checkKeyPacket(keyPacket); this.keyId = null; } @@ -108,7 +110,9 @@ public final class DOMPGPData extends DOMStructure implements PGPData { * @throws ClassCastException if other contains any * entries that are not of type {@link XMLStructure} */ - public DOMPGPData(byte[] keyId, byte[] keyPacket, List other) { + public DOMPGPData(byte[] keyId, byte[] keyPacket, + List other) + { if (keyId == null) { throw new NullPointerException("keyId cannot be null"); } @@ -117,19 +121,20 @@ public final class DOMPGPData extends DOMStructure implements PGPData { throw new IllegalArgumentException("keyId must be 8 bytes long"); } if (other == null || other.isEmpty()) { - this.externalElements = Collections.EMPTY_LIST; + this.externalElements = Collections.emptyList(); } else { - List otherCopy = new ArrayList(other); - for (int i = 0, size = otherCopy.size(); i < size; i++) { - if (!(otherCopy.get(i) instanceof XMLStructure)) { + this.externalElements = + Collections.unmodifiableList(new ArrayList(other)); + for (int i = 0, size = this.externalElements.size(); i < size; i++) { + if (!(this.externalElements.get(i) instanceof XMLStructure)) { throw new ClassCastException ("other["+i+"] is not a valid PGPData type"); } } - this.externalElements = Collections.unmodifiableList(otherCopy); } - this.keyId = (byte []) keyId.clone(); - this.keyPacket = keyPacket == null ? null : (byte []) keyPacket.clone(); + this.keyId = (byte[])keyId.clone(); + this.keyPacket = keyPacket == null ? null + : (byte[])keyPacket.clone(); if (keyPacket != null) { checkKeyPacket(keyPacket); } @@ -146,11 +151,11 @@ public final class DOMPGPData extends DOMStructure implements PGPData { byte[] keyPacket = null; NodeList nl = pdElem.getChildNodes(); int length = nl.getLength(); - List other = new ArrayList(length); + List other = new ArrayList(length); for (int x = 0; x < length; x++) { Node n = nl.item(x); if (n.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element) n; + Element childElem = (Element)n; String localName = childElem.getLocalName(); try { if (localName.equals("PGPKeyID")) { @@ -172,11 +177,11 @@ public final class DOMPGPData extends DOMStructure implements PGPData { } public byte[] getKeyId() { - return (keyId == null ? null : (byte []) keyId.clone()); + return (keyId == null ? null : (byte[])keyId.clone()); } public byte[] getKeyPacket() { - return (keyPacket == null ? null : (byte []) keyPacket.clone()); + return (keyPacket == null ? null : (byte[])keyPacket.clone()); } public List getExternalElements() { @@ -184,16 +189,17 @@ public final class DOMPGPData extends DOMStructure implements PGPData { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element pdElem = DOMUtils.createElement - (ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix); + Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData", + XMLSignature.XMLNS, dsPrefix); // create and append PGPKeyID element if (keyId != null) { - Element keyIdElem = DOMUtils.createElement - (ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix); + Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID", + XMLSignature.XMLNS, + dsPrefix); keyIdElem.appendChild (ownerDoc.createTextNode(Base64.encode(keyId))); pdElem.appendChild(keyIdElem); @@ -201,17 +207,19 @@ public final class DOMPGPData extends DOMStructure implements PGPData { // create and append PGPKeyPacket element if (keyPacket != null) { - Element keyPktElem = DOMUtils.createElement - (ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix); + Element keyPktElem = DOMUtils.createElement(ownerDoc, + "PGPKeyPacket", + XMLSignature.XMLNS, + dsPrefix); keyPktElem.appendChild (ownerDoc.createTextNode(Base64.encode(keyPacket))); pdElem.appendChild(keyPktElem); } // create and append any elements - for (int i = 0, size = externalElements.size(); i < size; i++) { + for (XMLStructure extElem : externalElements) { DOMUtils.appendChild(pdElem, ((javax.xml.crypto.dom.DOMStructure) - externalElements.get(i)).getNode()); + extElem).getNode()); } parent.appendChild(pdElem); @@ -229,26 +237,26 @@ public final class DOMPGPData extends DOMStructure implements PGPData { // and minimally one byte of content if (keyPacket.length < 3) { throw new IllegalArgumentException("keypacket must be at least " + - "3 bytes long"); + "3 bytes long"); } int tag = keyPacket[0]; // first bit must be set if ((tag & 128) != 128) { throw new IllegalArgumentException("keypacket tag is invalid: " + - "bit 7 is not set"); + "bit 7 is not set"); } // make sure using new format if ((tag & 64) != 64) { throw new IllegalArgumentException("old keypacket tag format is " + - "unsupported"); + "unsupported"); } // tag value must be 6, 14, 5 or 7 if (((tag & 6) != 6) && ((tag & 14) != 14) && ((tag & 5) != 5) && ((tag & 7) != 7)) { throw new IllegalArgumentException("keypacket tag is invalid: " + - "must be 6, 14, 5, or 7"); + "must be 6, 14, 5, or 7"); } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java index 6d92f75bf86..132497838e3 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMReference.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMReference.java 1334007 2012-05-04 14:59:46Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -43,8 +45,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.security.*; import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -66,11 +66,10 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream public final class DOMReference extends DOMStructure implements Reference, DOMURIReference { - /** - * The maximum number of transforms per reference, if secure validation - * is enabled. - */ - public static final int MAXIMUM_TRANSFORM_COUNT = 5; + /** + * The maximum number of transforms per reference, if secure validation is enabled. + */ + public static final int MAXIMUM_TRANSFORM_COUNT = 5; /** * Look up useC14N11 system property. If true, an explicit C14N11 transform @@ -82,17 +81,18 @@ public final class DOMReference extends DOMStructure private static boolean useC14N11 = AccessController.doPrivileged(new PrivilegedAction() { public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.useC14N11"); + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.useC14N11")); } }); - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private final DigestMethod digestMethod; private final String id; - private final List transforms; - private List allTransforms; + private final List transforms; + private List allTransforms; private final Data appliedTransformData; private Attr here; private final String uri; @@ -124,46 +124,51 @@ public final class DOMReference extends DOMStructure * not of type Transform */ public DOMReference(String uri, String type, DigestMethod dm, - List transforms, String id, Provider provider) { + List transforms, String id, + Provider provider) + { this(uri, type, dm, null, null, transforms, id, null, provider); } public DOMReference(String uri, String type, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String id, - Provider provider) { + List appliedTransforms, + Data result, List transforms, + String id, Provider provider) + { this(uri, type, dm, appliedTransforms, result, transforms, id, null, provider); } public DOMReference(String uri, String type, DigestMethod dm, - List appliedTransforms, Data result, List transforms, String id, - byte[] digestValue, Provider provider) { + List appliedTransforms, + Data result, List transforms, + String id, byte[] digestValue, Provider provider) + { if (dm == null) { throw new NullPointerException("DigestMethod must be non-null"); } - this.allTransforms = new ArrayList(); - if (appliedTransforms != null) { - List transformsCopy = new ArrayList(appliedTransforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + if (appliedTransforms == null) { + this.allTransforms = new ArrayList(); + } else { + this.allTransforms = new ArrayList(appliedTransforms); + for (int i = 0, size = this.allTransforms.size(); i < size; i++) { + if (!(this.allTransforms.get(i) instanceof Transform)) { throw new ClassCastException ("appliedTransforms["+i+"] is not a valid type"); } } - this.allTransforms = transformsCopy; } if (transforms == null) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { - List transformsCopy = new ArrayList(transforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + this.transforms = new ArrayList(transforms); + for (int i = 0, size = this.transforms.size(); i < size; i++) { + if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } - this.transforms = transformsCopy; - this.allTransforms.addAll(transformsCopy); + this.allTransforms.addAll(this.transforms); } this.digestMethod = dm; this.uri = uri; @@ -177,7 +182,7 @@ public final class DOMReference extends DOMStructure this.type = type; this.id = id; if (digestValue != null) { - this.digestValue = (byte[]) digestValue.clone(); + this.digestValue = (byte[])digestValue.clone(); this.digested = true; } this.appliedTransformData = result; @@ -190,12 +195,14 @@ public final class DOMReference extends DOMStructure * @param refElem a Reference element */ public DOMReference(Element refElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { boolean secVal = Utils.secureValidation(context); // unmarshal Transforms, if specified Element nextSibling = DOMUtils.getFirstChildElement(refElem); - List transforms = new ArrayList(5); + List transforms = new ArrayList(5); if (nextSibling.getLocalName().equals("Transforms")) { Element transformElem = DOMUtils.getFirstChildElement(nextSibling); @@ -207,9 +214,8 @@ public final class DOMReference extends DOMStructure transformCount++; if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) { - String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + - " transforms per Reference are allowed" + - " with secure validation"; + String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " " + + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } } @@ -221,11 +227,10 @@ public final class DOMReference extends DOMStructure this.digestMethod = DOMDigestMethod.unmarshal(dmElem); String digestMethodAlgorithm = this.digestMethod.getAlgorithm(); if (secVal - && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) - { - throw new MarshalException("It is forbidden to use algorithm " + - digestMethod + - " when secure validation is enabled"); + && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) { + throw new MarshalException( + "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled" + ); } // unmarshal DigestValue @@ -277,23 +282,24 @@ public final class DOMReference extends DOMStructure } public byte[] getDigestValue() { - return (digestValue == null ? null : (byte[]) digestValue.clone()); + return (digestValue == null ? null : (byte[])digestValue.clone()); } public byte[] getCalculatedDigestValue() { return (calcDigestValue == null ? null - : (byte[]) calcDigestValue.clone()); + : (byte[])calcDigestValue.clone()); } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Marshalling Reference"); + throws MarshalException + { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Marshalling Reference"); } Document ownerDoc = DOMUtils.getOwnerDocument(parent); - refElem = DOMUtils.createElement - (ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix); + refElem = DOMUtils.createElement(ownerDoc, "Reference", + XMLSignature.XMLNS, dsPrefix); // set attributes DOMUtils.setAttributeID(refElem, "Id", id); @@ -302,25 +308,28 @@ public final class DOMReference extends DOMStructure // create and append Transforms element if (!allTransforms.isEmpty()) { - Element transformsElem = DOMUtils.createElement - (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix); + Element transformsElem = DOMUtils.createElement(ownerDoc, + "Transforms", + XMLSignature.XMLNS, + dsPrefix); refElem.appendChild(transformsElem); - for (int i = 0, size = allTransforms.size(); i < size; i++) { - DOMStructure transform = - (DOMStructure) allTransforms.get(i); - transform.marshal(transformsElem, dsPrefix, context); + for (Transform transform : allTransforms) { + ((DOMStructure)transform).marshal(transformsElem, + dsPrefix, context); } } // create and append DigestMethod element - ((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context); + ((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context); // create and append DigestValue element - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Adding digestValueElem"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Adding digestValueElem"); } - Element digestValueElem = DOMUtils.createElement - (ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix); + Element digestValueElem = DOMUtils.createElement(ownerDoc, + "DigestValue", + XMLSignature.XMLNS, + dsPrefix); if (digestValue != null) { digestValueElem.appendChild (ownerDoc.createTextNode(Base64.encode(digestValue))); @@ -332,7 +341,8 @@ public final class DOMReference extends DOMStructure } public void digest(XMLSignContext signContext) - throws XMLSignatureException { + throws XMLSignatureException + { Data data = null; if (appliedTransformData == null) { data = dereference(signContext); @@ -343,8 +353,8 @@ public final class DOMReference extends DOMStructure // insert digestValue into DigestValue element String encodedDV = Base64.encode(digestValue); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference object uri = " + uri); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference object uri = " + uri); } Element digestElem = DOMUtils.getLastChildElement(refElem); if (digestElem == null) { @@ -355,13 +365,14 @@ public final class DOMReference extends DOMStructure (refElem.getOwnerDocument().createTextNode(encodedDV)); digested = true; - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference digesting completed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference digesting completed"); } } public boolean validate(XMLValidateContext validateContext) - throws XMLSignatureException { + throws XMLSignatureException + { if (validateContext == null) { throw new NullPointerException("validateContext cannot be null"); } @@ -371,11 +382,9 @@ public final class DOMReference extends DOMStructure Data data = dereference(validateContext); calcDigestValue = transform(data, validateContext); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Expected digest: " - + Base64.encode(digestValue)); - log.log(Level.FINE, "Actual digest: " - + Base64.encode(calcDigestValue)); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Expected digest: " + Base64.encode(digestValue)); + log.log(java.util.logging.Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue)); } validationStatus = Arrays.equals(digestValue, calcDigestValue); @@ -392,7 +401,8 @@ public final class DOMReference extends DOMStructure } private Data dereference(XMLCryptoContext context) - throws XMLSignatureException { + throws XMLSignatureException + { Data data = null; // use user-specified URIDereferencer if specified; otherwise use deflt @@ -402,11 +412,9 @@ public final class DOMReference extends DOMStructure } try { data = deref.dereference(this, context); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "URIDereferencer class name: " - + deref.getClass().getName()); - log.log(Level.FINE, "Data class name: " - + data.getClass().getName()); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "URIDereferencer class name: " + deref.getClass().getName()); + log.log(java.util.logging.Level.FINE, "Data class name: " + data.getClass().getName()); } } catch (URIReferenceException ure) { throw new XMLSignatureException(ure); @@ -416,12 +424,13 @@ public final class DOMReference extends DOMStructure } private byte[] transform(Data dereferencedData, - XMLCryptoContext context) throws XMLSignatureException { - + XMLCryptoContext context) + throws XMLSignatureException + { if (md == null) { try { md = MessageDigest.getInstance - (((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm()); + (((DOMDigestMethod)digestMethod).getMessageDigestAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } @@ -430,28 +439,25 @@ public final class DOMReference extends DOMStructure DigesterOutputStream dos; Boolean cache = (Boolean) context.getProperty("javax.xml.crypto.dsig.cacheReference"); - if (cache != null && cache.booleanValue() == true) { + if (cache != null && cache.booleanValue()) { this.derefData = copyDerefData(dereferencedData); dos = new DigesterOutputStream(md, true); } else { dos = new DigesterOutputStream(md); } - OutputStream os = new UnsyncBufferedOutputStream(dos); + OutputStream os = null; Data data = dereferencedData; - for (int i = 0, size = transforms.size(); i < size; i++) { - DOMTransform transform = (DOMTransform) transforms.get(i); - try { + try { + os = new UnsyncBufferedOutputStream(dos); + for (int i = 0, size = transforms.size(); i < size; i++) { + DOMTransform transform = (DOMTransform)transforms.get(i); if (i < size - 1) { data = transform.transform(data, context); } else { data = transform.transform(data, context, os); } - } catch (TransformException te) { - throw new XMLSignatureException(te); } - } - try { if (data != null) { XMLSignatureInput xi; // explicitly use C14N 1.1 when generating signature @@ -460,9 +466,9 @@ public final class DOMReference extends DOMStructure String c14nalg = CanonicalizationMethod.INCLUSIVE; if (context instanceof XMLSignContext) { if (!c14n11) { - Boolean prop = (Boolean) context.getProperty + Boolean prop = (Boolean)context.getProperty ("com.sun.org.apache.xml.internal.security.useC14N11"); - c14n11 = (prop != null && prop.booleanValue() == true); + c14n11 = (prop != null && prop.booleanValue()); if (c14n11) { c14nalg = "http://www.w3.org/2006/12/xml-c14n11"; } @@ -471,17 +477,20 @@ public final class DOMReference extends DOMStructure } } if (data instanceof ApacheData) { - xi = ((ApacheData) data).getXMLSignatureInput(); + xi = ((ApacheData)data).getXMLSignatureInput(); } else if (data instanceof OctetStreamData) { xi = new XMLSignatureInput (((OctetStreamData)data).getOctetStream()); } else if (data instanceof NodeSetData) { TransformService spi = null; - try { + if (provider == null) { spi = TransformService.getInstance(c14nalg, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance - (c14nalg, "DOM", provider); + } else { + try { + spi = TransformService.getInstance(c14nalg, "DOM", provider); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } } data = spi.transform(data, context); xi = new XMLSignatureInput @@ -491,8 +500,18 @@ public final class DOMReference extends DOMStructure } if (context instanceof XMLSignContext && c14n11 && !xi.isOctetStream() && !xi.isOutputStreamSet()) { - DOMTransform t = new DOMTransform - (TransformService.getInstance(c14nalg, "DOM")); + TransformService spi = null; + if (provider == null) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } else { + try { + spi = TransformService.getInstance(c14nalg, "DOM", provider); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(c14nalg, "DOM"); + } + } + + DOMTransform t = new DOMTransform(spi); Element transformsElem = null; String dsPrefix = DOMUtils.getSignaturePrefix(context); if (allTransforms.isEmpty()) { @@ -504,7 +523,8 @@ public final class DOMReference extends DOMStructure } else { transformsElem = DOMUtils.getFirstChildElement(refElem); } - t.marshal(transformsElem, dsPrefix, (DOMCryptoContext) context); + t.marshal(transformsElem, dsPrefix, + (DOMCryptoContext)context); allTransforms.add(t); xi.updateOutputStream(os, true); } else { @@ -512,12 +532,35 @@ public final class DOMReference extends DOMStructure } } os.flush(); - if (cache != null && cache.booleanValue() == true) { + if (cache != null && cache.booleanValue()) { this.dis = dos.getInputStream(); } return dos.getDigestValue(); - } catch (Exception e) { + } catch (NoSuchAlgorithmException e) { throw new XMLSignatureException(e); + } catch (TransformException e) { + throw new XMLSignatureException(e); + } catch (MarshalException e) { + throw new XMLSignatureException(e); + } catch (IOException e) { + throw new XMLSignatureException(e); + } catch (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) { + throw new XMLSignatureException(e); + } finally { + if (os != null) { + try { + os.close(); + } catch (IOException e) { + throw new XMLSignatureException(e); + } + } + if (dos != null) { + try { + dos.close(); + } catch (IOException e) { + throw new XMLSignatureException(e); + } + } } } @@ -525,6 +568,7 @@ public final class DOMReference extends DOMStructure return here; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -533,19 +577,41 @@ public final class DOMReference extends DOMStructure if (!(o instanceof Reference)) { return false; } - Reference oref = (Reference) o; + Reference oref = (Reference)o; - boolean idsEqual = (id == null ? oref.getId() == null : - id.equals(oref.getId())); - boolean urisEqual = (uri == null ? oref.getURI() == null : - uri.equals(oref.getURI())); - boolean typesEqual = (type == null ? oref.getType() == null : - type.equals(oref.getType())); + boolean idsEqual = (id == null ? oref.getId() == null + : id.equals(oref.getId())); + boolean urisEqual = (uri == null ? oref.getURI() == null + : uri.equals(oref.getURI())); + boolean typesEqual = (type == null ? oref.getType() == null + : type.equals(oref.getType())); boolean digestValuesEqual = Arrays.equals(digestValue, oref.getDigestValue()); - return (digestMethod.equals(oref.getDigestMethod()) && idsEqual && - urisEqual && typesEqual && allTransforms.equals(oref.getTransforms())); + return digestMethod.equals(oref.getDigestMethod()) && idsEqual && + urisEqual && typesEqual && + allTransforms.equals(oref.getTransforms()) && digestValuesEqual; + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (uri != null) { + result = 31 * result + uri.hashCode(); + } + if (type != null) { + result = 31 * result + type.hashCode(); + } + if (digestValue != null) { + result = 31 * result + Arrays.hashCode(digestValue); + } + result = 31 * result + digestMethod.hashCode(); + result = 31 * result + allTransforms.hashCode(); + + return result; } boolean isDigested() { @@ -555,18 +621,17 @@ public final class DOMReference extends DOMStructure private static Data copyDerefData(Data dereferencedData) { if (dereferencedData instanceof ApacheData) { // need to make a copy of the Data - ApacheData ad = (ApacheData) dereferencedData; + ApacheData ad = (ApacheData)dereferencedData; XMLSignatureInput xsi = ad.getXMLSignatureInput(); if (xsi.isNodeSet()) { try { - final Set s = xsi.getNodeSet(); + final Set s = xsi.getNodeSet(); return new NodeSetData() { public Iterator iterator() { return s.iterator(); } }; } catch (Exception e) { // log a warning - log.log(Level.WARNING, - "cannot cache dereferenced data: " + e); + log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e); return null; } } else if (xsi.isElement()) { @@ -574,12 +639,12 @@ public final class DOMReference extends DOMStructure (xsi.getSubNode(), xsi.isExcludeComments()); } else if (xsi.isOctetStream() || xsi.isByteArray()) { try { - return new OctetStreamData - (xsi.getOctetStream(), xsi.getSourceURI(), xsi.getMIMEType()); + return new OctetStreamData + (xsi.getOctetStream(), xsi.getSourceURI(), + xsi.getMIMEType()); } catch (IOException ioe) { // log a warning - log.log(Level.WARNING, - "cannot cache dereferenced data: " + ioe); + log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe); return null; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java index 8b8e5275c43..001126a6336 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMRetrievalMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMRetrievalMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -38,6 +40,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.security.Provider; import java.util.*; + import javax.xml.XMLConstants; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; @@ -50,8 +53,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; - /** * DOM-based implementation of RetrievalMethod. * @@ -61,7 +62,7 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; public final class DOMRetrievalMethod extends DOMStructure implements RetrievalMethod, DOMURIReference { - private final List transforms; + private final List transforms; private String uri; private String type; private Attr here; @@ -83,24 +84,26 @@ public final class DOMRetrievalMethod extends DOMStructure * @throws ClassCastException if transforms contains any * entries that are not of type {@link Transform} */ - public DOMRetrievalMethod(String uri, String type, List transforms) { + public DOMRetrievalMethod(String uri, String type, + List transforms) + { if (uri == null) { throw new NullPointerException("uri cannot be null"); } if (transforms == null || transforms.isEmpty()) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { - List transformsCopy = new ArrayList(transforms); - for (int i = 0, size = transformsCopy.size(); i < size; i++) { - if (!(transformsCopy.get(i) instanceof Transform)) { + this.transforms = Collections.unmodifiableList( + new ArrayList(transforms)); + for (int i = 0, size = this.transforms.size(); i < size; i++) { + if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException ("transforms["+i+"] is not a valid type"); } } - this.transforms = Collections.unmodifiableList(transformsCopy); } this.uri = uri; - if ((uri != null) && (!uri.equals(""))) { + if (!uri.equals("")) { try { new URI(uri); } catch (URISyntaxException e) { @@ -117,7 +120,9 @@ public final class DOMRetrievalMethod extends DOMStructure * @param rmElem a RetrievalMethod element */ public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // get URI and Type attributes uri = DOMUtils.getAttributeValue(rmElem, "URI"); type = DOMUtils.getAttributeValue(rmElem, "Type"); @@ -128,7 +133,7 @@ public final class DOMRetrievalMethod extends DOMStructure boolean secVal = Utils.secureValidation(context); // get Transforms, if specified - List transforms = new ArrayList(); + List transforms = new ArrayList(); Element transformsElem = DOMUtils.getFirstChildElement(rmElem); int transformCount = 0; @@ -141,19 +146,15 @@ public final class DOMRetrievalMethod extends DOMStructure transformElem = DOMUtils.getNextSiblingElement(transformElem); transformCount++; - if (secVal && - (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) - { - String error = "A maxiumum of " + - DOMReference.MAXIMUM_TRANSFORM_COUNT + - " transforms per Reference are allowed" + - " with secure validation"; + if (secVal && (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) { + String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " " + + "transforms per Reference are allowed with secure validation"; throw new MarshalException(error); } } } if (transforms.isEmpty()) { - this.transforms = Collections.EMPTY_LIST; + this.transforms = Collections.emptyList(); } else { this.transforms = Collections.unmodifiableList(transforms); } @@ -172,11 +173,11 @@ public final class DOMRetrievalMethod extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element rmElem = DOMUtils.createElement - (ownerDoc, "RetrievalMethod", XMLSignature.XMLNS, dsPrefix); + Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod", + XMLSignature.XMLNS, dsPrefix); // add URI and Type attributes DOMUtils.setAttribute(rmElem, "URI", uri); @@ -184,12 +185,14 @@ public final class DOMRetrievalMethod extends DOMStructure // add Transforms elements if (!transforms.isEmpty()) { - Element transformsElem = DOMUtils.createElement - (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix); + Element transformsElem = DOMUtils.createElement(ownerDoc, + "Transforms", + XMLSignature.XMLNS, + dsPrefix); rmElem.appendChild(transformsElem); - for (int i = 0, size = transforms.size(); i < size; i++) { - ((DOMTransform) transforms.get(i)).marshal - (transformsElem, dsPrefix, context); + for (Transform transform : transforms) { + ((DOMTransform)transform).marshal(transformsElem, + dsPrefix, context); } } @@ -204,8 +207,8 @@ public final class DOMRetrievalMethod extends DOMStructure } public Data dereference(XMLCryptoContext context) - throws URIReferenceException { - + throws URIReferenceException + { if (context == null) { throw new NullPointerException("context cannot be null"); } @@ -223,9 +226,8 @@ public final class DOMRetrievalMethod extends DOMStructure // pass dereferenced data through Transforms try { - for (int i = 0, size = transforms.size(); i < size; i++) { - Transform transform = (Transform) transforms.get(i); - data = ((DOMTransform) transform).transform(data, context); + for (Transform transform : transforms) { + data = ((DOMTransform)transform).transform(data, context); } } catch (Exception e) { throw new URIReferenceException(e); @@ -249,14 +251,13 @@ public final class DOMRetrievalMethod extends DOMStructure } public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context) - throws URIReferenceException { - + throws URIReferenceException + { try { - ApacheData data = (ApacheData) dereference(context); + ApacheData data = (ApacheData)dereference(context); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream (data.getXMLSignatureInput().getBytes())); @@ -271,6 +272,7 @@ public final class DOMRetrievalMethod extends DOMStructure } } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -278,12 +280,24 @@ public final class DOMRetrievalMethod extends DOMStructure if (!(obj instanceof RetrievalMethod)) { return false; } - RetrievalMethod orm = (RetrievalMethod) obj; + RetrievalMethod orm = (RetrievalMethod)obj; - boolean typesEqual = (type == null ? orm.getType() == null : - type.equals(orm.getType())); + boolean typesEqual = (type == null ? orm.getType() == null + : type.equals(orm.getType())); return (uri.equals(orm.getURI()) && transforms.equals(orm.getTransforms()) && typesEqual); } + + @Override + public int hashCode() { + int result = 17; + if (type != null) { + result = 31 * result + type.hashCode(); + } + result = 31 * result + uri.hashCode(); + result = 31 * result + transforms.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java index 21179dd41f1..4ce9c3cb64c 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java @@ -2,44 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; -import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; import java.io.IOException; import java.security.*; import java.security.spec.AlgorithmParameterSpec; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; +import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA; import org.jcp.xml.dsig.internal.SignerOutputStream; /** @@ -47,29 +45,30 @@ import org.jcp.xml.dsig.internal.SignerOutputStream; * * @author Sean Mullan */ -public abstract class DOMSignatureMethod extends DOMStructure - implements SignatureMethod { +public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod { - private static Logger log = - Logger.getLogger("org.jcp.xml.dsig.internal.dom"); - - // see RFC 4051 for these algorithm definitions - final static String RSA_SHA256 = - "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; - final static String RSA_SHA384 = - "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; - final static String RSA_SHA512 = - "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; - final static String HMAC_SHA256 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; - final static String HMAC_SHA384 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; - final static String HMAC_SHA512 = - "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private SignatureMethodParameterSpec params; private Signature signature; + // see RFC 4051 for these algorithm definitions + static final String RSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; + static final String RSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"; + static final String RSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; + static final String ECDSA_SHA1 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + static final String ECDSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"; + static final String ECDSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; + static final String ECDSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; + /** * Creates a DOMSignatureMethod. * @@ -78,19 +77,20 @@ public abstract class DOMSignatureMethod extends DOMStructure * appropriate for this signature method */ DOMSignatureMethod(AlgorithmParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params != null && !(params instanceof SignatureMethodParameterSpec)) { throw new InvalidAlgorithmParameterException ("params must be of type SignatureMethodParameterSpec"); } - checkParams((SignatureMethodParameterSpec) params); - this.params = (SignatureMethodParameterSpec) params; + checkParams((SignatureMethodParameterSpec)params); + this.params = (SignatureMethodParameterSpec)params; } /** * Creates a DOMSignatureMethod from an element. This ctor - * invokes the abstract {@link #unmarshalParams unmarshalParams} method to + * invokes the {@link #unmarshalParams unmarshalParams} method to * unmarshal any algorithm-specific input parameters. * * @param smElem a SignatureMethod element @@ -119,13 +119,21 @@ public abstract class DOMSignatureMethod extends DOMStructure return new SHA512withRSA(smElem); } else if (alg.equals(SignatureMethod.DSA_SHA1)) { return new SHA1withDSA(smElem); + } else if (alg.equals(ECDSA_SHA1)) { + return new SHA1withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA256)) { + return new SHA256withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA384)) { + return new SHA384withECDSA(smElem); + } else if (alg.equals(ECDSA_SHA512)) { + return new SHA512withECDSA(smElem); } else if (alg.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(smElem); - } else if (alg.equals(HMAC_SHA256)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(smElem); - } else if (alg.equals(HMAC_SHA384)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(smElem); - } else if (alg.equals(HMAC_SHA512)) { + } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(smElem); } else { throw new MarshalException @@ -133,86 +141,14 @@ public abstract class DOMSignatureMethod extends DOMStructure } } - /** - * Checks if the specified parameters are valid for this algorithm. By - * default, this method throws an exception if parameters are specified - * since most SignatureMethod algorithms do not have parameters. Subclasses - * should override it if they have parameters. - * - * @param params the algorithm-specific params (may be null) - * @throws InvalidAlgorithmParameterException if the parameters are not - * appropriate for this signature method - */ - void checkParams(SignatureMethodParameterSpec params) - throws InvalidAlgorithmParameterException { - if (params != null) { - throw new InvalidAlgorithmParameterException("no parameters " + - "should be specified for the " + getSignatureAlgorithm() - + " SignatureMethod algorithm"); - } - } - public final AlgorithmParameterSpec getParameterSpec() { return params; } - /** - * Unmarshals SignatureMethodParameterSpec from the specified - * Element. By default, this method throws an exception since - * most SignatureMethod algorithms do not have parameters. Subclasses should - * override it if they have parameters. - * - * @param paramsElem the Element holding the input params - * @return the algorithm-specific SignatureMethodParameterSpec - * @throws MarshalException if the parameters cannot be unmarshalled - */ - SignatureMethodParameterSpec - unmarshalParams(Element paramsElem) throws MarshalException { - throw new MarshalException("no parameters should " + - "be specified for the " + getSignatureAlgorithm() + - " SignatureMethod algorithm"); - } - - /** - * This method invokes the abstract {@link #marshalParams marshalParams} - * method to marshal any algorithm-specific parameters. - */ - public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { - Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element smElem = DOMUtils.createElement - (ownerDoc, "SignatureMethod", XMLSignature.XMLNS, dsPrefix); - DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm()); - - if (params != null) { - marshalParams(smElem, dsPrefix); - } - - parent.appendChild(smElem); - } - - /** - * Verifies the passed-in signature with the specified key, using the - * underlying signature or MAC algorithm. - * - * @param key the verification key - * @param si the DOMSignedInfo - * @param signature the signature bytes to be verified - * @param context the XMLValidateContext - * @return true if the signature verified successfully, - * false if not - * @throws NullPointerException if key, si or - * signature are null - * @throws InvalidKeyException if the key is improperly encoded, of - * the wrong type, or parameters are missing, etc - * @throws SignatureException if an unexpected error occurs, such - * as the passed in signature is improperly encoded - * @throws XMLSignatureException if an unexpected error occurs - */ - boolean verify(Key key, DOMSignedInfo si, byte[] sig, - XMLValidateContext context) throws InvalidKeyException, - SignatureException, XMLSignatureException { + boolean verify(Key key, SignedInfo si, byte[] sig, + XMLValidateContext context) + throws InvalidKeyException, SignatureException, XMLSignatureException + { if (key == null || si == null || sig == null) { throw new NullPointerException(); } @@ -222,49 +158,40 @@ public abstract class DOMSignatureMethod extends DOMStructure } if (signature == null) { try { - Provider p = (Provider) context.getProperty + Provider p = (Provider)context.getProperty ("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) - ? Signature.getInstance(getSignatureAlgorithm()) - : Signature.getInstance(getSignatureAlgorithm(), p); + ? Signature.getInstance(getJCAAlgorithm()) + : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } - signature.initVerify((PublicKey) key); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Signature provider:"+ signature.getProvider()); - log.log(Level.FINE, "verifying with key: " + key); + signature.initVerify((PublicKey)key); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider()); + log.log(java.util.logging.Level.FINE, "verifying with key: " + key); } - si.canonicalize(context, new SignerOutputStream(signature)); + ((DOMSignedInfo)si).canonicalize(context, + new SignerOutputStream(signature)); - if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) { - try { + try { + Type type = getAlgorithmType(); + if (type == Type.DSA) { return signature.verify(convertXMLDSIGtoASN1(sig)); - } catch (IOException ioe) { - throw new XMLSignatureException(ioe); + } else if (type == Type.ECDSA) { + return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig)); + } else { + return signature.verify(sig); } - } else { - return signature.verify(sig); + } catch (IOException ioe) { + throw new XMLSignatureException(ioe); } } - /** - * Signs the bytes with the specified key, using the underlying - * signature or MAC algorithm. - * - * @param key the signing key - * @param si the DOMSignedInfo - * @param context the XMLSignContext - * @return the signature - * @throws NullPointerException if key or - * si are null - * @throws InvalidKeyException if the key is improperly encoded, of - * the wrong type, or parameters are missing, etc - * @throws XMLSignatureException if an unexpected error occurs - */ - byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context) - throws InvalidKeyException, XMLSignatureException { + byte[] sign(Key key, SignedInfo si, XMLSignContext context) + throws InvalidKeyException, XMLSignatureException + { if (key == null || si == null) { throw new NullPointerException(); } @@ -274,26 +201,30 @@ public abstract class DOMSignatureMethod extends DOMStructure } if (signature == null) { try { - Provider p = (Provider) context.getProperty + Provider p = (Provider)context.getProperty ("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) - ? Signature.getInstance(getSignatureAlgorithm()) - : Signature.getInstance(getSignatureAlgorithm(), p); + ? Signature.getInstance(getJCAAlgorithm()) + : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } - signature.initSign((PrivateKey) key); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Signature provider:" +signature.getProvider()); - log.log(Level.FINE, "Signing with key: " + key); + signature.initSign((PrivateKey)key); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider()); + log.log(java.util.logging.Level.FINE, "Signing with key: " + key); } - si.canonicalize(context, new SignerOutputStream(signature)); + ((DOMSignedInfo)si).canonicalize(context, + new SignerOutputStream(signature)); try { - if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) { + Type type = getAlgorithmType(); + if (type == Type.DSA) { return convertASN1toXMLDSIG(signature.sign()); + } else if (type == Type.ECDSA) { + return SignatureECDSA.convertASN1toXMLDSIG(signature.sign()); } else { return signature.sign(); } @@ -304,52 +235,6 @@ public abstract class DOMSignatureMethod extends DOMStructure } } - /** - * Marshals the algorithm-specific parameters to an Element and - * appends it to the specified parent element. By default, this method - * throws an exception since most SignatureMethod algorithms do not have - * parameters. Subclasses should override it if they have parameters. - * - * @param parent the parent element to append the parameters to - * @param paramsPrefix the algorithm parameters prefix to use - * @throws MarshalException if the parameters cannot be marshalled - */ - void marshalParams(Element parent, String paramsPrefix) - throws MarshalException { - throw new MarshalException("no parameters should " + - "be specified for the " + getSignatureAlgorithm() + - " SignatureMethod algorithm"); - } - - /** - * Returns the java.security.Signature standard algorithm name. - */ - abstract String getSignatureAlgorithm(); - - /** - * Returns true if parameters are equal; false otherwise. - * - * Subclasses should override this method to compare algorithm-specific - * parameters. - */ - boolean paramsEqual(AlgorithmParameterSpec spec) { - return (getParameterSpec() == spec); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof SignatureMethod)) { - return false; - } - SignatureMethod osm = (SignatureMethod) o; - - return (getAlgorithm().equals(osm.getAlgorithm()) && - paramsEqual(osm.getParameterSpec())); - } - /** * Converts an ASN.1 DSA value to a XML Signature DSA Value. * @@ -362,8 +247,8 @@ public abstract class DOMSignatureMethod extends DOMStructure * @see 6.4.1 DSA */ private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) - throws IOException { - + throws IOException + { byte rLength = asn1Bytes[3]; int i; @@ -384,7 +269,7 @@ public abstract class DOMSignatureMethod extends DOMStructure System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i); System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes, - 40 - j, j); + 40 - j, j); return xmldsigBytes; } @@ -402,8 +287,8 @@ public abstract class DOMSignatureMethod extends DOMStructure * @see 6.4.1 DSA */ private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) - throws IOException { - + throws IOException + { if (xmldsigBytes.length != 40) { throw new IOException("Invalid XMLDSIG format of DSA signature"); } @@ -431,9 +316,9 @@ public abstract class DOMSignatureMethod extends DOMStructure byte asn1Bytes[] = new byte[6 + j + l]; asn1Bytes[0] = 48; - asn1Bytes[1] = (byte) (4 + j + l); + asn1Bytes[1] = (byte)(4 + j + l); asn1Bytes[2] = 2; - asn1Bytes[3] = (byte) j; + asn1Bytes[3] = (byte)j; System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i); @@ -456,9 +341,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return SignatureMethod.RSA_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA1withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA256withRSA extends DOMSignatureMethod { @@ -472,9 +360,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return RSA_SHA256; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA256withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA384withRSA extends DOMSignatureMethod { @@ -488,9 +379,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return RSA_SHA384; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA384withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA512withRSA extends DOMSignatureMethod { @@ -504,9 +398,12 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return RSA_SHA512; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA512withRSA"; } + Type getAlgorithmType() { + return Type.RSA; + } } static final class SHA1withDSA extends DOMSignatureMethod { @@ -520,8 +417,87 @@ public abstract class DOMSignatureMethod extends DOMStructure public String getAlgorithm() { return SignatureMethod.DSA_SHA1; } - String getSignatureAlgorithm() { + String getJCAAlgorithm() { return "SHA1withDSA"; } + Type getAlgorithmType() { + return Type.DSA; + } + } + + static final class SHA1withECDSA extends DOMSignatureMethod { + SHA1withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA1withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA1; + } + String getJCAAlgorithm() { + return "SHA1withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA256withECDSA extends DOMSignatureMethod { + SHA256withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA256withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA256; + } + String getJCAAlgorithm() { + return "SHA256withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA384withECDSA extends DOMSignatureMethod { + SHA384withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA384withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA384; + } + String getJCAAlgorithm() { + return "SHA384withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } + } + + static final class SHA512withECDSA extends DOMSignatureMethod { + SHA512withECDSA(AlgorithmParameterSpec params) + throws InvalidAlgorithmParameterException { + super(params); + } + SHA512withECDSA(Element dmElem) throws MarshalException { + super(dmElem); + } + public String getAlgorithm() { + return ECDSA_SHA512; + } + String getJCAAlgorithm() { + return "SHA512withECDSA"; + } + Type getAlgorithmType() { + return Type.ECDSA; + } } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java index 424724f1d28..ecfa41a11bc 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureProperties.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureProperties.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,6 +33,7 @@ import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -46,7 +49,7 @@ public final class DOMSignatureProperties extends DOMStructure implements SignatureProperties { private final String id; - private final List properties; + private final List properties; /** * Creates a DOMSignatureProperties from the specified @@ -61,20 +64,22 @@ public final class DOMSignatureProperties extends DOMStructure * @throws IllegalArgumentException if properties is empty * @throws NullPointerException if properties */ - public DOMSignatureProperties(List properties, String id) { + public DOMSignatureProperties(List properties, + String id) + { if (properties == null) { throw new NullPointerException("properties cannot be null"); } else if (properties.isEmpty()) { throw new IllegalArgumentException("properties cannot be empty"); } else { - List propsCopy = new ArrayList(properties); - for (int i = 0, size = propsCopy.size(); i < size; i++) { - if (!(propsCopy.get(i) instanceof SignatureProperty)) { + this.properties = Collections.unmodifiableList( + new ArrayList(properties)); + for (int i = 0, size = this.properties.size(); i < size; i++) { + if (!(this.properties.get(i) instanceof SignatureProperty)) { throw new ClassCastException ("properties["+i+"] is not a valid type"); } } - this.properties = Collections.unmodifiableList(propsCopy); } this.id = id; } @@ -85,7 +90,9 @@ public final class DOMSignatureProperties extends DOMStructure * @param propsElem a SignatureProperties element * @throws MarshalException if a marshalling error occurs */ - public DOMSignatureProperties(Element propsElem) throws MarshalException{ + public DOMSignatureProperties(Element propsElem, XMLCryptoContext context) + throws MarshalException + { // unmarshal attributes Attr attr = propsElem.getAttributeNodeNS(null, "Id"); if (attr != null) { @@ -97,11 +104,13 @@ public final class DOMSignatureProperties extends DOMStructure NodeList nodes = propsElem.getChildNodes(); int length = nodes.getLength(); - List properties = new ArrayList(length); + List properties = + new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { - properties.add(new DOMSignatureProperty((Element) child)); + properties.add(new DOMSignatureProperty((Element)child, + context)); } } if (properties.isEmpty()) { @@ -120,25 +129,27 @@ public final class DOMSignatureProperties extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element propsElem = DOMUtils.createElement - (ownerDoc, "SignatureProperties", XMLSignature.XMLNS, dsPrefix); + Element propsElem = DOMUtils.createElement(ownerDoc, + "SignatureProperties", + XMLSignature.XMLNS, + dsPrefix); // set attributes DOMUtils.setAttributeID(propsElem, "Id", id); // create and append any properties - for (int i = 0, size = properties.size(); i < size; i++) { - DOMSignatureProperty property = - (DOMSignatureProperty) properties.get(i); - property.marshal(propsElem, dsPrefix, context); + for (SignatureProperty property : properties) { + ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix, + context); } parent.appendChild(propsElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -147,11 +158,22 @@ public final class DOMSignatureProperties extends DOMStructure if (!(o instanceof SignatureProperties)) { return false; } - SignatureProperties osp = (SignatureProperties) o; + SignatureProperties osp = (SignatureProperties)o; - boolean idsEqual = (id == null ? osp.getId() == null : - id.equals(osp.getId())); + boolean idsEqual = (id == null ? osp.getId() == null + : id.equals(osp.getId())); return (properties.equals(osp.getProperties()) && idsEqual); } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + properties.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java index 9bb8838aadb..117c4657cc7 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignatureProperty.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignatureProperty.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,6 +33,7 @@ import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -47,7 +50,7 @@ public final class DOMSignatureProperty extends DOMStructure private final String id; private final String target; - private final List content; + private final List content; /** * Creates a SignatureProperty from the specified parameters. @@ -63,7 +66,9 @@ public final class DOMSignatureProperty extends DOMStructure * @throws NullPointerException if content or * target is null */ - public DOMSignatureProperty(List content, String target, String id) { + public DOMSignatureProperty(List content, + String target, String id) + { if (target == null) { throw new NullPointerException("target cannot be null"); } else if (content == null) { @@ -71,14 +76,14 @@ public final class DOMSignatureProperty extends DOMStructure } else if (content.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } else { - List contentCopy = new ArrayList(content); - for (int i = 0, size = contentCopy.size(); i < size; i++) { - if (!(contentCopy.get(i) instanceof XMLStructure)) { + this.content = Collections.unmodifiableList( + new ArrayList(content)); + for (int i = 0, size = this.content.size(); i < size; i++) { + if (!(this.content.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid type"); } } - this.content = Collections.unmodifiableList(contentCopy); } this.target = target; this.id = id; @@ -89,7 +94,9 @@ public final class DOMSignatureProperty extends DOMStructure * * @param propElem a SignatureProperty element */ - public DOMSignatureProperty(Element propElem) throws MarshalException { + public DOMSignatureProperty(Element propElem, XMLCryptoContext context) + throws MarshalException + { // unmarshal attributes target = DOMUtils.getAttributeValue(propElem, "Target"); if (target == null) { @@ -105,7 +112,7 @@ public final class DOMSignatureProperty extends DOMStructure NodeList nodes = propElem.getChildNodes(); int length = nodes.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { content.add(new javax.xml.crypto.dom.DOMStructure(nodes.item(i))); } @@ -129,26 +136,26 @@ public final class DOMSignatureProperty extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element propElem = DOMUtils.createElement - (ownerDoc, "SignatureProperty", XMLSignature.XMLNS, dsPrefix); + Element propElem = DOMUtils.createElement(ownerDoc, "SignatureProperty", + XMLSignature.XMLNS, dsPrefix); // set attributes DOMUtils.setAttributeID(propElem, "Id", id); DOMUtils.setAttribute(propElem, "Target", target); // create and append any elements and mixed content - for (int i = 0, size = content.size(); i < size; i++) { - javax.xml.crypto.dom.DOMStructure property = - (javax.xml.crypto.dom.DOMStructure) content.get(i); - DOMUtils.appendChild(propElem, property.getNode()); + for (XMLStructure property : content) { + DOMUtils.appendChild(propElem, + ((javax.xml.crypto.dom.DOMStructure)property).getNode()); } parent.appendChild(propElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -157,31 +164,43 @@ public final class DOMSignatureProperty extends DOMStructure if (!(o instanceof SignatureProperty)) { return false; } - SignatureProperty osp = (SignatureProperty) o; + SignatureProperty osp = (SignatureProperty)o; - boolean idsEqual = (id == null ? osp.getId() == null : - id.equals(osp.getId())); + boolean idsEqual = (id == null ? osp.getId() == null + : id.equals(osp.getId())); - return (equalsContent(osp.getContent()) && - target.equals(osp.getTarget()) && idsEqual); + @SuppressWarnings("unchecked") + List ospContent = osp.getContent(); + return (equalsContent(ospContent) && + target.equals(osp.getTarget()) && idsEqual); } - private boolean equalsContent(List otherContent) { + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + target.hashCode(); + result = 31 * result + content.hashCode(); + + return result; + } + + private boolean equalsContent(List otherContent) { int osize = otherContent.size(); if (content.size() != osize) { return false; } for (int i = 0; i < osize; i++) { - XMLStructure oxs = (XMLStructure) otherContent.get(i); - XMLStructure xs = (XMLStructure) content.get(i); + XMLStructure oxs = otherContent.get(i); + XMLStructure xs = content.get(i); if (oxs instanceof javax.xml.crypto.dom.DOMStructure) { if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) { return false; } - Node onode = - ((javax.xml.crypto.dom.DOMStructure) oxs).getNode(); - Node node = - ((javax.xml.crypto.dom.DOMStructure) xs).getNode(); + Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode(); + Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode(); if (!DOMUtils.nodesEqual(node, onode)) { return false; } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java index 36ebabc612d..fea139be24f 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSignedInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -33,13 +35,11 @@ import javax.xml.crypto.dsig.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; -import java.io.IOException; -import java.io.InputStreamReader; import java.io.OutputStream; +import java.io.IOException; import java.security.Provider; import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; + import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -47,7 +47,6 @@ import org.w3c.dom.Node; import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; -import com.sun.org.apache.xml.internal.security.utils.XMLUtils; /** * DOM-based implementation of SignedInfo. @@ -57,12 +56,12 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; public final class DOMSignedInfo extends DOMStructure implements SignedInfo { /** - * The maximum number of references per Manifest, if secure validation is - * enabled. + * The maximum number of references per Manifest, if secure validation is enabled. */ public static final int MAXIMUM_REFERENCE_COUNT = 30; - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); /** Signature - NOT Recommended RSAwithMD5 */ private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = @@ -72,7 +71,7 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5"; - private List references; + private List references; private CanonicalizationMethod canonicalizationMethod; private SignatureMethod signatureMethod; private String id; @@ -95,14 +94,14 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { * type Reference */ public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, - List references) { + List references) { if (cm == null || sm == null || references == null) { throw new NullPointerException(); } this.canonicalizationMethod = cm; this.signatureMethod = sm; - this.references = Collections.unmodifiableList - (new ArrayList(references)); + this.references = Collections.unmodifiableList( + new ArrayList(references)); if (this.references.isEmpty()) { throw new IllegalArgumentException("list of references must " + "contain at least one entry"); @@ -132,7 +131,7 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { * type Reference */ public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, - List references, String id) { + List references, String id) { this(cm, sm, references); this.id = id; } @@ -142,8 +141,8 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { * * @param siElem a SignedInfo element */ - public DOMSignedInfo(Element siElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + public DOMSignedInfo(Element siElem, XMLCryptoContext context, Provider provider) + throws MarshalException { localSiElem = siElem; ownerDoc = siElem.getOwnerDocument(); @@ -152,26 +151,26 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { // unmarshal CanonicalizationMethod Element cmElem = DOMUtils.getFirstChildElement(siElem); - canonicalizationMethod = new DOMCanonicalizationMethod - (cmElem, context, provider); + canonicalizationMethod = new DOMCanonicalizationMethod(cmElem, context, provider); // unmarshal SignatureMethod Element smElem = DOMUtils.getNextSiblingElement(cmElem); signatureMethod = DOMSignatureMethod.unmarshal(smElem); boolean secVal = Utils.secureValidation(context); - String sigMethAlg = signatureMethod.getAlgorithm(); - if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(sigMethAlg) - || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(sigMethAlg)))) - { - throw new MarshalException("It is forbidden to use algorithm " + - signatureMethod + - " when secure validation is enabled"); + + String signatureMethodAlgorithm = signatureMethod.getAlgorithm(); + if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(signatureMethodAlgorithm) + || ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(signatureMethodAlgorithm)))) { + throw new MarshalException( + "It is forbidden to use algorithm " + signatureMethod + " when secure validation is enabled" + ); } // unmarshal References - ArrayList refList = new ArrayList(5); + ArrayList refList = new ArrayList(5); Element refElem = DOMUtils.getNextSiblingElement(smElem); + int refCount = 0; while (refElem != null) { refList.add(new DOMReference(refElem, context, provider)); @@ -179,9 +178,8 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { refCount++; if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) { - String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + - " references per SignedInfo are allowed with" + - " secure validation"; + String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " " + + "references per Manifest are allowed with secure validation"; throw new MarshalException(error); } } @@ -208,9 +206,8 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { return canonData; } - public void canonicalize(XMLCryptoContext context,ByteArrayOutputStream bos) + public void canonicalize(XMLCryptoContext context, ByteArrayOutputStream bos) throws XMLSignatureException { - if (context == null) { throw new NullPointerException("context cannot be null"); } @@ -219,14 +216,17 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { try { os.close(); } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } // Impossible } DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true); try { - Data data = ((DOMCanonicalizationMethod) - canonicalizationMethod).canonicalize(subTree, context, os); + ((DOMCanonicalizationMethod) + canonicalizationMethod).canonicalize(subTree, context, bos); } catch (TransformException te) { throw new XMLSignatureException(te); } @@ -234,44 +234,37 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { byte[] signedInfoBytes = bos.toByteArray(); // this whole block should only be done if logging is enabled - if (log.isLoggable(Level.FINE)) { - InputStreamReader isr = new InputStreamReader - (new ByteArrayInputStream(signedInfoBytes)); - char[] siBytes = new char[signedInfoBytes.length]; - try { - isr.read(siBytes); - log.log(Level.FINE, "Canonicalized SignedInfo:\n" - + new String(siBytes)); - } catch (IOException ioex) { - log.log(Level.FINE, "IOException reading SignedInfo bytes"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); + StringBuilder sb = new StringBuilder(signedInfoBytes.length); + for (int i = 0; i < signedInfoBytes.length; i++) { + sb.append((char)signedInfoBytes[i]); } - log.log(Level.FINE, "Data to be signed/verified:" - + Base64.encode(signedInfoBytes)); + log.log(java.util.logging.Level.FINE, sb.toString()); + log.log(java.util.logging.Level.FINE, "Data to be signed/verified:" + Base64.encode(signedInfoBytes)); } this.canonData = new ByteArrayInputStream(signedInfoBytes); } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element siElem = DOMUtils.createElement - (ownerDoc, "SignedInfo", XMLSignature.XMLNS, dsPrefix); + Element siElem = DOMUtils.createElement(ownerDoc, "SignedInfo", + XMLSignature.XMLNS, dsPrefix); // create and append CanonicalizationMethod element DOMCanonicalizationMethod dcm = - (DOMCanonicalizationMethod) canonicalizationMethod; + (DOMCanonicalizationMethod)canonicalizationMethod; dcm.marshal(siElem, dsPrefix, context); // create and append SignatureMethod element - ((DOMSignatureMethod) signatureMethod).marshal - (siElem, dsPrefix, context); + ((DOMStructure)signatureMethod).marshal(siElem, dsPrefix, context); // create and append Reference elements - for (int i = 0, size = references.size(); i < size; i++) { - DOMReference reference = (DOMReference) references.get(i); - reference.marshal(siElem, dsPrefix, context); + for (Reference reference : references) { + ((DOMReference)reference).marshal(siElem, dsPrefix, context); } // append Id attribute @@ -281,6 +274,7 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { localSiElem = siElem; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -289,13 +283,26 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo { if (!(o instanceof SignedInfo)) { return false; } - SignedInfo osi = (SignedInfo) o; + SignedInfo osi = (SignedInfo)o; - boolean idEqual = (id == null ? osi.getId() == null : - id.equals(osi.getId())); + boolean idEqual = (id == null ? osi.getId() == null + : id.equals(osi.getId())); return (canonicalizationMethod.equals(osi.getCanonicalizationMethod()) - && signatureMethod.equals(osi.getSignatureMethod()) && - references.equals(osi.getReferences()) && idEqual); + && signatureMethod.equals(osi.getSignatureMethod()) && + references.equals(osi.getReferences()) && idEqual); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + result = 31 * result + canonicalizationMethod.hashCode(); + result = 31 * result + signatureMethod.hashCode(); + result = 31 * result + references.hashCode(); + + return result; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java index f3cb1d93d9f..02ea86f37e6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMStructure.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMStructure.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java index c80992b661f..ca33a18e726 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2006 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMSubTreeData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id$ */ package org.jcp.xml.dsig.internal.dom; @@ -45,17 +47,15 @@ import org.w3c.dom.Node; public class DOMSubTreeData implements NodeSetData { private boolean excludeComments; - private Iterator ni; private Node root; public DOMSubTreeData(Node root, boolean excludeComments) { this.root = root; - this.ni = new DelayedNodeIterator(root, excludeComments); this.excludeComments = excludeComments; } public Iterator iterator() { - return ni; + return new DelayedNodeIterator(root, excludeComments); } public Node getRoot() { @@ -70,10 +70,10 @@ public class DOMSubTreeData implements NodeSetData { * This is an Iterator that contains a backing node-set that is * not populated until the caller first attempts to advance the iterator. */ - static class DelayedNodeIterator implements Iterator { + static class DelayedNodeIterator implements Iterator { private Node root; - private List nodeSet; - private ListIterator li; + private List nodeSet; + private ListIterator li; private boolean withComments; DelayedNodeIterator(Node root, boolean excludeComments) { @@ -89,13 +89,13 @@ public class DOMSubTreeData implements NodeSetData { return li.hasNext(); } - public Object next() { + public Node next() { if (nodeSet == null) { nodeSet = dereferenceSameDocumentURI(root); li = nodeSet.listIterator(); } if (li.hasNext()) { - return (Node) li.next(); + return li.next(); } else { throw new NoSuchElementException(); } @@ -109,11 +109,11 @@ public class DOMSubTreeData implements NodeSetData { * Dereferences a same-document URI fragment. * * @param node the node (document or element) referenced by the - * URI fragment. If null, returns an empty set. + * URI fragment. If null, returns an empty set. * @return a set of nodes (minus any comment nodes) */ - private List dereferenceSameDocumentURI(Node node) { - List nodeSet = new ArrayList(); + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); if (node != null) { nodeSetMinusCommentNodes(node, nodeSet, null); } @@ -129,8 +129,10 @@ public class DOMSubTreeData implements NodeSetData { * @param nodeSet the set of nodes traversed so far * @param the previous sibling node */ - private void nodeSetMinusCommentNodes(Node node, List nodeSet, - Node prevSibling) { + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { switch (node.getNodeType()) { case Node.ELEMENT_NODE : NamedNodeMap attrs = node.getAttributes(); @@ -140,7 +142,6 @@ public class DOMSubTreeData implements NodeSetData { } } nodeSet.add(node); - case Node.DOCUMENT_NODE : Node pSibling = null; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { @@ -148,14 +149,25 @@ public class DOMSubTreeData implements NodeSetData { pSibling = child; } break; + case Node.DOCUMENT_NODE : + pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; case Node.TEXT_NODE : case Node.CDATA_SECTION_NODE: // emulate XPath which only returns the first node in // contiguous text/cdata nodes if (prevSibling != null && (prevSibling.getNodeType() == Node.TEXT_NODE || - prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)){ return; + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; } + nodeSet.add(node); + break; case Node.PROCESSING_INSTRUCTION_NODE : nodeSet.add(node); break; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java index a9398e592c1..d7a40e0e2c6 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMTransform.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -35,13 +37,11 @@ import java.security.spec.AlgorithmParameterSpec; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import org.w3c.dom.NodeList; import javax.xml.crypto.*; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.dom.DOMSignContext; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; /** * DOM-based abstract implementation of Transform. @@ -69,15 +69,26 @@ public class DOMTransform extends DOMStructure implements Transform { * @param transElem a Transform element */ public DOMTransform(Element transElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm"); - try { - spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException e1) { + + if (provider == null) { + try { + spi = TransformService.getInstance(algorithm, "DOM"); + } catch (NoSuchAlgorithmException e1) { + throw new MarshalException(e1); + } + } else { try { spi = TransformService.getInstance(algorithm, "DOM", provider); - } catch (NoSuchAlgorithmException e2) { - throw new MarshalException(e2); + } catch (NoSuchAlgorithmException nsae) { + try { + spi = TransformService.getInstance(algorithm, "DOM"); + } catch (NoSuchAlgorithmException e2) { + throw new MarshalException(e2); + } } } try { @@ -100,21 +111,25 @@ public class DOMTransform extends DOMStructure implements Transform { * method to marshal any algorithm-specific parameters. */ public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); Element transformElem = null; if (parent.getLocalName().equals("Transforms")) { - transformElem = DOMUtils.createElement - (ownerDoc, "Transform", XMLSignature.XMLNS, dsPrefix); + transformElem = DOMUtils.createElement(ownerDoc, "Transform", + XMLSignature.XMLNS, + dsPrefix); } else { - transformElem = DOMUtils.createElement - (ownerDoc, "CanonicalizationMethod", XMLSignature.XMLNS, dsPrefix); + transformElem = DOMUtils.createElement(ownerDoc, + "CanonicalizationMethod", + XMLSignature.XMLNS, + dsPrefix); } DOMUtils.setAttribute(transformElem, "Algorithm", getAlgorithm()); - spi.marshalParams - (new javax.xml.crypto.dom.DOMStructure(transformElem), context); + spi.marshalParams(new javax.xml.crypto.dom.DOMStructure(transformElem), + context); parent.appendChild(transformElem); } @@ -131,7 +146,8 @@ public class DOMTransform extends DOMStructure implements Transform { * executing the transform */ public Data transform(Data data, XMLCryptoContext xc) - throws TransformException { + throws TransformException + { return spi.transform(data, xc); } @@ -149,10 +165,12 @@ public class DOMTransform extends DOMStructure implements Transform { * executing the transform */ public Data transform(Data data, XMLCryptoContext xc, OutputStream os) - throws TransformException { + throws TransformException + { return spi.transform(data, xc, os); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -161,11 +179,23 @@ public class DOMTransform extends DOMStructure implements Transform { if (!(o instanceof Transform)) { return false; } - Transform otransform = (Transform) o; + Transform otransform = (Transform)o; return (getAlgorithm().equals(otransform.getAlgorithm()) && - DOMUtils.paramsEqual - (getParameterSpec(), otransform.getParameterSpec())); + DOMUtils.paramsEqual(getParameterSpec(), + otransform.getParameterSpec())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + getAlgorithm().hashCode(); + AlgorithmParameterSpec spec = getParameterSpec(); + if (spec != null) { + result = 31 * result + spec.hashCode(); + } + + return result; } /** @@ -185,9 +215,10 @@ public class DOMTransform extends DOMStructure implements Transform { * executing the transform */ Data transform(Data data, XMLCryptoContext xc, DOMSignContext context) - throws MarshalException, TransformException { + throws MarshalException, TransformException + { marshal(context.getParent(), - DOMUtils.getSignaturePrefix(context), context); + DOMUtils.getSignaturePrefix(context), context); return transform(data, xc); } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java index cca0c9e2e03..33e0a90224f 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMURIDereferencer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -37,7 +39,6 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import javax.xml.crypto.*; import javax.xml.crypto.dom.*; -import javax.xml.crypto.dsig.*; /** * DOM-based implementation of URIDereferencer. @@ -82,21 +83,17 @@ public class DOMURIDereferencer implements URIDereferencer { id = id.substring(i1+1, i2); } - Node refElem = dcc.getElementById(id); - if (refElem != null) { + Node referencedElem = dcc.getElementById(id); + if (referencedElem != null) { if (secVal) { - Element start = - refElem.getOwnerDocument().getDocumentElement(); - if (!XMLUtils.protectAgainstWrappingAttack(start, - (Element)refElem, - id)) { - String error = "Multiple Elements with the same ID " + - id + " were detected"; + Element start = referencedElem.getOwnerDocument().getDocumentElement(); + if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) { + String error = "Multiple Elements with the same ID " + id + " were detected"; throw new URIReferenceException(error); } } - XMLSignatureInput result = new XMLSignatureInput(refElem); + XMLSignatureInput result = new XMLSignatureInput(referencedElem); if (!uri.substring(1).startsWith("xpointer(id(")) { result.setExcludeComments(true); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java index 184a6d34426..c55a13ae323 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMUtils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMUtils.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -34,7 +36,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.*; @@ -56,7 +57,7 @@ public class DOMUtils { */ public static Document getOwnerDocument(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; + return (Document)node; } else { return node.getOwnerDocument(); } @@ -72,8 +73,9 @@ public class DOMUtils { * @param prefix the namespace prefix * @return the newly created element */ - public static Element createElement(Document doc, String tag, String nsURI, - String prefix) { + public static Element createElement(Document doc, String tag, + String nsURI, String prefix) + { String qName = (prefix == null || prefix.length() == 0) ? tag : prefix + ":" + tag; return doc.createElementNS(nsURI, qName); @@ -88,7 +90,9 @@ public class DOMUtils { * @param value the attribute value. If null, no attribute is set. */ public static void setAttribute(Element elem, String name, String value) { - if (value == null) return; + if (value == null) { + return; + } elem.setAttributeNS(null, name, value); } @@ -103,7 +107,9 @@ public class DOMUtils { * @param value the attribute value. If null, no attribute is set. */ public static void setAttributeID(Element elem, String name, String value) { - if (value == null) return; + if (value == null) { + return; + } elem.setAttributeNS(null, name, value); elem.setIdAttributeNS(null, name, true); } @@ -122,7 +128,7 @@ public class DOMUtils { while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { child = child.getNextSibling(); } - return (Element) child; + return (Element)child; } /** @@ -139,7 +145,7 @@ public class DOMUtils { while (child != null && child.getNodeType() != Node.ELEMENT_NODE) { child = child.getPreviousSibling(); } - return (Element) child; + return (Element)child; } /** @@ -156,7 +162,7 @@ public class DOMUtils { while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) { sibling = sibling.getNextSibling(); } - return (Element) sibling; + return (Element)sibling; } /** @@ -185,25 +191,25 @@ public class DOMUtils { * @param nl the NodeList * @return a Set of Nodes */ - public static Set nodeSet(NodeList nl) { + public static Set nodeSet(NodeList nl) { return new NodeSet(nl); } - static class NodeSet extends AbstractSet { + static class NodeSet extends AbstractSet { private NodeList nl; public NodeSet(NodeList nl) { this.nl = nl; } public int size() { return nl.getLength(); } - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { int index = 0; public void remove() { throw new UnsupportedOperationException(); } - public Object next() { + public Node next() { if (!hasNext()) { throw new NoSuchElementException(); } @@ -291,39 +297,41 @@ public class DOMUtils { } if (spec1 instanceof XPathFilter2ParameterSpec && spec2 instanceof XPathFilter2ParameterSpec) { - return paramsEqual((XPathFilter2ParameterSpec) spec1, - (XPathFilter2ParameterSpec) spec2); + return paramsEqual((XPathFilter2ParameterSpec)spec1, + (XPathFilter2ParameterSpec)spec2); } if (spec1 instanceof ExcC14NParameterSpec && spec2 instanceof ExcC14NParameterSpec) { return paramsEqual((ExcC14NParameterSpec) spec1, - (ExcC14NParameterSpec) spec2); + (ExcC14NParameterSpec)spec2); } if (spec1 instanceof XPathFilterParameterSpec && spec2 instanceof XPathFilterParameterSpec) { - return paramsEqual((XPathFilterParameterSpec) spec1, - (XPathFilterParameterSpec) spec2); + return paramsEqual((XPathFilterParameterSpec)spec1, + (XPathFilterParameterSpec)spec2); } if (spec1 instanceof XSLTTransformParameterSpec && spec2 instanceof XSLTTransformParameterSpec) { - return paramsEqual((XSLTTransformParameterSpec) spec1, - (XSLTTransformParameterSpec) spec2); + return paramsEqual((XSLTTransformParameterSpec)spec1, + (XSLTTransformParameterSpec)spec2); } return false; } private static boolean paramsEqual(XPathFilter2ParameterSpec spec1, - XPathFilter2ParameterSpec spec2) { - - List types = spec1.getXPathList(); - List otypes = spec2.getXPathList(); + XPathFilter2ParameterSpec spec2) + { + @SuppressWarnings("unchecked") + List types = spec1.getXPathList(); + @SuppressWarnings("unchecked") + List otypes = spec2.getXPathList(); int size = types.size(); if (size != otypes.size()) { return false; } for (int i = 0; i < size; i++) { - XPathType type = (XPathType) types.get(i); - XPathType otype = (XPathType) otypes.get(i); + XPathType type = types.get(i); + XPathType otype = otypes.get(i); if (!type.getExpression().equals(otype.getExpression()) || !type.getNamespaceMap().equals(otype.getNamespaceMap()) || type.getFilter() != otype.getFilter()) { @@ -334,18 +342,21 @@ public class DOMUtils { } private static boolean paramsEqual(ExcC14NParameterSpec spec1, - ExcC14NParameterSpec spec2) { + ExcC14NParameterSpec spec2) + { return spec1.getPrefixList().equals(spec2.getPrefixList()); } private static boolean paramsEqual(XPathFilterParameterSpec spec1, - XPathFilterParameterSpec spec2) { + XPathFilterParameterSpec spec2) + { return (spec1.getXPath().equals(spec2.getXPath()) && - spec1.getNamespaceMap().equals(spec2.getNamespaceMap())); + spec1.getNamespaceMap().equals(spec2.getNamespaceMap())); } private static boolean paramsEqual(XSLTTransformParameterSpec spec1, - XSLTTransformParameterSpec spec2) { + XSLTTransformParameterSpec spec2) + { XMLStructure ostylesheet = spec2.getStylesheet(); if (!(ostylesheet instanceof javax.xml.crypto.dom.DOMStructure)) { diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java index d9a50864f04..11076a7ccfc 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMX509Data.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -51,7 +53,7 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; //@@@ check for illegal combinations of data violating MUSTs in W3c spec public final class DOMX509Data extends DOMStructure implements X509Data { - private final List content; + private final List content; private CertificateFactory cf; /** @@ -69,18 +71,18 @@ public final class DOMX509Data extends DOMStructure implements X509Data { * @throws ClassCastException if content contains any entries * that are not of one of the valid types mentioned above */ - public DOMX509Data(List content) { + public DOMX509Data(List content) { if (content == null) { throw new NullPointerException("content cannot be null"); } - List contentCopy = new ArrayList(content); + List contentCopy = new ArrayList(content); if (contentCopy.isEmpty()) { throw new IllegalArgumentException("content cannot be empty"); } for (int i = 0, size = contentCopy.size(); i < size; i++) { Object x509Type = contentCopy.get(i); if (x509Type instanceof String) { - new X500Principal((String) x509Type); + new X500Principal((String)x509Type); } else if (!(x509Type instanceof byte[]) && !(x509Type instanceof X509Certificate) && !(x509Type instanceof X509CRL) && @@ -102,7 +104,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { // get all children nodes NodeList nl = xdElem.getChildNodes(); int length = nl.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nl.item(i); // ignore all non-Element nodes @@ -110,7 +112,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { continue; } - Element childElem = (Element) child; + Element childElem = (Element)child; String localName = childElem.getLocalName(); if (localName.equals("X509Certificate")) { content.add(unmarshalX509Certificate(childElem)); @@ -138,32 +140,32 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - - Element xdElem = DOMUtils.createElement - (ownerDoc, "X509Data", XMLSignature.XMLNS, dsPrefix); + Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data", + XMLSignature.XMLNS, dsPrefix); // append children and preserve order for (int i = 0, size = content.size(); i < size; i++) { Object object = content.get(i); if (object instanceof X509Certificate) { - marshalCert((X509Certificate) object,xdElem,ownerDoc,dsPrefix); + marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix); } else if (object instanceof XMLStructure) { if (object instanceof X509IssuerSerial) { - ((DOMX509IssuerSerial) object).marshal + ((DOMX509IssuerSerial)object).marshal (xdElem, dsPrefix, context); } else { javax.xml.crypto.dom.DOMStructure domContent = - (javax.xml.crypto.dom.DOMStructure) object; + (javax.xml.crypto.dom.DOMStructure)object; DOMUtils.appendChild(xdElem, domContent.getNode()); } } else if (object instanceof byte[]) { - marshalSKI((byte[]) object, xdElem, ownerDoc, dsPrefix); + marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix); } else if (object instanceof String) { - marshalSubjectName((String) object, xdElem, ownerDoc,dsPrefix); + marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix); } else if (object instanceof X509CRL) { - marshalCRL((X509CRL) object, xdElem, ownerDoc, dsPrefix); + marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix); } } @@ -171,31 +173,32 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } private void marshalSKI(byte[] skid, Node parent, Document doc, - String dsPrefix) { - - Element skidElem = DOMUtils.createElement - (doc, "X509SKI", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + { + Element skidElem = DOMUtils.createElement(doc, "X509SKI", + XMLSignature.XMLNS, dsPrefix); skidElem.appendChild(doc.createTextNode(Base64.encode(skid))); parent.appendChild(skidElem); } private void marshalSubjectName(String name, Node parent, Document doc, - String dsPrefix) { - - Element snElem = DOMUtils.createElement - (doc, "X509SubjectName", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + { + Element snElem = DOMUtils.createElement(doc, "X509SubjectName", + XMLSignature.XMLNS, dsPrefix); snElem.appendChild(doc.createTextNode(name)); parent.appendChild(snElem); } private void marshalCert(X509Certificate cert, Node parent, Document doc, - String dsPrefix) throws MarshalException { - - Element certElem = DOMUtils.createElement - (doc, "X509Certificate", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + throws MarshalException + { + Element certElem = DOMUtils.createElement(doc, "X509Certificate", + XMLSignature.XMLNS, dsPrefix); try { certElem.appendChild(doc.createTextNode - (Base64.encode(cert.getEncoded()))); + (Base64.encode(cert.getEncoded()))); } catch (CertificateEncodingException e) { throw new MarshalException("Error encoding X509Certificate", e); } @@ -203,13 +206,14 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } private void marshalCRL(X509CRL crl, Node parent, Document doc, - String dsPrefix) throws MarshalException { - - Element crlElem = DOMUtils.createElement - (doc, "X509CRL", XMLSignature.XMLNS, dsPrefix); + String dsPrefix) + throws MarshalException + { + Element crlElem = DOMUtils.createElement(doc, "X509CRL", + XMLSignature.XMLNS, dsPrefix); try { crlElem.appendChild(doc.createTextNode - (Base64.encode(crl.getEncoded()))); + (Base64.encode(crl.getEncoded()))); } catch (CRLException e) { throw new MarshalException("Error encoding X509CRL", e); } @@ -217,10 +221,11 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } private X509Certificate unmarshalX509Certificate(Element elem) - throws MarshalException { + throws MarshalException + { try { ByteArrayInputStream bs = unmarshalBase64Binary(elem); - return (X509Certificate) cf.generateCertificate(bs); + return (X509Certificate)cf.generateCertificate(bs); } catch (CertificateException e) { throw new MarshalException("Cannot create X509Certificate", e); } @@ -229,7 +234,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { private X509CRL unmarshalX509CRL(Element elem) throws MarshalException { try { ByteArrayInputStream bs = unmarshalBase64Binary(elem); - return (X509CRL) cf.generateCRL(bs); + return (X509CRL)cf.generateCRL(bs); } catch (CRLException e) { throw new MarshalException("Cannot create X509CRL", e); } @@ -249,6 +254,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { } } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -257,9 +263,9 @@ public final class DOMX509Data extends DOMStructure implements X509Data { if (!(o instanceof X509Data)) { return false; } - X509Data oxd = (X509Data) o; + X509Data oxd = (X509Data)o; - List ocontent = oxd.getContent(); + @SuppressWarnings("unchecked") List ocontent = oxd.getContent(); int size = content.size(); if (size != ocontent.size()) { return false; @@ -270,7 +276,7 @@ public final class DOMX509Data extends DOMStructure implements X509Data { Object ox = ocontent.get(i); if (x instanceof byte[]) { if (!(ox instanceof byte[]) || - !Arrays.equals((byte[]) x, (byte[]) ox)) { + !Arrays.equals((byte[])x, (byte[])ox)) { return false; } } else { @@ -282,4 +288,12 @@ public final class DOMX509Data extends DOMStructure implements X509Data { return true; } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + content.hashCode(); + + return result; + } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java index f3cad8333a0..318d9cfe886 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMX509IssuerSerial.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMX509IssuerSerial.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -94,15 +96,16 @@ public final class DOMX509IssuerSerial extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element isElem = DOMUtils.createElement - (ownerDoc, "X509IssuerSerial", XMLSignature.XMLNS, dsPrefix); - Element inElem = DOMUtils.createElement - (ownerDoc, "X509IssuerName", XMLSignature.XMLNS, dsPrefix); - Element snElem = DOMUtils.createElement - (ownerDoc, "X509SerialNumber", XMLSignature.XMLNS, dsPrefix); + Element isElem = DOMUtils.createElement(ownerDoc, "X509IssuerSerial", + XMLSignature.XMLNS, dsPrefix); + Element inElem = DOMUtils.createElement(ownerDoc, "X509IssuerName", + XMLSignature.XMLNS, dsPrefix); + Element snElem = DOMUtils.createElement(ownerDoc, "X509SerialNumber", + XMLSignature.XMLNS, dsPrefix); inElem.appendChild(ownerDoc.createTextNode(issuerName)); snElem.appendChild(ownerDoc.createTextNode(serialNumber.toString())); isElem.appendChild(inElem); @@ -110,6 +113,7 @@ public final class DOMX509IssuerSerial extends DOMStructure parent.appendChild(isElem); } + @Override public boolean equals(Object obj) { if (this == obj) { return true; @@ -117,8 +121,17 @@ public final class DOMX509IssuerSerial extends DOMStructure if (!(obj instanceof X509IssuerSerial)) { return false; } - X509IssuerSerial ois = (X509IssuerSerial) obj; + X509IssuerSerial ois = (X509IssuerSerial)obj; return (issuerName.equals(ois.getIssuerName()) && - serialNumber.equals(ois.getSerialNumber())); + serialNumber.equals(ois.getSerialNumber())); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + issuerName.hashCode(); + result = 31 * result + serialNumber.hashCode(); + + return result; } } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java index a5416f5d770..01c7bcc1628 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXMLObject.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLObject.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -32,6 +34,7 @@ import javax.xml.crypto.dsig.*; import java.security.Provider; import java.util.*; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -48,7 +51,8 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { private final String id; private final String mimeType; private final String encoding; - private final List content; + private final List content; + private Element objectElem; /** * Creates an XMLObject from the specified parameters. @@ -63,19 +67,20 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { * @throws ClassCastException if content contains any * entries that are not of type {@link XMLStructure} */ - public DOMXMLObject(List content, String id, String mimeType, - String encoding) { + public DOMXMLObject(List content, String id, + String mimeType, String encoding) + { if (content == null || content.isEmpty()) { - this.content = Collections.EMPTY_LIST; + this.content = Collections.emptyList(); } else { - List contentCopy = new ArrayList(content); - for (int i = 0, size = contentCopy.size(); i < size; i++) { - if (!(contentCopy.get(i) instanceof XMLStructure)) { + this.content = Collections.unmodifiableList( + new ArrayList(content)); + for (int i = 0, size = this.content.size(); i < size; i++) { + if (!(this.content.get(i) instanceof XMLStructure)) { throw new ClassCastException ("content["+i+"] is not a valid type"); } } - this.content = Collections.unmodifiableList(contentCopy); } this.id = id; this.mimeType = mimeType; @@ -89,7 +94,9 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { * @throws MarshalException if there is an error when unmarshalling */ public DOMXMLObject(Element objElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { // unmarshal attributes this.encoding = DOMUtils.getAttributeValue(objElem, "Encoding"); @@ -104,17 +111,17 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { NodeList nodes = objElem.getChildNodes(); int length = nodes.getLength(); - List content = new ArrayList(length); + List content = new ArrayList(length); for (int i = 0; i < length; i++) { Node child = nodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element) child; + Element childElem = (Element)child; String tag = childElem.getLocalName(); if (tag.equals("Manifest")) { content.add(new DOMManifest(childElem, context, provider)); continue; } else if (tag.equals("SignatureProperties")) { - content.add(new DOMSignatureProperties(childElem)); + content.add(new DOMSignatureProperties(childElem, context)); continue; } else if (tag.equals("X509Data")) { content.add(new DOMX509Data(childElem)); @@ -125,10 +132,11 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { content.add(new javax.xml.crypto.dom.DOMStructure(child)); } if (content.isEmpty()) { - this.content = Collections.EMPTY_LIST; + this.content = Collections.emptyList(); } else { this.content = Collections.unmodifiableList(content); } + this.objectElem = objElem; } public List getContent() { @@ -151,29 +159,32 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { throws MarshalException { Document ownerDoc = DOMUtils.getOwnerDocument(parent); - Element objElem = DOMUtils.createElement - (ownerDoc, "Object", XMLSignature.XMLNS, dsPrefix); + Element objElem = objectElem != null ? objectElem : null; + if (objElem == null) { + objElem = DOMUtils.createElement(ownerDoc, "Object", + XMLSignature.XMLNS, dsPrefix); - // set attributes - DOMUtils.setAttributeID(objElem, "Id", id); - DOMUtils.setAttribute(objElem, "MimeType", mimeType); - DOMUtils.setAttribute(objElem, "Encoding", encoding); + // set attributes + DOMUtils.setAttributeID(objElem, "Id", id); + DOMUtils.setAttribute(objElem, "MimeType", mimeType); + DOMUtils.setAttribute(objElem, "Encoding", encoding); - // create and append any elements and mixed content, if necessary - for (int i = 0, size = content.size(); i < size; i++) { - XMLStructure object = (XMLStructure) content.get(i); - if (object instanceof DOMStructure) { - ((DOMStructure) object).marshal(objElem, dsPrefix, context); - } else { - javax.xml.crypto.dom.DOMStructure domObject = - (javax.xml.crypto.dom.DOMStructure) object; - DOMUtils.appendChild(objElem, domObject.getNode()); + // create and append any elements and mixed content, if necessary + for (XMLStructure object : content) { + if (object instanceof DOMStructure) { + ((DOMStructure)object).marshal(objElem, dsPrefix, context); + } else { + javax.xml.crypto.dom.DOMStructure domObject = + (javax.xml.crypto.dom.DOMStructure)object; + DOMUtils.appendChild(objElem, domObject.getNode()); + } } } parent.appendChild(objElem); } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -182,34 +193,53 @@ public final class DOMXMLObject extends DOMStructure implements XMLObject { if (!(o instanceof XMLObject)) { return false; } - XMLObject oxo = (XMLObject) o; + XMLObject oxo = (XMLObject)o; - boolean idsEqual = (id == null ? oxo.getId() == null : - id.equals(oxo.getId())); - boolean encodingsEqual = (encoding == null ? oxo.getEncoding() == null : - encoding.equals(oxo.getEncoding())); - boolean mimeTypesEqual = (mimeType == null ? oxo.getMimeType() == null : - mimeType.equals(oxo.getMimeType())); + boolean idsEqual = (id == null ? oxo.getId() == null + : id.equals(oxo.getId())); + boolean encodingsEqual = + (encoding == null ? oxo.getEncoding() == null + : encoding.equals(oxo.getEncoding())); + boolean mimeTypesEqual = + (mimeType == null ? oxo.getMimeType() == null + : mimeType.equals(oxo.getMimeType())); + @SuppressWarnings("unchecked") + List oxoContent = oxo.getContent(); return (idsEqual && encodingsEqual && mimeTypesEqual && - equalsContent(oxo.getContent())); + equalsContent(oxoContent)); } - private boolean equalsContent(List otherContent) { + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (encoding != null) { + result = 31 * result + encoding.hashCode(); + } + if (mimeType != null) { + result = 31 * result + mimeType.hashCode(); + } + result = 31 * result + content.hashCode(); + + return result; + } + + private boolean equalsContent(List otherContent) { if (content.size() != otherContent.size()) { return false; } for (int i = 0, osize = otherContent.size(); i < osize; i++) { - XMLStructure oxs = (XMLStructure) otherContent.get(i); - XMLStructure xs = (XMLStructure) content.get(i); + XMLStructure oxs = otherContent.get(i); + XMLStructure xs = content.get(i); if (oxs instanceof javax.xml.crypto.dom.DOMStructure) { if (!(xs instanceof javax.xml.crypto.dom.DOMStructure)) { return false; } - Node onode = - ((javax.xml.crypto.dom.DOMStructure) oxs).getNode(); - Node node = - ((javax.xml.crypto.dom.DOMStructure) xs).getNode(); + Node onode = ((javax.xml.crypto.dom.DOMStructure)oxs).getNode(); + Node node = ((javax.xml.crypto.dom.DOMStructure)xs).getNode(); if (!DOMUtils.nodesEqual(node, onode)) { return false; } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java index 6c91e369f42..ebd41baae2a 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. @@ -29,7 +31,7 @@ * =========================================================================== */ /* - * $Id: DOMXMLSignature.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLSignature.java 1333415 2012-05-03 12:03:51Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -40,7 +42,6 @@ import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.KeyInfo; -import java.io.*; import java.security.InvalidKeyException; import java.security.Key; import java.security.Provider; @@ -48,8 +49,7 @@ import java.util.Collections; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -67,11 +67,12 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; public final class DOMXMLSignature extends DOMStructure implements XMLSignature { - private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom"); + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom"); private String id; private SignatureValue sv; private KeyInfo ki; - private List objects; + private List objects; private SignedInfo si; private Document ownerDoc = null; private Element localSigElem = null; @@ -79,7 +80,7 @@ public final class DOMXMLSignature extends DOMStructure private boolean validationStatus; private boolean validated = false; private KeySelectorResult ksr; - private HashMap signatureIdMap; + private HashMap signatureIdMap; static { com.sun.org.apache.xml.internal.security.Init.init(); @@ -98,8 +99,9 @@ public final class DOMXMLSignature extends DOMStructure * omit) * @throws NullPointerException if si is null */ - public DOMXMLSignature(SignedInfo si, KeyInfo ki, List objs, String id, - String signatureValueId) + public DOMXMLSignature(SignedInfo si, KeyInfo ki, + List objs, + String id, String signatureValueId) { if (si == null) { throw new NullPointerException("signedInfo cannot be null"); @@ -108,16 +110,16 @@ public final class DOMXMLSignature extends DOMStructure this.id = id; this.sv = new DOMSignatureValue(signatureValueId); if (objs == null) { - this.objects = Collections.EMPTY_LIST; + this.objects = Collections.emptyList(); } else { - List objsCopy = new ArrayList(objs); - for (int i = 0, size = objsCopy.size(); i < size; i++) { - if (!(objsCopy.get(i) instanceof XMLObject)) { + this.objects = + Collections.unmodifiableList(new ArrayList(objs)); + for (int i = 0, size = this.objects.size(); i < size; i++) { + if (!(this.objects.get(i) instanceof XMLObject)) { throw new ClassCastException ("objs["+i+"] is not an XMLObject"); } } - this.objects = Collections.unmodifiableList(objsCopy); } this.ki = ki; } @@ -129,7 +131,9 @@ public final class DOMXMLSignature extends DOMStructure * @throws MarshalException if XMLSignature cannot be unmarshalled */ public DOMXMLSignature(Element sigElem, XMLCryptoContext context, - Provider provider) throws MarshalException { + Provider provider) + throws MarshalException + { localSigElem = sigElem; ownerDoc = localSigElem.getOwnerDocument(); @@ -142,7 +146,7 @@ public final class DOMXMLSignature extends DOMStructure // unmarshal SignatureValue Element sigValElem = DOMUtils.getNextSiblingElement(siElem); - sv = new DOMSignatureValue(sigValElem); + sv = new DOMSignatureValue(sigValElem, context); // unmarshal KeyInfo, if specified Element nextSibling = DOMUtils.getNextSiblingElement(sigValElem); @@ -153,12 +157,12 @@ public final class DOMXMLSignature extends DOMStructure // unmarshal Objects, if specified if (nextSibling == null) { - objects = Collections.EMPTY_LIST; + objects = Collections.emptyList(); } else { - List tempObjects = new ArrayList(); + List tempObjects = new ArrayList(); while (nextSibling != null) { - tempObjects.add - (new DOMXMLObject(nextSibling, context, provider)); + tempObjects.add(new DOMXMLObject(nextSibling, + context, provider)); nextSibling = DOMUtils.getNextSiblingElement(nextSibling); } objects = Collections.unmodifiableList(tempObjects); @@ -190,41 +194,42 @@ public final class DOMXMLSignature extends DOMStructure } public void marshal(Node parent, String dsPrefix, DOMCryptoContext context) - throws MarshalException { + throws MarshalException + { marshal(parent, null, dsPrefix, context); } public void marshal(Node parent, Node nextSibling, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + DOMCryptoContext context) + throws MarshalException + { ownerDoc = DOMUtils.getOwnerDocument(parent); - - sigElem = DOMUtils.createElement - (ownerDoc, "Signature", XMLSignature.XMLNS, dsPrefix); + sigElem = DOMUtils.createElement(ownerDoc, "Signature", + XMLSignature.XMLNS, dsPrefix); // append xmlns attribute if (dsPrefix == null || dsPrefix.length() == 0) { - sigElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); + sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", + XMLSignature.XMLNS); } else { - sigElem.setAttributeNS - ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, - XMLSignature.XMLNS); + sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + dsPrefix, XMLSignature.XMLNS); } // create and append SignedInfo element - ((DOMSignedInfo) si).marshal(sigElem, dsPrefix, context); + ((DOMSignedInfo)si).marshal(sigElem, dsPrefix, context); // create and append SignatureValue element - ((DOMSignatureValue) sv).marshal(sigElem, dsPrefix, context); + ((DOMSignatureValue)sv).marshal(sigElem, dsPrefix, context); // create and append KeyInfo element if necessary if (ki != null) { - ((DOMKeyInfo) ki).marshal(sigElem, null, dsPrefix, context); + ((DOMKeyInfo)ki).marshal(sigElem, null, dsPrefix, context); } // create and append Object elements if necessary for (int i = 0, size = objects.size(); i < size; i++) { - ((DOMXMLObject) objects.get(i)).marshal(sigElem, dsPrefix, context); + ((DOMXMLObject)objects.get(i)).marshal(sigElem, dsPrefix, context); } // append Id attribute @@ -234,8 +239,8 @@ public final class DOMXMLSignature extends DOMStructure } public boolean validate(XMLValidateContext vc) - throws XMLSignatureException { - + throws XMLSignatureException + { if (vc == null) { throw new NullPointerException("validateContext is null"); } @@ -258,20 +263,20 @@ public final class DOMXMLSignature extends DOMStructure } // validate all References - List refs = this.si.getReferences(); + @SuppressWarnings("unchecked") + List refs = this.si.getReferences(); boolean validateRefs = true; for (int i = 0, size = refs.size(); validateRefs && i < size; i++) { - Reference ref = (Reference) refs.get(i); + Reference ref = refs.get(i); boolean refValid = ref.validate(vc); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Reference[" + ref.getURI() + "] is valid: " - + refValid); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Reference[" + ref.getURI() + "] is valid: " + refValid); } validateRefs &= refValid; } if (!validateRefs) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Couldn't validate the References"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Couldn't validate the References"); } validationStatus = false; validated = true; @@ -281,27 +286,30 @@ public final class DOMXMLSignature extends DOMStructure // validate Manifests, if property set boolean validateMans = true; if (Boolean.TRUE.equals(vc.getProperty - ("org.jcp.xml.dsig.validateManifests"))) { - + ("org.jcp.xml.dsig.validateManifests"))) + { for (int i=0, size=objects.size(); validateMans && i < size; i++) { - XMLObject xo = (XMLObject) objects.get(i); - List content = xo.getContent(); + XMLObject xo = objects.get(i); + @SuppressWarnings("unchecked") + List content = xo.getContent(); int csize = content.size(); for (int j = 0; validateMans && j < csize; j++) { - XMLStructure xs = (XMLStructure) content.get(j); + XMLStructure xs = content.get(j); if (xs instanceof Manifest) { - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "validating manifest"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "validating manifest"); } - Manifest man = (Manifest) xs; - List manRefs = man.getReferences(); + Manifest man = (Manifest)xs; + @SuppressWarnings("unchecked") + List manRefs = man.getReferences(); int rsize = manRefs.size(); for (int k = 0; validateMans && k < rsize; k++) { - Reference ref = (Reference) manRefs.get(k); + Reference ref = manRefs.get(k); boolean refValid = ref.validate(vc); - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "Manifest ref[" - + ref.getURI() + "] is valid: " + refValid); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Manifest ref[" + ref.getURI() + "] is valid: " + refValid + ); } validateMans &= refValid; } @@ -316,41 +324,39 @@ public final class DOMXMLSignature extends DOMStructure } public void sign(XMLSignContext signContext) - throws MarshalException, XMLSignatureException { + throws MarshalException, XMLSignatureException + { if (signContext == null) { throw new NullPointerException("signContext cannot be null"); } - DOMSignContext context = (DOMSignContext) signContext; - if (context != null) { - marshal(context.getParent(), context.getNextSibling(), + DOMSignContext context = (DOMSignContext)signContext; + marshal(context.getParent(), context.getNextSibling(), DOMUtils.getSignaturePrefix(context), context); - } // generate references and signature value - List allReferences = new ArrayList(); + List allReferences = new ArrayList(); // traverse the Signature and register all objects with IDs that // may contain References - signatureIdMap = new HashMap(); + signatureIdMap = new HashMap(); signatureIdMap.put(id, this); signatureIdMap.put(si.getId(), si); - List refs = si.getReferences(); - for (int i = 0, size = refs.size(); i < size; i++) { - Reference ref = (Reference) refs.get(i); + @SuppressWarnings("unchecked") + List refs = si.getReferences(); + for (Reference ref : refs) { signatureIdMap.put(ref.getId(), ref); } - for (int i = 0, size = objects.size(); i < size; i++) { - XMLObject obj = (XMLObject) objects.get(i); + for (XMLObject obj : objects) { signatureIdMap.put(obj.getId(), obj); - List content = obj.getContent(); - for (int j = 0, csize = content.size(); j < csize; j++) { - XMLStructure xs = (XMLStructure) content.get(j); + @SuppressWarnings("unchecked") + List content = obj.getContent(); + for (XMLStructure xs : content) { if (xs instanceof Manifest) { - Manifest man = (Manifest) xs; + Manifest man = (Manifest)xs; signatureIdMap.put(man.getId(), man); - List manRefs = man.getReferences(); - for (int k = 0, msize = manRefs.size(); k < msize; k++) { - Reference ref = (Reference) manRefs.get(k); + @SuppressWarnings("unchecked") + List manRefs = man.getReferences(); + for (Reference ref : manRefs) { allReferences.add(ref); signatureIdMap.put(ref.getId(), ref); } @@ -359,56 +365,51 @@ public final class DOMXMLSignature extends DOMStructure } // always add SignedInfo references after Manifest references so // that Manifest reference are digested first - allReferences.addAll(si.getReferences()); + allReferences.addAll(refs); // generate/digest each reference - for (int i = 0, size = allReferences.size(); i < size; i++) { - DOMReference ref = (DOMReference) allReferences.get(i); - digestReference(ref, signContext); + for (Reference ref : allReferences) { + digestReference((DOMReference)ref, signContext); } // do final sweep to digest any references that were skipped or missed - for (int i = 0, size = allReferences.size(); i < size; i++) { - DOMReference ref = (DOMReference) allReferences.get(i); - if (ref.isDigested()) { + for (Reference ref : allReferences) { + if (((DOMReference)ref).isDigested()) { continue; } - ref.digest(signContext); + ((DOMReference)ref).digest(signContext); } Key signingKey = null; KeySelectorResult ksr = null; try { - ksr = signContext.getKeySelector().select - (ki, KeySelector.Purpose.SIGN, - si.getSignatureMethod(), signContext); + ksr = signContext.getKeySelector().select(ki, + KeySelector.Purpose.SIGN, + si.getSignatureMethod(), + signContext); signingKey = ksr.getKey(); if (signingKey == null) { throw new XMLSignatureException("the keySelector did not " + - "find a signing key"); + "find a signing key"); } } catch (KeySelectorException kse) { throw new XMLSignatureException("cannot find signing key", kse); } // calculate signature value - byte[] val = null; try { - val = ((DOMSignatureMethod) si.getSignatureMethod()).sign - (signingKey, (DOMSignedInfo) si, signContext); + byte[] val = ((AbstractDOMSignatureMethod) + si.getSignatureMethod()).sign(signingKey, si, signContext); + ((DOMSignatureValue)sv).setValue(val); } catch (InvalidKeyException ike) { throw new XMLSignatureException(ike); } - if (log.isLoggable(Level.FINE)) { - log.log(Level.FINE, "SignatureValue = " + val); - } - ((DOMSignatureValue) sv).setValue(val); - this.localSigElem = sigElem; this.ksr = ksr; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -417,22 +418,39 @@ public final class DOMXMLSignature extends DOMStructure if (!(o instanceof XMLSignature)) { return false; } - XMLSignature osig = (XMLSignature) o; + XMLSignature osig = (XMLSignature)o; boolean idEqual = (id == null ? osig.getId() == null : id.equals(osig.getId())); boolean keyInfoEqual = - (ki == null ? osig.getKeyInfo() == null : - ki.equals(osig.getKeyInfo())); + (ki == null ? osig.getKeyInfo() == null + : ki.equals(osig.getKeyInfo())); return (idEqual && keyInfoEqual && - sv.equals(osig.getSignatureValue()) && - si.equals(osig.getSignedInfo()) && - objects.equals(osig.getObjects())); + sv.equals(osig.getSignatureValue()) && + si.equals(osig.getSignedInfo()) && + objects.equals(osig.getObjects())); + } + + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + if (ki != null) { + result = 31 * result + ki.hashCode(); + } + result = 31 * result + sv.hashCode(); + result = 31 * result + si.hashCode(); + result = 31 * result + objects.hashCode(); + + return result; } private void digestReference(DOMReference ref, XMLSignContext signContext) - throws XMLSignatureException { + throws XMLSignatureException + { if (ref.isDigested()) { return; } @@ -441,15 +459,15 @@ public final class DOMXMLSignature extends DOMStructure if (Utils.sameDocumentURI(uri)) { String id = Utils.parseIdFromSameDocumentURI(uri); if (id != null && signatureIdMap.containsKey(id)) { - Object obj = signatureIdMap.get(id); - if (obj instanceof DOMReference) { - digestReference((DOMReference) obj, signContext); - } else if (obj instanceof Manifest) { - Manifest man = (Manifest) obj; + XMLStructure xs = signatureIdMap.get(id); + if (xs instanceof DOMReference) { + digestReference((DOMReference)xs, signContext); + } else if (xs instanceof Manifest) { + Manifest man = (Manifest)xs; List manRefs = man.getReferences(); for (int i = 0, size = manRefs.size(); i < size; i++) { - digestReference - ((DOMReference) manRefs.get(i), signContext); + digestReference((DOMReference)manRefs.get(i), + signContext); } } } @@ -457,9 +475,9 @@ public final class DOMXMLSignature extends DOMStructure // reference dependencies in the XPath Transform - so be on // the safe side, and skip and do at end in the final sweep if (uri.length() == 0) { - List transforms = ref.getTransforms(); - for (int i = 0, size = transforms.size(); i < size; i++) { - Transform transform = (Transform) transforms.get(i); + @SuppressWarnings("unchecked") + List transforms = ref.getTransforms(); + for (Transform transform : transforms) { String transformAlg = transform.getAlgorithm(); if (transformAlg.equals(Transform.XPATH) || transformAlg.equals(Transform.XPATH2)) { @@ -472,8 +490,8 @@ public final class DOMXMLSignature extends DOMStructure } public class DOMSignatureValue extends DOMStructure - implements SignatureValue { - + implements SignatureValue + { private String id; private byte[] value; private String valueBase64; @@ -485,7 +503,9 @@ public final class DOMXMLSignature extends DOMStructure this.id = id; } - DOMSignatureValue(Element sigValueElem) throws MarshalException { + DOMSignatureValue(Element sigValueElem, XMLCryptoContext context) + throws MarshalException + { try { // base64 decode signatureValue value = Base64.decode(sigValueElem); @@ -508,12 +528,12 @@ public final class DOMXMLSignature extends DOMStructure } public byte[] getValue() { - return (value == null) ? null : (byte[]) value.clone(); + return (value == null) ? null : (byte[])value.clone(); } public boolean validate(XMLValidateContext validateContext) - throws XMLSignatureException { - + throws XMLSignatureException + { if (validateContext == null) { throw new NullPointerException("context cannot be null"); } @@ -531,18 +551,18 @@ public final class DOMXMLSignature extends DOMStructure (ki, KeySelector.Purpose.VERIFY, sm, validateContext); validationKey = ksResult.getKey(); if (validationKey == null) { - throw new XMLSignatureException("the keyselector did " + - "not find a validation key"); + throw new XMLSignatureException("the keyselector did not " + + "find a validation key"); } } catch (KeySelectorException kse) { throw new XMLSignatureException("cannot find validation " + - "key", kse); + "key", kse); } // canonicalize SignedInfo and verify signature try { - validationStatus = ((DOMSignatureMethod) sm).verify - (validationKey, (DOMSignedInfo) si, value, validateContext); + validationStatus = ((AbstractDOMSignatureMethod)sm).verify + (validationKey, si, value, validateContext); } catch (Exception e) { throw new XMLSignatureException(e); } @@ -552,6 +572,7 @@ public final class DOMXMLSignature extends DOMStructure return validationStatus; } + @Override public boolean equals(Object o) { if (this == o) { return true; @@ -560,7 +581,7 @@ public final class DOMXMLSignature extends DOMStructure if (!(o instanceof SignatureValue)) { return false; } - SignatureValue osv = (SignatureValue) o; + SignatureValue osv = (SignatureValue)o; boolean idEqual = (id == null ? osv.getId() == null : id.equals(osv.getId())); @@ -569,12 +590,23 @@ public final class DOMXMLSignature extends DOMStructure return idEqual; } - public void marshal(Node parent, String dsPrefix, - DOMCryptoContext context) throws MarshalException { + @Override + public int hashCode() { + int result = 17; + if (id != null) { + result = 31 * result + id.hashCode(); + } + return result; + } + + public void marshal(Node parent, String dsPrefix, + DOMCryptoContext context) + throws MarshalException + { // create SignatureValue element - sigValueElem = DOMUtils.createElement - (ownerDoc, "SignatureValue", XMLSignature.XMLNS, dsPrefix); + sigValueElem = DOMUtils.createElement(ownerDoc, "SignatureValue", + XMLSignature.XMLNS, dsPrefix); if (valueBase64 != null) { sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64)); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java index fb9664db0c1..b085a33f5e5 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java @@ -2,31 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXMLSignatureFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; import javax.xml.crypto.*; +import javax.xml.crypto.dom.DOMCryptoContext; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.*; @@ -34,7 +37,6 @@ import javax.xml.crypto.dsig.spec.*; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; -import java.security.spec.AlgorithmParameterSpec; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -56,6 +58,7 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { return new DOMXMLSignature(si, ki, null, null, null); } + @SuppressWarnings("unchecked") public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki, List objects, String id, String signatureValueId) { return new DOMXMLSignature(si, ki, objects, id, signatureValueId); @@ -65,11 +68,13 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { return newReference(uri, dm, null, null, null); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id) { return new DOMReference(uri, type, dm, transforms, id, getProvider()); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List appliedTransforms, Data result, List transforms, String type, String id) { @@ -86,6 +91,7 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { (uri, type, dm, appliedTransforms, result, transforms, id, getProvider()); } + @SuppressWarnings("unchecked") public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id, byte[] digestValue) { if (digestValue == null) { @@ -95,34 +101,41 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { (uri, type, dm, null, null, transforms, id, digestValue, getProvider()); } + @SuppressWarnings("unchecked") public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references) { return newSignedInfo(cm, sm, references, null); } + @SuppressWarnings("unchecked") public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references, String id) { return new DOMSignedInfo(cm, sm, references, id); } // Object factory methods + @SuppressWarnings("unchecked") public XMLObject newXMLObject(List content, String id, String mimeType, String encoding) { return new DOMXMLObject(content, id, mimeType, encoding); } + @SuppressWarnings("unchecked") public Manifest newManifest(List references) { return newManifest(references, null); } + @SuppressWarnings("unchecked") public Manifest newManifest(List references, String id) { return new DOMManifest(references, id); } + @SuppressWarnings("unchecked") public SignatureProperties newSignatureProperties(List props, String id) { return new DOMSignatureProperties(props, id); } + @SuppressWarnings("unchecked") public SignatureProperty newSignatureProperty (List info, String target, String id) { return new DOMSignatureProperty(info, target, id); @@ -143,12 +156,19 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { if (xmlStructure == null) { throw new NullPointerException("xmlStructure cannot be null"); } + if (!(xmlStructure instanceof javax.xml.crypto.dom.DOMStructure)) { + throw new ClassCastException("xmlStructure must be of type DOMStructure"); + } return unmarshal (((javax.xml.crypto.dom.DOMStructure) xmlStructure).getNode(), - null); + new UnmarshalContext()); } - private XMLSignature unmarshal(Node node, XMLValidateContext context) + private static class UnmarshalContext extends DOMCryptoContext { + UnmarshalContext() {} + } + + private XMLSignature unmarshal(Node node, XMLCryptoContext context) throws MarshalException { node.normalize(); @@ -221,12 +241,20 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { return new DOMSignatureMethod.SHA1withDSA(params); } else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) { return new DOMHMACSignatureMethod.SHA1(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA256)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) { return new DOMHMACSignatureMethod.SHA256(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA384)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA384)) { return new DOMHMACSignatureMethod.SHA384(params); - } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA512)) { + } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA512)) { return new DOMHMACSignatureMethod.SHA512(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA1)) { + return new DOMSignatureMethod.SHA1withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA256)) { + return new DOMSignatureMethod.SHA256withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA384)) { + return new DOMSignatureMethod.SHA384withECDSA(params); + } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA512)) { + return new DOMSignatureMethod.SHA512withECDSA(params); } else { throw new NoSuchAlgorithmException("unsupported algorithm"); } @@ -235,12 +263,18 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { public Transform newTransform(String algorithm, TransformParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { + TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + spi.init(params); return new DOMTransform(spi); } @@ -249,11 +283,16 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + if (params == null) { spi.init(null); } else { @@ -266,11 +305,16 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { C14NMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } + spi.init(params); return new DOMCanonicalizationMethod(spi); } @@ -279,16 +323,21 @@ public final class DOMXMLSignatureFactory extends XMLSignatureFactory { XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; - try { + if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); - } catch (NoSuchAlgorithmException nsae) { - spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } else { + try { + spi = TransformService.getInstance(algorithm, "DOM", getProvider()); + } catch (NoSuchAlgorithmException nsae) { + spi = TransformService.getInstance(algorithm, "DOM"); + } } if (params == null) { spi.init(null); } else { spi.init(params, null); } + return new DOMCanonicalizationMethod(spi); } diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java index 6da75e93b23..edabc988002 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * =========================================================================== @@ -29,7 +31,7 @@ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXPathFilter2Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXPathFilter2Transform.java 1203789 2011-11-18 18:46:07Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -40,10 +42,10 @@ import javax.xml.crypto.dsig.spec.XPathType; import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; import java.security.InvalidAlgorithmParameterException; import java.util.ArrayList; -import java.util.Iterator; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; +import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -57,7 +59,8 @@ import org.w3c.dom.NamedNodeMap; public final class DOMXPathFilter2Transform extends ApacheTransform { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilter2ParameterSpec)) { @@ -68,23 +71,23 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - + throws InvalidAlgorithmParameterException + { super.init(parent, context); try { unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } catch (MarshalException me) { - throw (InvalidAlgorithmParameterException) - new InvalidAlgorithmParameterException().initCause(me); + throw new InvalidAlgorithmParameterException(me); } } - private void unmarshalParams(Element curXPathElem) throws MarshalException { - List list = new ArrayList(); + private void unmarshalParams(Element curXPathElem) throws MarshalException + { + List list = new ArrayList(); while (curXPathElem != null) { String xPath = curXPathElem.getFirstChild().getNodeValue(); - String filterVal = - DOMUtils.getAttributeValue(curXPathElem, "Filter"); + String filterVal = DOMUtils.getAttributeValue(curXPathElem, + "Filter"); if (filterVal == null) { throw new MarshalException("filter cannot be null"); } @@ -96,15 +99,16 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { } else if (filterVal.equals("union")) { filter = XPathType.Filter.UNION; } else { - throw new MarshalException("Unknown XPathType filter type" - + filterVal); + throw new MarshalException("Unknown XPathType filter type" + + filterVal); } NamedNodeMap attributes = curXPathElem.getAttributes(); if (attributes != null) { int length = attributes.getLength(); - Map namespaceMap = new HashMap(length); + Map namespaceMap = + new HashMap(length); for (int i = 0; i < length; i++) { - Attr attr = (Attr) attributes.item(i); + Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && prefix.equals("xmlns")) { namespaceMap.put(attr.getLocalName(), attr.getValue()); @@ -121,32 +125,34 @@ public final class DOMXPathFilter2Transform extends ApacheTransform { } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); XPathFilter2ParameterSpec xp = - (XPathFilter2ParameterSpec) getParameterSpec(); + (XPathFilter2ParameterSpec)getParameterSpec(); String prefix = DOMUtils.getNSPrefix(context, Transform.XPATH2); String qname = (prefix == null || prefix.length() == 0) ? "xmlns" : "xmlns:" + prefix; - List list = xp.getXPathList(); - for (int i = 0, size = list.size(); i < size; i++) { - XPathType xpathType = (XPathType) list.get(i); - Element elem = DOMUtils.createElement - (ownerDoc, "XPath", Transform.XPATH2, prefix); + @SuppressWarnings("unchecked") + List xpathList = xp.getXPathList(); + for (XPathType xpathType : xpathList) { + Element elem = DOMUtils.createElement(ownerDoc, "XPath", + Transform.XPATH2, prefix); elem.appendChild (ownerDoc.createTextNode(xpathType.getExpression())); - DOMUtils.setAttribute - (elem, "Filter", xpathType.getFilter().toString()); + DOMUtils.setAttribute(elem, "Filter", + xpathType.getFilter().toString()); elem.setAttributeNS("http://www.w3.org/2000/xmlns/", qname, - Transform.XPATH2); + Transform.XPATH2); // add namespace attributes, if necessary - Iterator it = xpathType.getNamespaceMap().entrySet().iterator(); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" - + (String) entry.getKey(), (String) entry.getValue()); + @SuppressWarnings("unchecked") + Set> entries = + xpathType.getNamespaceMap().entrySet(); + for (Map.Entry entry : entries) { + elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + entry.getKey(), + entry.getValue()); } transformElem.appendChild(elem); diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java index 6258561f10b..aaf8d22bc20 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXPathTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXPathTransform.java 1203789 2011-11-18 18:46:07Z mullan $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,9 +33,9 @@ import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec; import java.security.InvalidAlgorithmParameterException; -import java.util.Iterator; -import java.util.Map; import java.util.HashMap; +import java.util.Map; +import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -47,7 +49,8 @@ import org.w3c.dom.NamedNodeMap; public final class DOMXPathTransform extends ApacheTransform { public void init(TransformParameterSpec params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException + { if (params == null) { throw new InvalidAlgorithmParameterException("params are required"); } else if (!(params instanceof XPathFilterParameterSpec)) { @@ -58,8 +61,8 @@ public final class DOMXPathTransform extends ApacheTransform { } public void init(XMLStructure parent, XMLCryptoContext context) - throws InvalidAlgorithmParameterException { - + throws InvalidAlgorithmParameterException + { super.init(parent, context); unmarshalParams(DOMUtils.getFirstChildElement(transformElem)); } @@ -70,9 +73,10 @@ public final class DOMXPathTransform extends ApacheTransform { NamedNodeMap attributes = paramsElem.getAttributes(); if (attributes != null) { int length = attributes.getLength(); - Map namespaceMap = new HashMap(length); + Map namespaceMap = + new HashMap(length); for (int i = 0; i < length; i++) { - Attr attr = (Attr) attributes.item(i); + Attr attr = (Attr)attributes.item(i); String prefix = attr.getPrefix(); if (prefix != null && prefix.equals("xmlns")) { namespaceMap.put(attr.getLocalName(), attr.getValue()); @@ -85,22 +89,23 @@ public final class DOMXPathTransform extends ApacheTransform { } public void marshalParams(XMLStructure parent, XMLCryptoContext context) - throws MarshalException { - + throws MarshalException + { super.marshalParams(parent, context); XPathFilterParameterSpec xp = - (XPathFilterParameterSpec) getParameterSpec(); - Element xpathElem = DOMUtils.createElement - (ownerDoc, "XPath", XMLSignature.XMLNS, - DOMUtils.getSignaturePrefix(context)); + (XPathFilterParameterSpec)getParameterSpec(); + Element xpathElem = DOMUtils.createElement(ownerDoc, "XPath", + XMLSignature.XMLNS, DOMUtils.getSignaturePrefix(context)); xpathElem.appendChild(ownerDoc.createTextNode(xp.getXPath())); // add namespace attributes, if necessary - Iterator i = xp.getNamespaceMap().entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" - + (String) entry.getKey(), (String) entry.getValue()); + @SuppressWarnings("unchecked") + Set> entries = + xp.getNamespaceMap().entrySet(); + for (Map.Entry entry : entries) { + xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + + entry.getKey(), + entry.getValue()); } transformElem.appendChild(xpathElem); diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java index cc1362bcc0d..06bb624309d 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: DOMXSLTTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: DOMXSLTTransform.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -31,7 +33,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import javax.xml.crypto.*; -import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec; diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java index 8f0e3526806..8c080609c6d 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java @@ -2,27 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: Utils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: Utils.java 1197150 2011-11-03 14:34:57Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -44,7 +46,8 @@ public final class Utils { private Utils() {} public static byte[] readBytesFromStream(InputStream is) - throws IOException { + throws IOException + { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; while (true) { @@ -67,10 +70,10 @@ public final class Utils { * @param i the Iterator * @return the Set of Nodes */ - static Set toNodeSet(Iterator i) { - Set nodeSet = new HashSet(); + static Set toNodeSet(Iterator i) { + Set nodeSet = new HashSet(); while (i.hasNext()) { - Node n = (Node) i.next(); + Node n = i.next(); nodeSet.add(n); // insert attributes nodes to comply with XPath if (n.getNodeType() == Node.ELEMENT_NODE) { diff --git a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java index c122cb176a7..2cc871485b3 100644 --- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java +++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ /* * =========================================================================== @@ -29,7 +31,7 @@ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. */ /* - * $Id: XMLDSigRI.java,v 1.2 2008/07/24 15:20:32 mullan Exp $ + * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $ */ package org.jcp.xml.dsig.internal.dom; @@ -53,13 +55,15 @@ public final class XMLDSigRI extends Provider { static final long serialVersionUID = -5049765099299494554L; private static final String INFO = "XMLDSig " + - "(DOM XMLSignatureFactory; DOM KeyInfoFactory)"; + "(DOM XMLSignatureFactory; DOM KeyInfoFactory; " + + "C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " + + "XPath2, XSLT TransformServices)"; public XMLDSigRI() { /* We are the XMLDSig provider */ - super("XMLDSig", 1.0, INFO); + super("XMLDSig", 1.8, INFO); - final Map map = new HashMap(); + final Map map = new HashMap(); map.put("XMLSignatureFactory.DOM", "org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory"); map.put("KeyInfoFactory.DOM", @@ -67,94 +71,89 @@ public final class XMLDSigRI extends Provider { // Inclusive C14N - map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE, + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE, "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod"); map.put("Alg.Alias.TransformService.INCLUSIVE", CanonicalizationMethod.INCLUSIVE); - map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE + " MechanismType", "DOM"); // InclusiveWithComments C14N - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod"); map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS", CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS); - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS + " MechanismType", "DOM"); // Inclusive C14N 1.1 - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11", + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11", "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method"); - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11" + + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11" + " MechanismType", "DOM"); // InclusiveWithComments C14N 1.1 - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11#WithComments", + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments", "org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method"); - map.put((String)"TransformService." + - "http://www.w3.org/2006/12/xml-c14n11#WithComments" + + map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11#WithComments" + " MechanismType", "DOM"); // Exclusive C14N - map.put((String) "TransformService." + CanonicalizationMethod.EXCLUSIVE, + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE, "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod"); map.put("Alg.Alias.TransformService.EXCLUSIVE", CanonicalizationMethod.EXCLUSIVE); - map.put((String)"TransformService." + CanonicalizationMethod.EXCLUSIVE + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE + " MechanismType", "DOM"); // ExclusiveWithComments C14N - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, "org.jcp.xml.dsig.internal.dom.DOMExcC14NMethod"); map.put("Alg.Alias.TransformService.EXCLUSIVE_WITH_COMMENTS", CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS); - map.put((String) "TransformService." + + map.put("TransformService." + CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS + " MechanismType", "DOM"); // Base64 Transform - map.put((String) "TransformService." + Transform.BASE64, + map.put("TransformService." + Transform.BASE64, "org.jcp.xml.dsig.internal.dom.DOMBase64Transform"); map.put("Alg.Alias.TransformService.BASE64", Transform.BASE64); - map.put((String) "TransformService." + Transform.BASE64 + + map.put("TransformService." + Transform.BASE64 + " MechanismType", "DOM"); // Enveloped Transform - map.put((String) "TransformService." + Transform.ENVELOPED, + map.put("TransformService." + Transform.ENVELOPED, "org.jcp.xml.dsig.internal.dom.DOMEnvelopedTransform"); map.put("Alg.Alias.TransformService.ENVELOPED", Transform.ENVELOPED); - map.put((String) "TransformService." + Transform.ENVELOPED + + map.put("TransformService." + Transform.ENVELOPED + " MechanismType", "DOM"); // XPath2 Transform - map.put((String) "TransformService." + Transform.XPATH2, + map.put("TransformService." + Transform.XPATH2, "org.jcp.xml.dsig.internal.dom.DOMXPathFilter2Transform"); map.put("Alg.Alias.TransformService.XPATH2", Transform.XPATH2); - map.put((String) "TransformService." + Transform.XPATH2 + + map.put("TransformService." + Transform.XPATH2 + " MechanismType", "DOM"); // XPath Transform - map.put((String) "TransformService." + Transform.XPATH, + map.put("TransformService." + Transform.XPATH, "org.jcp.xml.dsig.internal.dom.DOMXPathTransform"); map.put("Alg.Alias.TransformService.XPATH", Transform.XPATH); - map.put((String) "TransformService." + Transform.XPATH + + map.put("TransformService." + Transform.XPATH + " MechanismType", "DOM"); // XSLT Transform - map.put((String) "TransformService." + Transform.XSLT, + map.put("TransformService." + Transform.XSLT, "org.jcp.xml.dsig.internal.dom.DOMXSLTTransform"); map.put("Alg.Alias.TransformService.XSLT", Transform.XSLT); - map.put((String) "TransformService." + Transform.XSLT + - " MechanismType", "DOM"); + map.put("TransformService." + Transform.XSLT + " MechanismType", "DOM"); - AccessController.doPrivileged(new java.security.PrivilegedAction() { - public Object run() { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { putAll(map); return null; }