--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/Algorithm.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,82 +2,78 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
-
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-
/**
* The Algorithm class which stores the Algorithm URI as a string.
- *
*/
public abstract class Algorithm extends SignatureElementProxy {
- /**
- *
- * @param doc
- * @param algorithmURI is the URI of the algorithm as String
- */
- public Algorithm(Document doc, String algorithmURI) {
+ /**
+ *
+ * @param doc
+ * @param algorithmURI is the URI of the algorithm as String
+ */
+ public Algorithm(Document doc, String algorithmURI) {
+ super(doc);
+
+ this.setAlgorithmURI(algorithmURI);
+ }
- super(doc);
-
- this.setAlgorithmURI(algorithmURI);
- }
+ /**
+ * Constructor Algorithm
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public Algorithm(Element element, String BaseURI) throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- /**
- * Constructor Algorithm
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public Algorithm(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Method getAlgorithmURI
+ *
+ * @return The URI of the algorithm
+ */
+ public String getAlgorithmURI() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ }
- /**
- * Method getAlgorithmURI
- *
- * @return The URI of the alogrithm
- */
- public String getAlgorithmURI() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
- }
-
- /**
- * Sets the algorithm's URI as used in the signature.
- *
- * @param algorithmURI is the URI of the algorithm as String
- */
- protected void setAlgorithmURI(String algorithmURI) {
-
- if ( (algorithmURI != null)) {
- this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM,
- algorithmURI);
- }
- }
+ /**
+ * Sets the algorithm's URI as used in the signature.
+ *
+ * @param algorithmURI is the URI of the algorithm as String
+ */
+ protected void setAlgorithmURI(String algorithmURI) {
+ if (algorithmURI != null) {
+ this.constructionElement.setAttributeNS(
+ null, Constants._ATT_ALGORITHM, algorithmURI
+ );
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/JCEMapper.java Fri Jul 05 14:37:41 2013 -0700
@@ -115,6 +115,18 @@
new Algorithm("", "SHA1withECDSA", "Signature")
);
algorithmsMap.put(
+ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256,
+ new Algorithm("", "SHA256withECDSA", "Signature")
+ );
+ algorithmsMap.put(
+ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384,
+ new Algorithm("", "SHA384withECDSA", "Signature")
+ );
+ algorithmsMap.put(
+ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512,
+ new Algorithm("", "SHA512withECDSA", "Signature")
+ );
+ algorithmsMap.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
new Algorithm("", "HmacMD5", "Mac")
);
@@ -155,6 +167,18 @@
new Algorithm("AES", "AES/CBC/ISO10126Padding", "BlockEncryption", 256)
);
algorithmsMap.put(
+ XMLCipher.AES_128_GCM,
+ new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 128)
+ );
+ algorithmsMap.put(
+ XMLCipher.AES_192_GCM,
+ new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 192)
+ );
+ algorithmsMap.put(
+ XMLCipher.AES_256_GCM,
+ new Algorithm("AES", "AES/GCM/NoPadding", "BlockEncryption", 256)
+ );
+ algorithmsMap.put(
XMLCipher.RSA_v1dot5,
new Algorithm("RSA", "RSA/ECB/PKCS1Padding", "KeyTransport")
);
@@ -163,6 +187,10 @@
new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
);
algorithmsMap.put(
+ XMLCipher.RSA_OAEP_11,
+ new Algorithm("RSA", "RSA/ECB/OAEPPadding", "KeyTransport")
+ );
+ algorithmsMap.put(
XMLCipher.DIFFIE_HELLMAN,
new Algorithm("", "", "KeyAgreement")
);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/MessageDigestAlgorithm.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,265 +2,254 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.MessageDigest;
import java.security.NoSuchProviderException;
-import java.util.HashMap;
-import java.util.Map;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
import org.w3c.dom.Document;
-
/**
* Digest Message wrapper & selector class.
*
* <pre>
* MessageDigestAlgorithm.getInstance()
* </pre>
- *
*/
public class MessageDigestAlgorithm extends Algorithm {
/** Message Digest - NOT RECOMMENDED MD5*/
- public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5";
- /** Digest - Required SHA1*/
- public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
- /** Message Digest - RECOMMENDED SHA256*/
- public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256";
- /** Message Digest - OPTIONAL SHA384*/
- public static final String ALGO_ID_DIGEST_SHA384 = Constants.MoreAlgorithmsSpecNS + "sha384";
- /** Message Digest - OPTIONAL SHA512*/
- public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512";
- /** Message Digest - OPTIONAL RIPEMD-160*/
- public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160";
+ public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 =
+ Constants.MoreAlgorithmsSpecNS + "md5";
+ /** Digest - Required SHA1*/
+ public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1";
+ /** Message Digest - RECOMMENDED SHA256*/
+ public static final String ALGO_ID_DIGEST_SHA256 =
+ EncryptionConstants.EncryptionSpecNS + "sha256";
+ /** Message Digest - OPTIONAL SHA384*/
+ public static final String ALGO_ID_DIGEST_SHA384 =
+ Constants.MoreAlgorithmsSpecNS + "sha384";
+ /** Message Digest - OPTIONAL SHA512*/
+ public static final String ALGO_ID_DIGEST_SHA512 =
+ EncryptionConstants.EncryptionSpecNS + "sha512";
+ /** Message Digest - OPTIONAL RIPEMD-160*/
+ public static final String ALGO_ID_DIGEST_RIPEMD160 =
+ EncryptionConstants.EncryptionSpecNS + "ripemd160";
- /** Field algorithm stores the actual {@link java.security.MessageDigest} */
- java.security.MessageDigest algorithm = null;
-
- /**
- * 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) {
+ /** Field algorithm stores the actual {@link java.security.MessageDigest} */
+ private final MessageDigest algorithm;
- super(doc, algorithmURI);
-
- this.algorithm = messageDigest;
- }
+ /**
+ * 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);
- static ThreadLocal<Map<String, MessageDigest>> instances=new
- ThreadLocal<Map<String, MessageDigest>>() {
- protected Map<String, MessageDigest> initialValue() {
- return new HashMap<String, MessageDigest>();
- };
- };
+ algorithm = getDigestInstance(algorithmURI);
+ }
- /**
- * Factory method for constructing a message digest algorithm by name.
- *
- * @param doc
- * @param algorithmURI
- * @return The MessageDigestAlgorithm element to attach in document and to digest
- * @throws XMLSignatureException
- */
- public static MessageDigestAlgorithm getInstance(
- Document doc, String algorithmURI) throws XMLSignatureException {
- MessageDigest md = getDigestInstance(algorithmURI);
- return new MessageDigestAlgorithm(doc, md, algorithmURI);
- }
+ /**
+ * Factory method for constructing a message digest algorithm by name.
+ *
+ * @param doc
+ * @param algorithmURI
+ * @return The MessageDigestAlgorithm element to attach in document and to digest
+ * @throws XMLSignatureException
+ */
+ public static MessageDigestAlgorithm getInstance(
+ Document doc, String algorithmURI
+ ) throws XMLSignatureException {
+ return new MessageDigestAlgorithm(doc, algorithmURI);
+ }
+
+ private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
+ String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
-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);
- }
+ if (algorithmID == null) {
+ Object[] exArgs = { algorithmURI };
+ throw new XMLSignatureException("algorithms.NoSuchMap", exArgs);
+ }
- MessageDigest md;
- String provider=JCEMapper.getProviderId();
- try {
- if (provider==null) {
+ 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() };
+ } 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;
+ }
- throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
- } catch (NoSuchProviderException ex) {
- Object[] exArgs = { algorithmID,
- ex.getLocalizedMessage() };
-
- throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
- }
- instances.get().put(algorithmURI, md);
- return md;
-}
+ /**
+ * Returns the actual {@link java.security.MessageDigest} algorithm object
+ *
+ * @return the actual {@link java.security.MessageDigest} algorithm object
+ */
+ public java.security.MessageDigest getAlgorithm() {
+ return algorithm;
+ }
- /**
- * 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#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()}
- * 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[])}
+ * 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 this.algorithm.digest(buf, offset, len);
- }
+ /**
+ * 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 this.algorithm.getAlgorithm();
- }
+ /**
+ * 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 this.algorithm.getProvider();
- }
+ /**
+ * 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 this.algorithm.getDigestLength();
- }
+ /**
+ * 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() {
- this.algorithm.reset();
- }
+ /**
+ * 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) {
- 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) {
+ 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)}
+ * 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) {
- this.algorithm.update(buf, offset, len);
- }
+ /**
+ * 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 getBaseNamespace() {
+ return Constants.SignatureSpecNS;
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_DIGESTMETHOD;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_DIGESTMETHOD;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java Fri Jul 05 14:37:41 2013 -0700
@@ -74,7 +74,7 @@
this.algorithmURI = algorithmURI;
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
- signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+ signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
}
/**
@@ -92,10 +92,10 @@
this.algorithmURI = algorithmURI;
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
- signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+ signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength);
- ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(_constructionElement);
+ ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement);
}
/**
@@ -136,7 +136,7 @@
}
signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
- signatureAlgorithm.engineGetContextFromElement(this._constructionElement);
+ signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
}
/**
@@ -310,7 +310,7 @@
* @return the URI representation of Transformation algorithm
*/
public final String getURI() {
- return _constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ return constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
}
/**
@@ -380,9 +380,7 @@
* This method registers the default algorithms.
*/
public static void registerDefaultAlgorithms() {
- algorithmHash.put(
- XMLSignature.ALGO_ID_SIGNATURE_DSA, SignatureDSA.class
- );
+ algorithmHash.put(SignatureDSA.URI, SignatureDSA.class);
algorithmHash.put(
XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, SignatureBaseRSA.SignatureRSASHA1.class
);
@@ -410,6 +408,15 @@
XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class
);
algorithmHash.put(
+ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class
+ );
+ algorithmHash.put(
+ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384, SignatureECDSA.SignatureECDSASHA384.class
+ );
+ algorithmHash.put(
+ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class
+ );
+ algorithmHash.put(
XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class
);
algorithmHash.put(
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms;
@@ -27,157 +29,149 @@
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import org.w3c.dom.Element;
-
-/**
- *
- * @author $Author: mullan $
- */
public abstract class SignatureAlgorithmSpi {
- /**
- * Returns the URI representation of <code>Transformation algorithm</code>
- *
- * @return the URI representation of <code>Transformation algorithm</code>
- */
- protected abstract String engineGetURI();
+ /**
+ * Returns the URI representation of <code>Transformation algorithm</code>
+ *
+ * @return the URI representation of <code>Transformation algorithm</code>
+ */
+ protected abstract String engineGetURI();
- /**
- * Proxy method for {@link java.security.Signature#getAlgorithm}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @return the result of the {@link java.security.Signature#getAlgorithm} method
- */
- protected abstract String engineGetJCEAlgorithmString();
+ /**
+ * Proxy method for {@link java.security.Signature#getAlgorithm}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @return the result of the {@link java.security.Signature#getAlgorithm} method
+ */
+ protected abstract String engineGetJCEAlgorithmString();
- /**
- * Method engineGetJCEProviderName
- *
- * @return the JCE ProviderName
- */
- protected abstract String engineGetJCEProviderName();
+ /**
+ * Method engineGetJCEProviderName
+ *
+ * @return the JCE ProviderName
+ */
+ protected abstract String engineGetJCEProviderName();
- /**
- * Proxy method for {@link java.security.Signature#update(byte[])}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param input
- * @throws XMLSignatureException
- */
- protected abstract void engineUpdate(byte[] input)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#update(byte[])}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param input
+ * @throws XMLSignatureException
+ */
+ protected abstract void engineUpdate(byte[] input) throws XMLSignatureException;
+
+ /**
+ * Proxy method for {@link java.security.Signature#update(byte[])}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param input
+ * @throws XMLSignatureException
+ */
+ protected abstract void engineUpdate(byte input) throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#update(byte[])}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param input
- * @throws XMLSignatureException
- */
- protected abstract void engineUpdate(byte input)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param buf
+ * @param offset
+ * @param len
+ * @throws XMLSignatureException
+ */
+ protected abstract void engineUpdate(byte buf[], int offset, int len)
+ throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param buf
- * @param offset
- * @param len
- * @throws XMLSignatureException
- */
- protected abstract void engineUpdate(byte buf[], int offset, int len)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param signingKey
+ * @throws XMLSignatureException if this method is called on a MAC
+ */
+ protected abstract void engineInitSign(Key signingKey) throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey)}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param signingKey
- * @throws XMLSignatureException if this method is called on a MAC
- */
- protected abstract void engineInitSign(Key signingKey)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey,
+ * java.security.SecureRandom)}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param signingKey
+ * @param secureRandom
+ * @throws XMLSignatureException if this method is called on a MAC
+ */
+ protected abstract void engineInitSign(Key signingKey, SecureRandom secureRandom)
+ throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#initSign(java.security.PrivateKey, java.security.SecureRandom)}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param signingKey
- * @param secureRandom
- * @throws XMLSignatureException if this method is called on a MAC
- */
- protected abstract void engineInitSign(
- Key signingKey, SecureRandom secureRandom) throws XMLSignatureException;
-
- /**
- * Proxy method for {@link javax.crypto.Mac}
- * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object.
- *
- * @param signingKey
- * @param algorithmParameterSpec
- * @throws XMLSignatureException if this method is called on a Signature
- */
- protected abstract void engineInitSign(
- Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link javax.crypto.Mac}
+ * which is executed on the internal {@link javax.crypto.Mac#init(Key)} object.
+ *
+ * @param signingKey
+ * @param algorithmParameterSpec
+ * @throws XMLSignatureException if this method is called on a Signature
+ */
+ protected abstract void engineInitSign(
+ Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+ ) throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#sign()}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @return the result of the {@link java.security.Signature#sign()} method
- * @throws XMLSignatureException
- */
- protected abstract byte[] engineSign() throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#sign()}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @return the result of the {@link java.security.Signature#sign()} method
+ * @throws XMLSignatureException
+ */
+ protected abstract byte[] engineSign() throws XMLSignatureException;
- /**
- * Method engineInitVerify
- *
- * @param verificationKey
- * @throws XMLSignatureException
- */
- protected abstract void engineInitVerify(Key verificationKey)
- throws XMLSignatureException;
+ /**
+ * Method engineInitVerify
+ *
+ * @param verificationKey
+ * @throws XMLSignatureException
+ */
+ protected abstract void engineInitVerify(Key verificationKey) throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#verify(byte[])}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param signature
- * @return true if the signature is correct
- * @throws XMLSignatureException
- */
- protected abstract boolean engineVerify(byte[] signature)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#verify(byte[])}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param signature
+ * @return true if the signature is correct
+ * @throws XMLSignatureException
+ */
+ protected abstract boolean engineVerify(byte[] signature) throws XMLSignatureException;
- /**
- * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param params
- * @throws XMLSignatureException
- */
- protected abstract void engineSetParameter(AlgorithmParameterSpec params)
- throws XMLSignatureException;
+ /**
+ * Proxy method for {@link java.security.Signature#setParameter(
+ * java.security.spec.AlgorithmParameterSpec)}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param params
+ * @throws XMLSignatureException
+ */
+ protected abstract void engineSetParameter(AlgorithmParameterSpec params)
+ throws XMLSignatureException;
- /**
- * Method engineGetContextFromElement
- *
- * @param element
- */
- protected void engineGetContextFromElement(Element element) {
- }
+ /**
+ * Method engineGetContextFromElement
+ *
+ * @param element
+ */
+ protected void engineGetContextFromElement(Element element) {
+ }
- /**
- * Method engineSetHMACOutputLength
- *
- * @param HMACOutputLength
- * @throws XMLSignatureException
- */
- protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
- throws XMLSignatureException;
+ /**
+ * Method engineSetHMACOutputLength
+ *
+ * @param HMACOutputLength
+ * @throws XMLSignatureException
+ */
+ protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
+ throws XMLSignatureException;
public void reset() {
- }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
-
-
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
@@ -42,570 +42,498 @@
import org.w3c.dom.Element;
import org.w3c.dom.Text;
-
-/**
- *
- * @author $Author: mullan $
- */
public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName());
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(IntegrityHmac.class.getName());
+
+ /** Field macAlgorithm */
+ private Mac macAlgorithm = null;
- /**
- * Method engineGetURI
- *
- *@inheritDoc
- */
- public abstract String engineGetURI();
+ /** Field HMACOutputLength */
+ private int HMACOutputLength = 0;
+ private boolean HMACOutputLengthSet = false;
- /**
- * Returns the output length of the hash/digest.
- */
- abstract int getDigestLength();
-
- /** Field _macAlgorithm */
- private Mac _macAlgorithm = null;
- private boolean _HMACOutputLengthSet = false;
+ /**
+ * Method engineGetURI
+ *
+ *@inheritDoc
+ */
+ public abstract String engineGetURI();
- /** Field _HMACOutputLength */
- int _HMACOutputLength = 0;
-
- /**
- * Method IntegrityHmacSHA1das
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmac() throws XMLSignatureException {
+ /**
+ * Returns the output length of the hash/digest.
+ */
+ abstract int getDigestLength();
- 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);
+ /**
+ * Method IntegrityHmac
+ *
+ * @throws XMLSignatureException
+ */
+ public IntegrityHmac() throws XMLSignatureException {
+ String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
+ }
- try {
- this._macAlgorithm = Mac.getInstance(algorithmID);
- } catch (java.security.NoSuchAlgorithmException ex) {
- Object[] exArgs = { algorithmID,
- ex.getLocalizedMessage() };
+ 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;
- _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 {
+ public void reset() {
+ HMACOutputLength = 0;
+ HMACOutputLengthSet = false;
+ this.macAlgorithm.reset();
+ }
- 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)];
-
- System.arraycopy(completeResult, 0, strippedResult, 0, bytes);
-
- if (abits > 0) {
- byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
- (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE };
-
- strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]);
- }
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+ }
- return strippedResult;
- }
-
- /**
- * Method engineInitSign
- *
- * @param secretKey
- * @throws XMLSignatureException
- */
- protected void engineInitSign(Key secretKey) throws XMLSignatureException {
+ try {
+ this.macAlgorithm.init(secretKey);
+ } catch (InvalidKeyException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- if (!(secretKey instanceof SecretKey)) {
- String supplied = secretKey.getClass().getName();
- String needed = SecretKey.class.getName();
- Object exArgs[] = { supplied, needed };
-
- throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
- exArgs);
- }
-
- try {
- this._macAlgorithm.init(secretKey);
- } catch (InvalidKeyException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /**
+ * Method engineInitSign
+ *
+ * @param secretKey
+ * @param algorithmParameterSpec
+ * @throws XMLSignatureException
+ */
+ protected void engineInitSign(
+ Key secretKey, AlgorithmParameterSpec algorithmParameterSpec
+ ) throws XMLSignatureException {
+ if (!(secretKey instanceof SecretKey)) {
+ String supplied = secretKey.getClass().getName();
+ String needed = SecretKey.class.getName();
+ Object exArgs[] = { supplied, needed };
- /**
- * Method engineInitSign
- *
- * @param secretKey
- * @param algorithmParameterSpec
- * @throws XMLSignatureException
- */
- protected void engineInitSign(
- Key secretKey, AlgorithmParameterSpec algorithmParameterSpec)
- throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+ }
+
+ try {
+ this.macAlgorithm.init(secretKey, algorithmParameterSpec);
+ } catch (InvalidKeyException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (InvalidAlgorithmParameterException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- if (!(secretKey instanceof SecretKey)) {
- String supplied = secretKey.getClass().getName();
- String needed = SecretKey.class.getName();
- Object exArgs[] = { supplied, needed };
-
- throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
- exArgs);
- }
-
- try {
- this._macAlgorithm.init(secretKey, algorithmParameterSpec);
- } catch (InvalidKeyException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (InvalidAlgorithmParameterException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /**
+ * Method engineInitSign
+ *
+ * @param secretKey
+ * @param secureRandom
+ * @throws XMLSignatureException
+ */
+ protected void engineInitSign(Key secretKey, SecureRandom secureRandom)
+ throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
+ }
- /**
- * Method engineInitSign
- *
- * @param secretKey
- * @param secureRandom
- * @throws XMLSignatureException
- */
- protected void engineInitSign(Key secretKey, SecureRandom secureRandom)
- throws XMLSignatureException {
- throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
- }
-
- /**
- * Proxy method for {@link java.security.Signature#update(byte[])}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param input
- * @throws XMLSignatureException
- */
- protected void engineUpdate(byte[] input) throws XMLSignatureException {
+ /**
+ * 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.update(input);
- } catch (IllegalStateException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /**
+ * Proxy method for {@link java.security.Signature#update(byte)}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param input
+ * @throws XMLSignatureException
+ */
+ protected void engineUpdate(byte input) throws XMLSignatureException {
+ try {
+ this.macAlgorithm.update(input);
+ } catch (IllegalStateException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- /**
- * Proxy method for {@link java.security.Signature#update(byte)}
- * which is executed on the internal {@link java.security.Signature} object.
- *
- * @param input
- * @throws XMLSignatureException
- */
- protected void engineUpdate(byte input) throws XMLSignatureException {
-
- try {
- this._macAlgorithm.update(input);
- } catch (IllegalStateException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /**
+ * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
+ * which is executed on the internal {@link java.security.Signature} object.
+ *
+ * @param buf
+ * @param offset
+ * @param len
+ * @throws XMLSignatureException
+ */
+ protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
+ try {
+ this.macAlgorithm.update(buf, offset, len);
+ } catch (IllegalStateException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- /**
- * 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 {
+ /**
+ * Method engineGetJCEAlgorithmString
+ * @inheritDoc
+ *
+ */
+ protected String engineGetJCEAlgorithmString() {
+ return this.macAlgorithm.getAlgorithm();
+ }
- try {
- this._macAlgorithm.update(buf, offset, len);
- } catch (IllegalStateException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
-
- /**
- * Method engineGetJCEAlgorithmString
- * @inheritDoc
- *
- */
- protected String engineGetJCEAlgorithmString() {
-
- log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
-
- return this._macAlgorithm.getAlgorithm();
- }
+ /**
+ * Method engineGetJCEAlgorithmString
+ *
+ * @inheritDoc
+ */
+ protected String engineGetJCEProviderName() {
+ return this.macAlgorithm.getProvider().getName();
+ }
- /**
- * Method engineGetJCEAlgorithmString
- *
- * @inheritDoc
- */
- protected String engineGetJCEProviderName() {
- return this._macAlgorithm.getProvider().getName();
- }
+ /**
+ * Method engineSetHMACOutputLength
+ *
+ * @param HMACOutputLength
+ */
+ protected void engineSetHMACOutputLength(int HMACOutputLength) {
+ this.HMACOutputLength = HMACOutputLength;
+ this.HMACOutputLengthSet = true;
+ }
- /**
- * Method engineSetHMACOutputLength
- *
- * @param HMACOutputLength
- */
- protected void engineSetHMACOutputLength(int HMACOutputLength) {
- this._HMACOutputLength = HMACOutputLength;
- this._HMACOutputLengthSet = true;
- }
+ /**
+ * Method engineGetContextFromElement
+ *
+ * @param element
+ */
+ protected void engineGetContextFromElement(Element element) {
+ super.engineGetContextFromElement(element);
- /**
- * Method engineGetContextFromElement
- *
- * @param element
- */
- protected void engineGetContextFromElement(Element element) {
+ if (element == null) {
+ throw new IllegalArgumentException("element null");
+ }
- super.engineGetContextFromElement(element);
+ Text hmaclength =
+ XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0);
- if (element == null) {
- throw new IllegalArgumentException("element null");
- }
-
- Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(),
- Constants._TAG_HMACOUTPUTLENGTH,0);
+ if (hmaclength != null) {
+ this.HMACOutputLength = Integer.parseInt(hmaclength.getData());
+ this.HMACOutputLengthSet = true;
+ }
+ }
- if (hmaclength != null) {
- this._HMACOutputLength = Integer.parseInt(hmaclength.getData());
- this._HMACOutputLengthSet = true;
- }
-
- }
+ /**
+ * Method engineAddContextToElement
+ *
+ * @param element
+ */
+ public void engineAddContextToElement(Element element) {
+ if (element == null) {
+ throw new IllegalArgumentException("null element");
+ }
- /**
- * Method engineAddContextToElement
- *
- * @param element
- */
- public void engineAddContextToElement(Element element) {
-
- if (element == null) {
- throw new IllegalArgumentException("null element");
- }
+ if (this.HMACOutputLengthSet) {
+ Document doc = element.getOwnerDocument();
+ Element HMElem =
+ XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
+ Text HMText =
+ doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString());
- if (this._HMACOutputLengthSet) {
- Document doc = element.getOwnerDocument();
- Element HMElem = XMLUtils.createElementInSignatureSpace(doc,
- Constants._TAG_HMACOUTPUTLENGTH);
- Text HMText =
- doc.createTextNode(new Integer(this._HMACOutputLength).toString());
+ HMElem.appendChild(HMText);
+ XMLUtils.addReturnToElement(element);
+ element.appendChild(HMElem);
+ XMLUtils.addReturnToElement(element);
+ }
+ }
- HMElem.appendChild(HMText);
- XMLUtils.addReturnToElement(element);
- element.appendChild(HMElem);
- XMLUtils.addReturnToElement(element);
- }
- }
+ /**
+ * Class IntegrityHmacSHA1
+ */
+ public static class IntegrityHmacSHA1 extends IntegrityHmac {
- /**
- * Class IntegrityHmacSHA1
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- public static class IntegrityHmacSHA1 extends IntegrityHmac {
+ /**
+ * Constructor IntegrityHmacSHA1
+ *
+ * @throws XMLSignatureException
+ */
+ public IntegrityHmacSHA1() throws XMLSignatureException {
+ super();
+ }
- /**
- * Constructor IntegrityHmacSHA1
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmacSHA1() 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_SHA1;
- }
+ int getDigestLength() {
+ return 160;
+ }
+ }
- int getDigestLength() {
- return 160;
- }
- }
+ /**
+ * Class IntegrityHmacSHA256
+ */
+ public static class IntegrityHmacSHA256 extends IntegrityHmac {
- /**
- * Class IntegrityHmacSHA256
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- public static class IntegrityHmacSHA256 extends IntegrityHmac {
+ /**
+ * Constructor IntegrityHmacSHA256
+ *
+ * @throws XMLSignatureException
+ */
+ public IntegrityHmacSHA256() throws XMLSignatureException {
+ super();
+ }
- /**
- * Constructor IntegrityHmacSHA256
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmacSHA256() throws XMLSignatureException {
- super();
- }
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
+ }
+
+ int getDigestLength() {
+ return 256;
+ }
+ }
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- public String engineGetURI() {
- return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
- }
+ /**
+ * Class IntegrityHmacSHA384
+ */
+ public static class IntegrityHmacSHA384 extends IntegrityHmac {
- 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();
+ }
- /**
- * Constructor IntegrityHmacSHA384
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmacSHA384() throws XMLSignatureException {
- super();
- }
+ /**
+ * Method engineGetURI
+ * @inheritDoc
+ *
+ */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
+ }
- /**
- * Method engineGetURI
- * @inheritDoc
- *
- */
- public String engineGetURI() {
- return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
- }
+ int getDigestLength() {
+ return 384;
+ }
+ }
- int getDigestLength() {
- return 384;
- }
- }
+ /**
+ * Class IntegrityHmacSHA512
+ */
+ public static class IntegrityHmacSHA512 extends IntegrityHmac {
- /**
- * Class IntegrityHmacSHA512
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- public static class IntegrityHmacSHA512 extends IntegrityHmac {
+ /**
+ * Constructor IntegrityHmacSHA512
+ *
+ * @throws XMLSignatureException
+ */
+ public IntegrityHmacSHA512() throws XMLSignatureException {
+ super();
+ }
- /**
- * Constructor IntegrityHmacSHA512
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmacSHA512() throws XMLSignatureException {
- super();
- }
+ /**
+ * Method engineGetURI
+ * @inheritDoc
+ *
+ */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
+ }
- /**
- * Method engineGetURI
- * @inheritDoc
- *
- */
- public String engineGetURI() {
- return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
- }
+ int getDigestLength() {
+ return 512;
+ }
+ }
- int getDigestLength() {
- return 512;
- }
- }
+ /**
+ * Class IntegrityHmacRIPEMD160
+ */
+ public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
- /**
- * Class IntegrityHmacRIPEMD160
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
+ /**
+ * Constructor IntegrityHmacRIPEMD160
+ *
+ * @throws XMLSignatureException
+ */
+ public IntegrityHmacRIPEMD160() throws XMLSignatureException {
+ super();
+ }
- /**
- * Constructor IntegrityHmacRIPEMD160
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmacRIPEMD160() throws XMLSignatureException {
- super();
- }
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
+ }
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- public String engineGetURI() {
- return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
- }
-
- int getDigestLength() {
- return 160;
- }
- }
+ int getDigestLength() {
+ return 160;
+ }
+ }
- /**
- * Class IntegrityHmacMD5
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- public static class IntegrityHmacMD5 extends IntegrityHmac {
+ /**
+ * Class IntegrityHmacMD5
+ */
+ public static class IntegrityHmacMD5 extends IntegrityHmac {
+
+ /**
+ * Constructor IntegrityHmacMD5
+ *
+ * @throws XMLSignatureException
+ */
+ public IntegrityHmacMD5() throws XMLSignatureException {
+ super();
+ }
- /**
- * Constructor IntegrityHmacMD5
- *
- * @throws XMLSignatureException
- */
- public IntegrityHmacMD5() throws XMLSignatureException {
- super();
- }
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
+ }
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- public String engineGetURI() {
- return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
- }
-
- int getDigestLength() {
- return 128;
- }
- }
+ int getDigestLength() {
+ return 128;
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2007 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
@@ -36,22 +38,17 @@
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
-/**
- *
- * @author $Author: mullan $
- */
public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger
- (SignatureBaseRSA.class.getName());
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName());
/** @inheritDoc */
public abstract String engineGetURI();
/** Field algorithm */
- private java.security.Signature _signatureAlgorithm = null;
+ private java.security.Signature signatureAlgorithm = null;
/**
* Constructor SignatureRSA
@@ -59,17 +56,17 @@
* @throws XMLSignatureException
*/
public SignatureBaseRSA() throws XMLSignatureException {
-
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
- if (log.isLoggable(java.util.logging.Level.FINE))
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID);
- String provider=JCEMapper.getProviderId();
+ }
+ String provider = JCEMapper.getProviderId();
try {
- if (provider==null) {
- this._signatureAlgorithm = Signature.getInstance(algorithmID);
+ if (provider == null) {
+ this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else {
- this._signatureAlgorithm = Signature.getInstance(algorithmID,provider);
+ this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
}
} catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
@@ -85,20 +82,17 @@
/** @inheritDoc */
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
-
try {
- this._signatureAlgorithm.setParameter(params);
+ this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
- protected boolean engineVerify(byte[] signature)
- throws XMLSignatureException {
-
+ protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
try {
- return this._signatureAlgorithm.verify(signature);
+ return this.signatureAlgorithm.verify(signature);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -106,32 +100,29 @@
/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
-
if (!(publicKey instanceof PublicKey)) {
String supplied = publicKey.getClass().getName();
String needed = PublicKey.class.getName();
Object exArgs[] = { supplied, needed };
- throw new XMLSignatureException
- ("algorithms.WrongKeyForThisOperation", exArgs);
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
- this._signatureAlgorithm.initVerify((PublicKey) publicKey);
+ this.signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555
- Signature sig = this._signatureAlgorithm;
+ Signature sig = this.signatureAlgorithm;
try {
- this._signatureAlgorithm = Signature.getInstance
- (_signatureAlgorithm.getAlgorithm());
+ this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
} catch (Exception e) {
// this shouldn't occur, but if it does, restore previous
// Signature
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
}
- this._signatureAlgorithm = sig;
+ this.signatureAlgorithm = sig;
}
throw new XMLSignatureException("empty", ex);
}
@@ -140,7 +131,7 @@
/** @inheritDoc */
protected byte[] engineSign() throws XMLSignatureException {
try {
- return this._signatureAlgorithm.sign();
+ return this.signatureAlgorithm.sign();
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -149,19 +140,16 @@
/** @inheritDoc */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException {
-
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
- throw new XMLSignatureException
- ("algorithms.WrongKeyForThisOperation", exArgs);
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
- this._signatureAlgorithm.initSign
- ((PrivateKey) privateKey, secureRandom);
+ this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -169,18 +157,16 @@
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
- throw new XMLSignatureException
- ("algorithms.WrongKeyForThisOperation", exArgs);
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
- this._signatureAlgorithm.initSign((PrivateKey) privateKey);
+ this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -189,7 +175,7 @@
/** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
- this._signatureAlgorithm.update(input);
+ this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -198,17 +184,16 @@
/** @inheritDoc */
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
- this._signatureAlgorithm.update(input);
+ this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
- protected void engineUpdate(byte buf[], int offset, int len)
- throws XMLSignatureException {
+ protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
try {
- this._signatureAlgorithm.update(buf, offset, len);
+ this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -216,34 +201,29 @@
/** @inheritDoc */
protected String engineGetJCEAlgorithmString() {
- return this._signatureAlgorithm.getAlgorithm();
+ return this.signatureAlgorithm.getAlgorithm();
}
/** @inheritDoc */
protected String engineGetJCEProviderName() {
- return this._signatureAlgorithm.getProvider().getName();
+ return this.signatureAlgorithm.getProvider().getName();
}
/** @inheritDoc */
protected void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException {
- throw new XMLSignatureException
- ("algorithms.HMACOutputLengthOnlyForHMAC");
+ throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/** @inheritDoc */
protected void engineInitSign(
- Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
- throws XMLSignatureException {
- throw new XMLSignatureException(
- "algorithms.CannotUseAlgorithmParameterSpecOnRSA");
+ Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+ ) throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
}
/**
* Class SignatureRSASHA1
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public static class SignatureRSASHA1 extends SignatureBaseRSA {
@@ -264,9 +244,6 @@
/**
* Class SignatureRSASHA256
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public static class SignatureRSASHA256 extends SignatureBaseRSA {
@@ -287,9 +264,6 @@
/**
* Class SignatureRSASHA384
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public static class SignatureRSASHA384 extends SignatureBaseRSA {
@@ -310,9 +284,6 @@
/**
* Class SignatureRSASHA512
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public static class SignatureRSASHA512 extends SignatureBaseRSA {
@@ -333,9 +304,6 @@
/**
* Class SignatureRSARIPEMD160
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public static class SignatureRSARIPEMD160 extends SignatureBaseRSA {
@@ -356,9 +324,6 @@
/**
* Class SignatureRSAMD5
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public static class SignatureRSAMD5 extends SignatureBaseRSA {
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
@@ -37,21 +39,17 @@
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
-/**
- *
- * @author $Author: mullan $
- */
public class SignatureDSA extends SignatureAlgorithmSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureDSA.class.getName());
- /** Field _URI */
- public static final String _URI = Constants.SignatureSpecNS + "dsa-sha1";
+ /** Field URI */
+ public static final String URI = Constants.SignatureSpecNS + "dsa-sha1";
/** Field algorithm */
- private java.security.Signature _signatureAlgorithm = null;
+ private java.security.Signature signatureAlgorithm = null;
/**
* Method engineGetURI
@@ -59,7 +57,7 @@
* @inheritDoc
*/
protected String engineGetURI() {
- return SignatureDSA._URI;
+ return SignatureDSA.URI;
}
/**
@@ -68,17 +66,17 @@
* @throws XMLSignatureException
*/
public SignatureDSA() throws XMLSignatureException {
-
- String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA._URI);
- if (log.isLoggable(java.util.logging.Level.FINE))
+ String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
+ }
String provider = JCEMapper.getProviderId();
try {
if (provider == null) {
- this._signatureAlgorithm = Signature.getInstance(algorithmID);
+ this.signatureAlgorithm = Signature.getInstance(algorithmID);
} else {
- this._signatureAlgorithm =
+ this.signatureAlgorithm =
Signature.getInstance(algorithmID, provider);
}
} catch (java.security.NoSuchAlgorithmException ex) {
@@ -95,9 +93,8 @@
*/
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
-
try {
- this._signatureAlgorithm.setParameter(params);
+ this.signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -107,15 +104,15 @@
* @inheritDoc
*/
protected boolean engineVerify(byte[] signature)
- throws XMLSignatureException {
-
+ throws XMLSignatureException {
try {
- if (log.isLoggable(java.util.logging.Level.FINE))
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature));
+ }
byte[] jcebytes = SignatureDSA.convertXMLDSIGtoASN1(signature);
- return this._signatureAlgorithm.verify(jcebytes);
+ return this.signatureAlgorithm.verify(jcebytes);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
} catch (IOException ex) {
@@ -127,32 +124,29 @@
* @inheritDoc
*/
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
-
if (!(publicKey instanceof PublicKey)) {
String supplied = publicKey.getClass().getName();
String needed = PublicKey.class.getName();
Object exArgs[] = { supplied, needed };
- throw new XMLSignatureException
- ("algorithms.WrongKeyForThisOperation", exArgs);
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
- this._signatureAlgorithm.initVerify((PublicKey) publicKey);
+ this.signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555
- Signature sig = this._signatureAlgorithm;
+ Signature sig = this.signatureAlgorithm;
try {
- this._signatureAlgorithm = Signature.getInstance
- (_signatureAlgorithm.getAlgorithm());
+ this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
} catch (Exception e) {
// this shouldn't occur, but if it does, restore previous
// Signature
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
}
- this._signatureAlgorithm = sig;
+ this.signatureAlgorithm = sig;
}
throw new XMLSignatureException("empty", ex);
}
@@ -162,9 +156,8 @@
* @inheritDoc
*/
protected byte[] engineSign() throws XMLSignatureException {
-
try {
- byte jcebytes[] = this._signatureAlgorithm.sign();
+ byte jcebytes[] = this.signatureAlgorithm.sign();
return SignatureDSA.convertASN1toXMLDSIG(jcebytes);
} catch (IOException ex) {
@@ -178,20 +171,17 @@
* @inheritDoc
*/
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
- throws XMLSignatureException {
-
+ throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
- throw new XMLSignatureException
- ("algorithms.WrongKeyForThisOperation", exArgs);
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
- this._signatureAlgorithm.initSign((PrivateKey) privateKey,
- secureRandom);
+ this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -201,18 +191,16 @@
* @inheritDoc
*/
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
-
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
- throw new XMLSignatureException
- ("algorithms.WrongKeyForThisOperation", exArgs);
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
- this._signatureAlgorithm.initSign((PrivateKey) privateKey);
+ this.signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -223,7 +211,7 @@
*/
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
- this._signatureAlgorithm.update(input);
+ this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -234,7 +222,7 @@
*/
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
- this._signatureAlgorithm.update(input);
+ this.signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -243,10 +231,9 @@
/**
* @inheritDoc
*/
- protected void engineUpdate(byte buf[], int offset, int len)
- throws XMLSignatureException {
+ protected void engineUpdate(byte buf[], int offset, int len) throws XMLSignatureException {
try {
- this._signatureAlgorithm.update(buf, offset, len);
+ this.signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
@@ -258,7 +245,7 @@
* @inheritDoc
*/
protected String engineGetJCEAlgorithmString() {
- return this._signatureAlgorithm.getAlgorithm();
+ return this.signatureAlgorithm.getAlgorithm();
}
/**
@@ -267,7 +254,7 @@
* @inheritDoc
*/
protected String engineGetJCEProviderName() {
- return this._signatureAlgorithm.getProvider().getName();
+ return this.signatureAlgorithm.getProvider().getName();
}
/**
@@ -282,8 +269,7 @@
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
- private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
- throws IOException {
+ private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
byte rLength = asn1Bytes[3];
int i;
@@ -294,19 +280,18 @@
int j;
for (j = sLength;
- (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
+ (j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
- || (asn1Bytes[2] != 2) || (i > 20)
- || (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
+ || (asn1Bytes[2] != 2) || (i > 20)
+ || (asn1Bytes[4 + rLength] != 2) || (j > 20)) {
throw new IOException("Invalid ASN.1 format of DSA signature");
}
byte xmldsigBytes[] = new byte[40];
- System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i,
- i);
+ System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 20 - i, i);
System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
- 40 - j, j);
+ 40 - j, j);
return xmldsigBytes;
}
@@ -323,8 +308,7 @@
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
- private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
- throws IOException {
+ private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
if (xmldsigBytes.length != 40) {
throw new IOException("Invalid XMLDSIG format of DSA signature");
@@ -337,7 +321,7 @@
int j = i;
if (xmldsigBytes[20 - i] < 0) {
- j += 1;
+ j += 1;
}
int k;
@@ -373,10 +357,8 @@
* @param HMACOutputLength
* @throws XMLSignatureException
*/
- protected void engineSetHMACOutputLength(int HMACOutputLength)
- throws XMLSignatureException {
- throw new XMLSignatureException(
- "algorithms.HMACOutputLengthOnlyForHMAC");
+ protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/**
@@ -387,9 +369,8 @@
* @throws XMLSignatureException
*/
protected void engineInitSign(
- Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
- throws XMLSignatureException {
- throw new XMLSignatureException(
- "algorithms.CannotUseAlgorithmParameterSpecOnDSA");
+ Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+ ) throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnDSA");
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
-
-
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
@@ -40,345 +40,417 @@
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
-
/**
*
- * @author $Author: mullan $
+ * @author $Author: raul $
+ * @author Alex Dupre
*/
public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureECDSA.class.getName());
/** @inheritDoc */
- public abstract String engineGetURI();
+ public abstract String engineGetURI();
- /** Field algorithm */
- private java.security.Signature _signatureAlgorithm = null;
+ /** Field algorithm */
+ private java.security.Signature signatureAlgorithm = null;
- /**
- * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
- *
- * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
- * pairs; the XML Signature requires the core BigInteger values.
- *
- * @param asn1Bytes
- * @return the decode bytes
- *
- * @throws IOException
- * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
- * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
- */
- private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
- throws IOException {
+ /**
+ * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
+ *
+ * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+ * pairs; the XML Signature requires the core BigInteger values.
+ *
+ * @param asn1Bytes
+ * @return the decode bytes
+ *
+ * @throws IOException
+ * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+ * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+ */
+ public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException {
- byte rLength = asn1Bytes[3];
- int i;
-
- 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.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");
+ }
- 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];
+ byte rLength = asn1Bytes[offset + 1];
+ int i;
+
+ for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--);
- System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i,
- i);
- System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
- 48 - j, j);
+ byte sLength = asn1Bytes[offset + 2 + rLength + 1];
+ int j;
+
+ for (j = sLength;
+ (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--);
+
+ int rawLen = Math.max(i, j);
- return xmldsigBytes;
- }
+ if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset
+ || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
+ || asn1Bytes[offset] != 2
+ || asn1Bytes[offset + 2 + rLength] != 2) {
+ throw new IOException("Invalid ASN.1 format of ECDSA signature");
+ }
+ byte xmldsigBytes[] = new byte[2*rawLen];
- /**
- * Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
- *
- * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
- * pairs; the XML Signature requires the core BigInteger values.
- *
- * @param xmldsigBytes
- * @return the encoded ASN.1 bytes
- *
- * @throws IOException
- * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
- * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
- */
- private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
- throws IOException {
+ System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i);
+ System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes,
+ 2*rawLen - j, j);
+
+ return xmldsigBytes;
+ }
- if (xmldsigBytes.length != 48) {
- throw new IOException("Invalid XMLDSIG format of ECDSA signature");
- }
+ /**
+ * Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
+ *
+ * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
+ * pairs; the XML Signature requires the core BigInteger values.
+ *
+ * @param xmldsigBytes
+ * @return the encoded ASN.1 bytes
+ *
+ * @throws IOException
+ * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
+ * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
+ */
+ public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException {
- int i;
-
- for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--);
-
- int j = i;
+ int rawLen = xmldsigBytes.length/2;
- if (xmldsigBytes[24 - i] < 0) {
- j += 1;
- }
+ int i;
+
+ for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--);
- int k;
+ int j = i;
- for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--);
+ if (xmldsigBytes[rawLen - i] < 0) {
+ j += 1;
+ }
- int l = k;
+ int k;
+
+ for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--);
- if (xmldsigBytes[48 - k] < 0) {
- l += 1;
- }
+ int l = k;
- byte asn1Bytes[] = new byte[6 + j + l];
+ if (xmldsigBytes[2*rawLen - k] < 0) {
+ l += 1;
+ }
- 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;
+ 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, 48 - k, asn1Bytes, (6 + j + l) - k, k);
-
- return asn1Bytes;
- }
-
- /**
- * Constructor SignatureRSA
- *
- * @throws XMLSignatureException
- */
- public SignatureECDSA() throws XMLSignatureException {
+ System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i);
- String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
+ offset += j;
+
+ asn1Bytes[offset++] = 2;
+ asn1Bytes[offset++] = (byte) l;
+
+ System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k);
+
+ return asn1Bytes;
+ }
- if (log.isLoggable(java.util.logging.Level.FINE))
- log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
- String provider=JCEMapper.getProviderId();
- try {
- if (provider==null) {
- this._signatureAlgorithm = Signature.getInstance(algorithmID);
- } else {
- this._signatureAlgorithm = Signature.getInstance(algorithmID,provider);
- }
- } catch (java.security.NoSuchAlgorithmException ex) {
- Object[] exArgs = { algorithmID,
- ex.getLocalizedMessage() };
+ /**
+ * Constructor SignatureRSA
+ *
+ * @throws XMLSignatureException
+ */
+ public SignatureECDSA() throws XMLSignatureException {
- throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
- } catch (NoSuchProviderException ex) {
- Object[] exArgs = { algorithmID,
- ex.getLocalizedMessage() };
+ String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
- throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
}
- }
+ String provider = JCEMapper.getProviderId();
+ try {
+ if (provider == null) {
+ this.signatureAlgorithm = Signature.getInstance(algorithmID);
+ } else {
+ this.signatureAlgorithm = Signature.getInstance(algorithmID,provider);
+ }
+ } catch (java.security.NoSuchAlgorithmException ex) {
+ Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
- /** @inheritDoc */
- protected void engineSetParameter(AlgorithmParameterSpec params)
- throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+ } catch (NoSuchProviderException ex) {
+ Object[] exArgs = { algorithmID, ex.getLocalizedMessage() };
- try {
- this._signatureAlgorithm.setParameter(params);
- } catch (InvalidAlgorithmParameterException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
+ }
+ }
- /** @inheritDoc */
- protected boolean engineVerify(byte[] signature)
- throws XMLSignatureException {
-
- 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));
+ /** @inheritDoc */
+ protected void engineSetParameter(AlgorithmParameterSpec params)
+ throws XMLSignatureException {
+ try {
+ this.signatureAlgorithm.setParameter(params);
+ } catch (InvalidAlgorithmParameterException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- return this._signatureAlgorithm.verify(jcebytes);
- } catch (SignatureException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (IOException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /** @inheritDoc */
+ protected boolean engineVerify(byte[] signature) throws XMLSignatureException {
+ try {
+ byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
- /** @inheritDoc */
- protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature));
+ }
- if (!(publicKey instanceof PublicKey)) {
- String supplied = publicKey.getClass().getName();
- String needed = PublicKey.class.getName();
- Object exArgs[] = { supplied, needed };
+ 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 {
- throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
- exArgs);
- }
+ if (!(publicKey instanceof PublicKey)) {
+ String supplied = publicKey.getClass().getName();
+ String needed = PublicKey.class.getName();
+ Object exArgs[] = { supplied, needed };
- try {
- this._signatureAlgorithm.initVerify((PublicKey) publicKey);
- } catch (InvalidKeyException ex) {
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+ }
+
+ try {
+ this.signatureAlgorithm.initVerify((PublicKey) publicKey);
+ } catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555
- Signature sig = this._signatureAlgorithm;
+ Signature sig = this.signatureAlgorithm;
try {
- this._signatureAlgorithm = Signature.getInstance
- (_signatureAlgorithm.getAlgorithm());
+ this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
} catch (Exception e) {
// this shouldn't occur, but if it does, restore previous
// Signature
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
}
- this._signatureAlgorithm = sig;
+ this.signatureAlgorithm = sig;
}
throw new XMLSignatureException("empty", ex);
- }
- }
+ }
+ }
+
+ /** @inheritDoc */
+ protected byte[] engineSign() throws XMLSignatureException {
+ try {
+ byte jcebytes[] = this.signatureAlgorithm.sign();
- /** @inheritDoc */
- protected byte[] engineSign() throws XMLSignatureException {
-
- try {
- byte jcebytes[] = this._signatureAlgorithm.sign();
+ return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
+ } catch (SignatureException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (IOException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
- } catch (SignatureException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (IOException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /** @inheritDoc */
+ protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
+ throws XMLSignatureException {
+ if (!(privateKey instanceof PrivateKey)) {
+ String supplied = privateKey.getClass().getName();
+ String needed = PrivateKey.class.getName();
+ Object exArgs[] = { supplied, needed };
+
+ throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
+ }
- /** @inheritDoc */
- protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
- throws XMLSignatureException {
+ try {
+ this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom);
+ } 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 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,
- secureRandom);
- } catch (InvalidKeyException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ try {
+ this.signatureAlgorithm.initSign((PrivateKey) privateKey);
+ } catch (InvalidKeyException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- /** @inheritDoc */
- protected void engineInitSign(Key privateKey) throws XMLSignatureException {
+ /** @inheritDoc */
+ protected void engineUpdate(byte[] input) throws XMLSignatureException {
+ try {
+ this.signatureAlgorithm.update(input);
+ } catch (SignatureException 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 buf[], int offset, int len) throws XMLSignatureException {
+ try {
+ this.signatureAlgorithm.update(buf, offset, len);
+ } catch (SignatureException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- try {
- this._signatureAlgorithm.initSign((PrivateKey) privateKey);
- } catch (InvalidKeyException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /** @inheritDoc */
+ protected String engineGetJCEAlgorithmString() {
+ return this.signatureAlgorithm.getAlgorithm();
+ }
- /** @inheritDoc */
- protected void engineUpdate(byte[] input) throws XMLSignatureException {
+ /** @inheritDoc */
+ protected String engineGetJCEProviderName() {
+ return this.signatureAlgorithm.getProvider().getName();
+ }
- try {
- this._signatureAlgorithm.update(input);
- } catch (SignatureException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ /** @inheritDoc */
+ protected void engineSetHMACOutputLength(int HMACOutputLength)
+ throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
+ }
- /** @inheritDoc */
- protected void engineUpdate(byte input) throws XMLSignatureException {
+ /** @inheritDoc */
+ protected void engineInitSign(
+ Key signingKey, AlgorithmParameterSpec algorithmParameterSpec
+ ) throws XMLSignatureException {
+ throw new XMLSignatureException("algorithms.CannotUseAlgorithmParameterSpecOnRSA");
+ }
- try {
- this._signatureAlgorithm.update(input);
- } catch (SignatureException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
-
- /** @inheritDoc */
- protected void engineUpdate(byte buf[], int offset, int len)
- throws XMLSignatureException {
+ /**
+ * 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 {
+
+ /**
+ * Constructor SignatureRSASHA384
+ *
+ * @throws XMLSignatureException
+ */
+ public SignatureECDSASHA384() throws XMLSignatureException {
+ super();
+ }
- /**
- * Class SignatureRSASHA1
- *
- * @author $Author: mullan $
- * @version $Revision: 1.2 $
- */
- public static class SignatureECDSASHA1 extends SignatureECDSA {
+ /** @inheritDoc */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384;
+ }
+ }
+
+ /**
+ * Class SignatureRSASHA512
+ *
+ * @author Alex Dupre
+ */
+ public static class SignatureECDSASHA512 extends SignatureECDSA {
- /**
- * Constructor SignatureRSASHA1
- *
- * @throws XMLSignatureException
- */
- public SignatureECDSASHA1() throws XMLSignatureException {
- super();
- }
+ /**
+ * Constructor SignatureRSASHA512
+ *
+ * @throws XMLSignatureException
+ */
+ public SignatureECDSASHA512() throws XMLSignatureException {
+ super();
+ }
- /** @inheritDoc */
- public String engineGetURI() {
- return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
- }
- }
+ /** @inheritDoc */
+ public String engineGetURI() {
+ return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512;
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,29 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
-
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
/**
* Class CanonicalizationException
*
@@ -32,57 +31,58 @@
*/
public class CanonicalizationException extends XMLSecurityException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
- /**
- * Constructor CanonicalizationException
- *
- */
- public CanonicalizationException() {
- super();
- }
+ /**
+ * Constructor CanonicalizationException
+ *
+ */
+ public CanonicalizationException() {
+ super();
+ }
- /**
- * Constructor CanonicalizationException
- *
- * @param _msgID
- */
- public CanonicalizationException(String _msgID) {
- super(_msgID);
- }
+ /**
+ * Constructor CanonicalizationException
+ *
+ * @param msgID
+ */
+ public CanonicalizationException(String msgID) {
+ super(msgID);
+ }
- /**
- * Constructor CanonicalizationException
- *
- * @param _msgID
- * @param exArgs
- */
- public CanonicalizationException(String _msgID, Object exArgs[]) {
- super(_msgID, exArgs);
- }
+ /**
+ * Constructor CanonicalizationException
+ *
+ * @param msgID
+ * @param exArgs
+ */
+ public CanonicalizationException(String msgID, Object exArgs[]) {
+ super(msgID, exArgs);
+ }
- /**
- * Constructor CanonicalizationException
- *
- * @param _msgID
- * @param _originalException
- */
- public CanonicalizationException(String _msgID, Exception _originalException) {
- super(_msgID, _originalException);
- }
+ /**
+ * Constructor CanonicalizationException
+ *
+ * @param msgID
+ * @param originalException
+ */
+ public CanonicalizationException(String msgID, Exception originalException) {
+ super(msgID, originalException);
+ }
- /**
- * Constructor CanonicalizationException
- *
- * @param _msgID
- * @param exArgs
- * @param _originalException
- */
- public CanonicalizationException(String _msgID, Object exArgs[],
- Exception _originalException) {
- super(_msgID, exArgs, _originalException);
- }
+ /**
+ * Constructor CanonicalizationException
+ *
+ * @param msgID
+ * @param exArgs
+ * @param originalException
+ */
+ public CanonicalizationException(
+ String msgID, Object exArgs[], Exception originalException
+ ) {
+ super(msgID, exArgs, originalException);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java Fri Jul 05 14:37:41 2013 -0700
@@ -39,6 +39,7 @@
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315ExclWithComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315WithComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@@ -91,6 +92,11 @@
*/
public static final String ALGO_ID_C14N11_WITH_COMMENTS =
ALGO_ID_C14N11_OMIT_COMMENTS + "#WithComments";
+ /**
+ * Non-standard algorithm to serialize the physical representation for XML Encryption
+ */
+ public static final String ALGO_ID_C14N_PHYSICAL =
+ "http://santuario.apache.org/c14n/physical";
private static Map<String, Class<? extends CanonicalizerSpi>> canonicalizerHash =
new ConcurrentHashMap<String, Class<? extends CanonicalizerSpi>>();
@@ -202,6 +208,10 @@
Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS,
Canonicalizer11_WithComments.class
);
+ canonicalizerHash.put(
+ Canonicalizer.ALGO_ID_C14N_PHYSICAL,
+ CanonicalizerPhysical.class
+ );
}
/**
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
-
-
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.util.Set;
@@ -29,7 +29,6 @@
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.xpath.XPath;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
@@ -37,166 +36,134 @@
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
-
/**
- * Base class which all Caninicalization algorithms extend.
+ * Base class which all Canonicalization algorithms extend.
*
- * $todo$ cange JavaDoc
* @author Christian Geuer-Pollmann
*/
public abstract class CanonicalizerSpi {
- /**
- * Method canonicalize
- *
- *
- * @param inputBytes
- * @return the c14n bytes.
- *
- *
- * @throws CanonicalizationException
- * @throws java.io.IOException
- * @throws javax.xml.parsers.ParserConfigurationException
- * @throws org.xml.sax.SAXException
- *
- */
- public byte[] engineCanonicalize(byte[] inputBytes)
- throws javax.xml.parsers.ParserConfigurationException,
- java.io.IOException, org.xml.sax.SAXException,
- CanonicalizationException {
+ /** Reset the writer after a c14n */
+ protected boolean reset = false;
- java.io.ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);
- InputSource in = new InputSource(bais);
- DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
- dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+ /**
+ * Method canonicalize
+ *
+ * @param inputBytes
+ * @return the c14n bytes.
+ *
+ * @throws CanonicalizationException
+ * @throws java.io.IOException
+ * @throws javax.xml.parsers.ParserConfigurationException
+ * @throws org.xml.sax.SAXException
+ */
+ public byte[] engineCanonicalize(byte[] inputBytes)
+ throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
+ org.xml.sax.SAXException, CanonicalizationException {
- // needs to validate for ID attribute nomalization
- dfactory.setNamespaceAware(true);
+ java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
+ InputSource in = new InputSource(bais);
+ DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
+ dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
- DocumentBuilder db = dfactory.newDocumentBuilder();
+ // needs to validate for ID attribute normalization
+ dfactory.setNamespaceAware(true);
+
+ DocumentBuilder db = dfactory.newDocumentBuilder();
- /*
- * for some of the test vectors from the specification,
- * there has to be a validatin parser for ID attributes, default
- * attribute values, NMTOKENS, etc.
- * Unfortunaltely, the test vectors do use different DTDs or
- * even no DTD. So Xerces 1.3.1 fires many warnings about using
- * ErrorHandlers.
- *
- * Text from the spec:
- *
- * The input octet stream MUST contain a well-formed XML document,
- * but the input need not be validated. However, the attribute
- * value normalization and entity reference resolution MUST be
- * performed in accordance with the behaviors of a validating
- * XML processor. As well, nodes for default attributes (declared
- * in the ATTLIST with an AttValue but not specified) are created
- * in each element. Thus, the declarations in the document type
- * declaration are used to help create the canonical form, even
- * though the document type declaration is not retained in the
- * canonical form.
- *
- */
+ Document document = db.parse(in);
+ return this.engineCanonicalizeSubTree(document);
+ }
- // ErrorHandler eh = new C14NErrorHandler();
- // db.setErrorHandler(eh);
- Document document = db.parse(in);
- byte result[] = this.engineCanonicalizeSubTree(document);
- return result;
- }
+ /**
+ * Method engineCanonicalizeXPathNodeSet
+ *
+ * @param xpathNodeSet
+ * @return the c14n bytes
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet)
+ throws CanonicalizationException {
+ return this.engineCanonicalizeXPathNodeSet(
+ XMLUtils.convertNodelistToSet(xpathNodeSet)
+ );
+ }
- /**
- * Method engineCanonicalizeXPathNodeSet
- *
- * @param xpathNodeSet
- * @return the c14n bytes
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet)
- throws CanonicalizationException {
-
- return this
- .engineCanonicalizeXPathNodeSet(XMLUtils
- .convertNodelistToSet(xpathNodeSet));
- }
+ /**
+ * Method engineCanonicalizeXPathNodeSet
+ *
+ * @param xpathNodeSet
+ * @param inclusiveNamespaces
+ * @return the c14n bytes
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces)
+ throws CanonicalizationException {
+ return this.engineCanonicalizeXPathNodeSet(
+ XMLUtils.convertNodelistToSet(xpathNodeSet), inclusiveNamespaces
+ );
+ }
- /**
- * Method engineCanonicalizeXPathNodeSet
- *
- * @param xpathNodeSet
- * @param inclusiveNamespaces
- * @return the c14n bytes
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeXPathNodeSet(NodeList xpathNodeSet, String inclusiveNamespaces)
- throws CanonicalizationException {
-
- return this
- .engineCanonicalizeXPathNodeSet(XMLUtils
- .convertNodelistToSet(xpathNodeSet), inclusiveNamespaces);
- }
+ /**
+ * Returns the URI of this engine.
+ * @return the URI
+ */
+ public abstract String engineGetURI();
- //J-
- /** Returns the URI of this engine.
- * @return the URI
- */
- public abstract String engineGetURI();
+ /**
+ * Returns true if comments are included
+ * @return true if comments are included
+ */
+ public abstract boolean engineGetIncludeComments();
- /** Returns the URI if include comments
- * @return true if include.
- */
- public abstract boolean engineGetIncludeComments();
-
- /**
- * C14n a nodeset
- *
- * @param xpathNodeSet
- * @return the c14n bytes
- * @throws CanonicalizationException
- */
- public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
- throws CanonicalizationException;
+ /**
+ * C14n a nodeset
+ *
+ * @param xpathNodeSet
+ * @return the c14n bytes
+ * @throws CanonicalizationException
+ */
+ public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
+ throws CanonicalizationException;
- /**
- * C14n a nodeset
- *
- * @param xpathNodeSet
- * @param inclusiveNamespaces
- * @return the c14n bytes
- * @throws CanonicalizationException
- */
- public abstract byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
- throws CanonicalizationException;
-
- /**
- * C14n a node tree.
- *
- * @param rootNode
- * @return the c14n bytes
- * @throws CanonicalizationException
- */
- public abstract byte[] engineCanonicalizeSubTree(Node rootNode)
- throws CanonicalizationException;
+ /**
+ * C14n a nodeset
+ *
+ * @param xpathNodeSet
+ * @param inclusiveNamespaces
+ * @return the c14n bytes
+ * @throws CanonicalizationException
+ */
+ public abstract byte[] engineCanonicalizeXPathNodeSet(
+ Set<Node> xpathNodeSet, String inclusiveNamespaces
+ ) throws CanonicalizationException;
- /**
- * C14n a node tree.
- *
- * @param rootNode
- * @param inclusiveNamespaces
- * @return the c14n bytes
- * @throws CanonicalizationException
- */
- public abstract byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
- throws CanonicalizationException;
+ /**
+ * C14n a node tree.
+ *
+ * @param rootNode
+ * @return the c14n bytes
+ * @throws CanonicalizationException
+ */
+ public abstract byte[] engineCanonicalizeSubTree(Node rootNode)
+ throws CanonicalizationException;
- /**
- * Sets the writter where the cannocalization ends. ByteArrayOutputStream if
- * none is setted.
- * @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;
- /** Reset the writter after a c14n */
- protected boolean reset=false;
- //J+
+ /**
+ * Sets the writer where the canonicalization ends. ByteArrayOutputStream if
+ * none is set.
+ * @param os
+ */
+ public abstract void setWriter(OutputStream os);
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,87 +2,82 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n;
-
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
-/**
- *
- * @author Christian Geuer-Pollmann
- */
public class InvalidCanonicalizerException extends XMLSecurityException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
- /**
- * Constructor InvalidCanonicalizerException
- *
- */
- public InvalidCanonicalizerException() {
- super();
- }
+ /**
+ * Constructor InvalidCanonicalizerException
+ *
+ */
+ public InvalidCanonicalizerException() {
+ super();
+ }
- /**
- * Constructor InvalidCanonicalizerException
- *
- * @param _msgID
- */
- public InvalidCanonicalizerException(String _msgID) {
- super(_msgID);
- }
+ /**
+ * Constructor InvalidCanonicalizerException
+ *
+ * @param msgID
+ */
+ public InvalidCanonicalizerException(String msgID) {
+ super(msgID);
+ }
- /**
- * Constructor InvalidCanonicalizerException
- *
- * @param _msgID
- * @param exArgs
- */
- public InvalidCanonicalizerException(String _msgID, Object exArgs[]) {
- super(_msgID, exArgs);
- }
+ /**
+ * Constructor InvalidCanonicalizerException
+ *
+ * @param msgID
+ * @param exArgs
+ */
+ public InvalidCanonicalizerException(String msgID, Object exArgs[]) {
+ super(msgID, exArgs);
+ }
- /**
- * Constructor InvalidCanonicalizerException
- *
- * @param _msgID
- * @param _originalException
- */
- public InvalidCanonicalizerException(String _msgID,
- Exception _originalException) {
- super(_msgID, _originalException);
- }
+ /**
+ * Constructor InvalidCanonicalizerException
+ *
+ * @param msgID
+ * @param originalException
+ */
+ public InvalidCanonicalizerException(String msgID, Exception originalException) {
+ super(msgID, originalException);
+ }
- /**
- * Constructor InvalidCanonicalizerException
- *
- * @param _msgID
- * @param exArgs
- * @param _originalException
- */
- public InvalidCanonicalizerException(String _msgID, Object exArgs[],
- Exception _originalException) {
- super(_msgID, exArgs, _originalException);
- }
+ /**
+ * Constructor InvalidCanonicalizerException
+ *
+ * @param msgID
+ * @param exArgs
+ * @param originalException
+ */
+ public InvalidCanonicalizerException(
+ String msgID, Object exArgs[], Exception originalException
+ ) {
+ super(msgID, exArgs, originalException);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.helper;
@@ -43,10 +45,10 @@
*/
public class AttrCompare implements Comparator<Attr>, Serializable {
- private final static long serialVersionUID = -7113259629930576230L;
- private final static int ATTR0_BEFORE_ATTR1 = -1;
- private final static int ATTR1_BEFORE_ATTR0 = 1;
- private final static String XMLNS=Constants.NamespaceSpecNS;
+ private static final long serialVersionUID = -7113259629930576230L;
+ private static final int ATTR0_BEFORE_ATTR1 = -1;
+ private static final int ATTR1_BEFORE_ATTR0 = 1;
+ private static final String XMLNS = Constants.NamespaceSpecNS;
/**
* Compares two attributes based on the C14n specification.
@@ -69,12 +71,11 @@
*
*/
public int compare(Attr attr0, Attr attr1) {
-
String namespaceURI0 = attr0.getNamespaceURI();
String namespaceURI1 = attr1.getNamespaceURI();
- boolean isNamespaceAttr0 = XMLNS==namespaceURI0;
- boolean isNamespaceAttr1 = XMLNS==namespaceURI1;
+ boolean isNamespaceAttr0 = XMLNS.equals(namespaceURI0);
+ boolean isNamespaceAttr1 = XMLNS.equals(namespaceURI1);
if (isNamespaceAttr0) {
if (isNamespaceAttr1) {
@@ -82,11 +83,11 @@
String localname0 = attr0.getLocalName();
String localname1 = attr1.getLocalName();
- if (localname0.equals("xmlns")) {
+ if ("xmlns".equals(localname0)) {
localname0 = "";
}
- if (localname1.equals("xmlns")) {
+ if ("xmlns".equals(localname1)) {
localname1 = "";
}
@@ -94,9 +95,7 @@
}
// attr0 is a namespace, attr1 is not
return ATTR0_BEFORE_ATTR1;
- }
-
- if (isNamespaceAttr1) {
+ } else if (isNamespaceAttr1) {
// attr1 is a namespace, attr0 is not
return ATTR1_BEFORE_ATTR0;
}
@@ -109,9 +108,7 @@
return name0.compareTo(name1);
}
return ATTR0_BEFORE_ATTR1;
- }
-
- if (namespaceURI1 == null) {
+ } else if (namespaceURI1 == null) {
return ATTR1_BEFORE_ATTR0;
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/C14nHelper.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,33 +2,32 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.helper;
-
-
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
-
/**
* Temporary swapped static functions from the normalizer Section
*
@@ -36,129 +35,121 @@
*/
public class C14nHelper {
- /**
- * Constructor C14nHelper
- *
- */
- private C14nHelper() {
-
- // don't allow instantiation
- }
+ /**
+ * Constructor C14nHelper
+ *
+ */
+ private C14nHelper() {
+ // don't allow instantiation
+ }
- /**
- * Method namespaceIsRelative
- *
- * @param namespace
- * @return true if the given namespace is relative.
- */
- public static boolean namespaceIsRelative(Attr namespace) {
- return !namespaceIsAbsolute(namespace);
- }
+ /**
+ * Method namespaceIsRelative
+ *
+ * @param 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 namespaceValue
- * @return true if the given namespace is absolute.
- */
- public static boolean namespaceIsAbsolute(String namespaceValue) {
+ /**
+ * Method namespaceIsAbsolute
+ *
+ * @param namespace
+ * @return true if the given namespace is absolute.
+ */
+ public static boolean namespaceIsAbsolute(Attr namespace) {
+ return namespaceIsAbsolute(namespace.getValue());
+ }
- // 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) {
+ // assume empty namespaces are absolute
+ if (namespaceValue.length() == 0) {
+ return true;
+ }
+ return namespaceValue.indexOf(':') > 0;
+ }
- /**
- * This method throws an exception if the Attribute value contains
- * a relative URI.
- *
- * @param attr
- * @throws CanonicalizationException
- */
- public static void assertNotRelativeNS(Attr attr)
- throws CanonicalizationException {
+ /**
+ * 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;
+ }
- if (attr == null) {
- return;
- }
+ String nodeAttrName = attr.getNodeName();
+ boolean definesDefaultNS = nodeAttrName.equals("xmlns");
+ boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");
- 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 {
-
- if (!document.isSupported("Traversal", "2.0")) {
- Object exArgs[] = {
- document.getImplementation().getClass().getName() };
-
- throw new CanonicalizationException(
- "c14n.Canonicalizer.TraversalNotSupported", exArgs);
- }
- }
+ /**
+ * This method throws a CanonicalizationException if the supplied 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() };
- /**
- * 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 {
+ throw new CanonicalizationException(
+ "c14n.Canonicalizer.TraversalNotSupported", exArgs
+ );
+ }
+ }
- if (ctxNode != null) {
- NamedNodeMap attributes = ctxNode.getAttributes();
+ /**
+ * This method throws a CanonicalizationException if the supplied Element
+ * contains any relative namespaces.
+ *
+ * @param ctxNode
+ * @throws CanonicalizationException
+ * @see C14nHelper#assertNotRelativeNS(Attr)
+ */
+ public static void checkForRelativeNamespace(Element ctxNode)
+ throws CanonicalizationException {
+ if (ctxNode != null) {
+ NamedNodeMap attributes = ctxNode.getAttributes();
- for (int i = 0; i < attributes.getLength(); i++) {
- C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
- }
- } else {
- throw new CanonicalizationException(
- "Called checkForRelativeNamespace() on null");
- }
- }
+ for (int i = 0; i < attributes.getLength(); i++) {
+ C14nHelper.assertNotRelativeNS((Attr) attributes.item(i));
+ }
+ } else {
+ throw new CanonicalizationException("Called checkForRelativeNamespace() on null");
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
@@ -25,7 +27,6 @@
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -34,7 +35,6 @@
import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -42,8 +42,6 @@
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
-import java.util.logging.Logger;
-import java.util.logging.Logger;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
@@ -57,40 +55,46 @@
*
* @author Sean Mullan
* @author Raul Benito
- * @version $Revision: 1.2 $
*/
public abstract class Canonicalizer11 extends CanonicalizerBase {
- boolean firstCall = true;
- final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
- static final String XMLNS_URI = Constants.NamespaceSpecNS;
- static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
- static Logger log = Logger.getLogger(Canonicalizer11.class.getName());
+ private static final String XMLNS_URI = Constants.NamespaceSpecNS;
+ private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(Canonicalizer11.class.getName());
+ private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
- static class XmlAttrStack {
- int currentLevel = 0;
- int lastlevel = 0;
- XmlsStackElement cur;
+ private boolean firstCall = true;
+
+ private static class XmlAttrStack {
static class XmlsStackElement {
int level;
boolean rendered = false;
List<Attr> nodes = new ArrayList<Attr>();
};
+
+ int currentLevel = 0;
+ int lastlevel = 0;
+ XmlsStackElement cur;
List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
+
void push(int level) {
currentLevel = level;
- if (currentLevel == -1)
+ if (currentLevel == -1) {
return;
+ }
cur = null;
while (lastlevel >= currentLevel) {
levels.remove(levels.size() - 1);
- if (levels.size() == 0) {
+ int newSize = levels.size();
+ if (newSize == 0) {
lastlevel = 0;
return;
}
- lastlevel=(levels.get(levels.size()-1)).level;
+ lastlevel = (levels.get(newSize - 1)).level;
}
}
+
void addXmlnsAttr(Attr n) {
if (cur == null) {
cur = new XmlsStackElement();
@@ -100,22 +104,24 @@
}
cur.nodes.add(n);
}
+
void getXmlnsAttr(Collection<Attr> col) {
+ int size = levels.size() - 1;
if (cur == null) {
cur = new XmlsStackElement();
cur.level = currentLevel;
lastlevel = currentLevel;
levels.add(cur);
}
- int size = levels.size() - 2;
boolean parentRendered = false;
XmlsStackElement e = null;
if (size == -1) {
parentRendered = true;
} else {
e = levels.get(size);
- if (e.rendered && e.level+1 == currentLevel)
+ if (e.rendered && e.level + 1 == currentLevel) {
parentRendered = true;
+ }
}
if (parentRendered) {
col.addAll(cur.nodes);
@@ -126,7 +132,7 @@
Map<String, Attr> loa = new HashMap<String, Attr>();
List<Attr> baseAttrs = new ArrayList<Attr>();
boolean successiveOmitted = true;
- for (;size>=0;size--) {
+ for (; size >= 0; size--) {
e = levels.get(size);
if (e.rendered) {
successiveOmitted = false;
@@ -134,16 +140,15 @@
Iterator<Attr> it = e.nodes.iterator();
while (it.hasNext() && successiveOmitted) {
Attr n = it.next();
- if (n.getLocalName().equals("base")) {
- if (!e.rendered) {
- baseAttrs.add(n);
- }
- } else if (!loa.containsKey(n.getName()))
+ if (n.getLocalName().equals("base") && !e.rendered) {
+ baseAttrs.add(n);
+ } else if (!loa.containsKey(n.getName())) {
loa.put(n.getName(), n);
+ }
}
}
if (!baseAttrs.isEmpty()) {
- Iterator<Attr> it = cur.nodes.iterator();
+ Iterator<Attr> it = col.iterator();
String base = null;
Attr baseAttr = null;
while (it.hasNext()) {
@@ -164,7 +169,9 @@
try {
base = joinURI(n.getValue(), base);
} catch (URISyntaxException ue) {
- ue.printStackTrace();
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, ue.getMessage(), ue);
+ }
}
}
}
@@ -178,7 +185,8 @@
col.addAll(loa.values());
}
};
- XmlAttrStack xmlattrStack = new XmlAttrStack();
+
+ private XmlAttrStack xmlattrStack = new XmlAttrStack();
/**
* Constructor Canonicalizer11
@@ -190,194 +198,6 @@
}
/**
- * Returns the Attr[]s to be outputted for the given element.
- * <br>
- * The code of this method is a copy of {@link #handleAttributes(Element,
- * NameSpaceSymbTable)},
- * whereas it takes into account that subtree-c14n is -- well --
- * subtree-based.
- * So if the element in question isRoot of c14n, it's parent is not in the
- * node set, as well as all other ancestors.
- *
- * @param E
- * @param ns
- * @return the Attr[]s to be outputted
- * @throws CanonicalizationException
- */
- Iterator<Attr> handleAttributesSubtree(Element E, NameSpaceSymbTable ns)
- throws CanonicalizationException {
- if (!E.hasAttributes() && !firstCall) {
- return null;
- }
- // result will contain the attrs which have to be outputted
- final SortedSet<Attr> result = this.result;
- result.clear();
- NamedNodeMap attrs = E.getAttributes();
- int attrsLength = attrs.getLength();
-
- for (int i = 0; i < attrsLength; i++) {
- Attr N = (Attr) attrs.item(i);
- String NUri = N.getNamespaceURI();
-
- if (XMLNS_URI != NUri) {
- // It's not a namespace attr node. Add to the result and
- // continue.
- result.add(N);
- continue;
- }
-
- String NName = N.getLocalName();
- String NValue = N.getValue();
- if (XML.equals(NName)
- && XML_LANG_URI.equals(NValue)) {
- // The default mapping for xml must not be output.
- continue;
- }
-
- Node n = ns.addMappingAndRender(NName, NValue, N);
-
- if (n != null) {
- // Render the ns definition
- result.add((Attr)n);
- if (C14nHelper.namespaceIsRelative(N)) {
- Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()};
- throw new CanonicalizationException(
- "c14n.Canonicalizer.RelativeNamespace", exArgs);
- }
- }
- }
-
- if (firstCall) {
- // It is the first node of the subtree
- // Obtain all the namespaces defined in the parents, and added
- // to the output.
- ns.getUnrenderedNodes(result);
- // output the attributes in the xml namespace.
- xmlattrStack.getXmlnsAttr(getSortedSetAsCollection(result));
- firstCall = false;
- }
-
- return result.iterator();
- }
-
-
-
- /**
- * Returns the Attr[]s to be outputted for the given element.
- * <br>
- * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a
- * DOM which has been prepared using
- * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
- * org.w3c.dom.Document)}.
- *
- * @param E
- * @param ns
- * @return the Attr[]s to be outputted
- * @throws CanonicalizationException
- */
- Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns)
- throws CanonicalizationException {
- // result will contain the attrs which have to be output
- xmlattrStack.push(ns.getLevel());
- boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1;
- NamedNodeMap attrs = null;
- int attrsLength = 0;
- if (E.hasAttributes()) {
- attrs = E.getAttributes();
- attrsLength = attrs.getLength();
- }
-
- SortedSet<Attr> result = this.result;
- result.clear();
-
- for (int i = 0; i < attrsLength; i++) {
- Attr N = (Attr)attrs.item(i);
- String NUri = N.getNamespaceURI();
-
- if (XMLNS_URI != NUri) {
- // A non namespace definition node.
- if (XML_LANG_URI == NUri) {
- if (N.getLocalName().equals("id")) {
- if (isRealVisible) {
- // treat xml:id like any other attribute
- // (emit it, but don't inherit it)
- result.add(N);
- }
- } else {
- xmlattrStack.addXmlnsAttr(N);
- }
- } else if (isRealVisible) {
- // The node is visible add the attribute to the list of
- // output attributes.
- result.add(N);
- }
- // keep working
- continue;
- }
-
- String NName = N.getLocalName();
- String NValue = N.getValue();
- if ("xml".equals(NName)
- && XML_LANG_URI.equals(NValue)) {
- /* except omit namespace node with local name xml, which defines
- * the xml prefix, if its string value is
- * http://www.w3.org/XML/1998/namespace.
- */
- continue;
- }
- // add the prefix binding to the ns symb table.
- // ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
- if (isVisible(N)) {
- if (!isRealVisible && ns.removeMappingIfRender(NName)) {
- continue;
- }
- // The xpath select this node output it if needed.
- // Node n = ns.addMappingAndRenderXNodeSet
- // (NName, NValue, N, isRealVisible);
- Node n = ns.addMappingAndRender(NName, NValue, N);
- if (n != null) {
- result.add((Attr)n);
- if (C14nHelper.namespaceIsRelative(N)) {
- Object exArgs[] =
- { E.getTagName(), NName, N.getNodeValue() };
- throw new CanonicalizationException(
- "c14n.Canonicalizer.RelativeNamespace", exArgs);
- }
- }
- } else {
- if (isRealVisible && NName != XMLNS) {
- ns.removeMapping(NName);
- } else {
- ns.addMapping(NName, NValue, N);
- }
- }
- }
- if (isRealVisible) {
- // The element is visible, handle the xmlns definition
- Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
- Node n = null;
- if (xmlns == null) {
- // No xmlns def just get the already defined.
- n = ns.getMapping(XMLNS);
- } else if (!isVisible(xmlns)) {
- // There is a defn but the xmlns is not selected by the xpath.
- // then xmlns=""
- n = ns.addMappingAndRender(XMLNS, "", nullNode);
- }
- // output the xmlns def if needed.
- if (n != null) {
- result.add((Attr)n);
- }
- // Float all xml:* attributes of the unselected parent elements to
- // this one. addXmlAttributes(E,result);
- xmlattrStack.getXmlnsAttr(result);
- ns.getUnrenderedNodes(result);
- }
-
- return result.iterator();
- }
-
- /**
* Always throws a CanonicalizationException because this is inclusive c14n.
*
* @param xpathNodeSet
@@ -385,10 +205,10 @@
* @return none it always fails
* @throws CanonicalizationException always
*/
- public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet,
- String inclusiveNamespaces) throws CanonicalizationException {
- throw new CanonicalizationException(
- "c14n.Canonicalizer.UnsupportedOperation");
+ public byte[] engineCanonicalizeXPathNodeSet(
+ Set<Node> xpathNodeSet, String inclusiveNamespaces
+ ) throws CanonicalizationException {
+ throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
}
/**
@@ -399,17 +219,189 @@
* @return none it always fails
* @throws CanonicalizationException
*/
- public byte[] engineCanonicalizeSubTree(Node rootNode,
- String inclusiveNamespaces) throws CanonicalizationException {
- throw new CanonicalizationException(
- "c14n.Canonicalizer.UnsupportedOperation");
+ public byte[] engineCanonicalizeSubTree(
+ Node rootNode, String inclusiveNamespaces
+ ) throws CanonicalizationException {
+ throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+ }
+
+ /**
+ * Returns the Attr[]s to be output for the given element.
+ * <br>
+ * The code of this method is a copy of {@link #handleAttributes(Element,
+ * NameSpaceSymbTable)},
+ * whereas it takes into account that subtree-c14n is -- well --
+ * subtree-based.
+ * So if the element in question isRoot of c14n, it's parent is not in the
+ * node set, as well as all other ancestors.
+ *
+ * @param element
+ * @param ns
+ * @return the Attr[]s to be output
+ * @throws CanonicalizationException
+ */
+ @Override
+ protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ if (!element.hasAttributes() && !firstCall) {
+ return null;
+ }
+ // result will contain the attrs which have to be output
+ final SortedSet<Attr> result = this.result;
+ result.clear();
+
+ if (element.hasAttributes()) {
+ NamedNodeMap attrs = element.getAttributes();
+ int attrsLength = attrs.getLength();
+
+ for (int i = 0; i < attrsLength; i++) {
+ Attr attribute = (Attr) attrs.item(i);
+ String NUri = attribute.getNamespaceURI();
+ String NName = attribute.getLocalName();
+ String NValue = attribute.getValue();
+
+ if (!XMLNS_URI.equals(NUri)) {
+ // It's not a namespace attr node. Add to the result and continue.
+ result.add(attribute);
+ } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
+ // The default mapping for xml must not be output.
+ Node n = ns.addMappingAndRender(NName, NValue, attribute);
+
+ if (n != null) {
+ // Render the ns definition
+ result.add((Attr)n);
+ if (C14nHelper.namespaceIsRelative(attribute)) {
+ Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
+ throw new CanonicalizationException(
+ "c14n.Canonicalizer.RelativeNamespace", exArgs
+ );
+ }
+ }
+ }
+ }
+ }
+
+ if (firstCall) {
+ // It is the first node of the subtree
+ // Obtain all the namespaces defined in the parents, and added to the output.
+ ns.getUnrenderedNodes(result);
+ // output the attributes in the xml namespace.
+ xmlattrStack.getXmlnsAttr(result);
+ firstCall = false;
+ }
+
+ return result.iterator();
}
- void circumventBugIfNeeded(XMLSignatureInput input)
+ /**
+ * Returns the Attr[]s to be output for the given element.
+ * <br>
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a
+ * DOM which has been prepared using
+ * {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
+ * org.w3c.dom.Document)}.
+ *
+ * @param element
+ * @param ns
+ * @return the Attr[]s to be output
+ * @throws CanonicalizationException
+ */
+ @Override
+ protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ // result will contain the attrs which have to be output
+ xmlattrStack.push(ns.getLevel());
+ boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
+ final SortedSet<Attr> result = this.result;
+ result.clear();
+
+ if (element.hasAttributes()) {
+ NamedNodeMap attrs = element.getAttributes();
+ int attrsLength = attrs.getLength();
+
+ for (int i = 0; i < attrsLength; i++) {
+ Attr attribute = (Attr) attrs.item(i);
+ String NUri = attribute.getNamespaceURI();
+ String NName = attribute.getLocalName();
+ String NValue = attribute.getValue();
+
+ if (!XMLNS_URI.equals(NUri)) {
+ //A non namespace definition node.
+ if (XML_LANG_URI.equals(NUri)) {
+ if (NName.equals("id")) {
+ if (isRealVisible) {
+ // treat xml:id like any other attribute
+ // (emit it, but don't inherit it)
+ result.add(attribute);
+ }
+ } else {
+ xmlattrStack.addXmlnsAttr(attribute);
+ }
+ } else if (isRealVisible) {
+ //The node is visible add the attribute to the list of output attributes.
+ result.add(attribute);
+ }
+ } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
+ /* except omit namespace node with local name xml, which defines
+ * the xml prefix, if its string value is
+ * http://www.w3.org/XML/1998/namespace.
+ */
+ // add the prefix binding to the ns symb table.
+ if (isVisible(attribute)) {
+ if (isRealVisible || !ns.removeMappingIfRender(NName)) {
+ // The xpath select this node output it if needed.
+ Node n = ns.addMappingAndRender(NName, NValue, attribute);
+ if (n != null) {
+ result.add((Attr)n);
+ if (C14nHelper.namespaceIsRelative(attribute)) {
+ Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+ throw new CanonicalizationException(
+ "c14n.Canonicalizer.RelativeNamespace", exArgs
+ );
+ }
+ }
+ }
+ } else {
+ if (isRealVisible && !XMLNS.equals(NName)) {
+ ns.removeMapping(NName);
+ } else {
+ ns.addMapping(NName, NValue, attribute);
+ }
+ }
+ }
+ }
+ }
+
+ if (isRealVisible) {
+ //The element is visible, handle the xmlns definition
+ Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
+ Node n = null;
+ if (xmlns == null) {
+ //No xmlns def just get the already defined.
+ n = ns.getMapping(XMLNS);
+ } else if (!isVisible(xmlns)) {
+ //There is a definition but the xmlns is not selected by the xpath.
+ //then xmlns=""
+ n = ns.addMappingAndRender(XMLNS, "", nullNode);
+ }
+ //output the xmlns def if needed.
+ if (n != null) {
+ result.add((Attr)n);
+ }
+ //Float all xml:* attributes of the unselected parent elements to this one.
+ xmlattrStack.getXmlnsAttr(result);
+ ns.getUnrenderedNodes(result);
+ }
+
+ return result.iterator();
+ }
+
+ protected void circumventBugIfNeeded(XMLSignatureInput input)
throws CanonicalizationException, ParserConfigurationException,
IOException, SAXException {
- if (!input.isNeedsToBeExpanded())
+ if (!input.isNeedsToBeExpanded()) {
return;
+ }
Document doc = null;
if (input.getSubNode() != null) {
doc = XMLUtils.getOwnerDocument(input.getSubNode());
@@ -419,40 +411,47 @@
XMLUtils.circumventBug2650(doc);
}
- void handleParent(Element e, NameSpaceSymbTable ns) {
- if (!e.hasAttributes()) {
+ protected void handleParent(Element e, NameSpaceSymbTable ns) {
+ if (!e.hasAttributes() && e.getNamespaceURI() == null) {
return;
}
xmlattrStack.push(-1);
NamedNodeMap attrs = e.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
- Attr N = (Attr) attrs.item(i);
- if (Constants.NamespaceSpecNS != N.getNamespaceURI()) {
- // Not a namespace definition, ignore.
- if (XML_LANG_URI == N.getNamespaceURI()) {
- xmlattrStack.addXmlnsAttr(N);
+ Attr attribute = (Attr) attrs.item(i);
+ String NName = attribute.getLocalName();
+ String NValue = attribute.getNodeValue();
+
+ if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
+ if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
+ ns.addMapping(NName, NValue, attribute);
}
- continue;
+ } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
+ xmlattrStack.addXmlnsAttr(attribute);
}
-
- String NName = N.getLocalName();
- String NValue = N.getNodeValue();
- if (XML.equals(NName)
- && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
- continue;
+ }
+ if (e.getNamespaceURI() != null) {
+ String NName = e.getPrefix();
+ String NValue = e.getNamespaceURI();
+ String Name;
+ if (NName == null || NName.equals("")) {
+ NName = "xmlns";
+ Name = "xmlns";
+ } else {
+ Name = "xmlns:" + NName;
}
- ns.addMapping(NName,NValue,N);
+ Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
+ n.setValue(NValue);
+ ns.addMapping(NName, NValue, n);
}
}
- private static String joinURI(String baseURI, String relativeURI)
- throws URISyntaxException {
+ private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
String bscheme = null;
String bauthority = null;
String bpath = "";
String bquery = null;
- String bfragment = null; // Is this correct?
// pre-parse the baseURI
if (baseURI != null) {
@@ -464,7 +463,6 @@
bauthority = base.getAuthority();
bpath = base.getPath();
bquery = base.getQuery();
- bfragment = base.getFragment();
}
URI r = new URI(relativeURI);
@@ -472,9 +470,8 @@
String rauthority = r.getAuthority();
String rpath = r.getPath();
String rquery = r.getQuery();
- String rfragment = null;
- String tscheme, tauthority, tpath, tquery, tfragment;
+ String tscheme, tauthority, tpath, tquery;
if (rscheme != null && rscheme.equals(bscheme)) {
rscheme = null;
}
@@ -518,13 +515,13 @@
}
tscheme = bscheme;
}
- tfragment = rfragment;
- return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString();
+ return new URI(tscheme, tauthority, tpath, tquery, null).toString();
}
private static String removeDotSegments(String path) {
-
- log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER");
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "STEP OUTPUT BUFFER\t\tINPUT BUFFER");
+ }
// 1. The input buffer is initialized with the now-appended path
// components then replace occurrences of "//" in the input buffer
@@ -535,7 +532,7 @@
}
// Initialize the output buffer with the empty string.
- StringBuffer output = new StringBuffer();
+ StringBuilder output = new StringBuilder();
// If the input buffer starts with a root slash "/" then move this
// character to the output buffer.
@@ -563,9 +560,9 @@
output.append("../");
}
printStep("2A", output.toString(), input);
- // 2B. if the input buffer begins with a prefix of "/./" or "/.",
- // where "." is a complete path segment, then replace that prefix
- // with "/" in the input buffer; otherwise,
+ // 2B. if the input buffer begins with a prefix of "/./" or "/.",
+ // where "." is a complete path segment, then replace that prefix
+ // with "/" in the input buffer; otherwise,
} else if (input.startsWith("/./")) {
input = input.substring(2);
printStep("2B", output.toString(), input);
@@ -573,16 +570,16 @@
// FIXME: what is complete path segment?
input = input.replaceFirst("/.", "/");
printStep("2B", output.toString(), input);
- // 2C. if the input buffer begins with a prefix of "/../" or "/..",
- // where ".." is a complete path segment, then replace that prefix
- // with "/" in the input buffer and if also the output buffer is
- // empty, last segment in the output buffer equals "../" or "..",
- // where ".." is a complete path segment, then append ".." or "/.."
- // for the latter case respectively to the output buffer else
- // remove the last segment and its preceding "/" (if any) from the
- // output buffer and if hereby the first character in the output
- // buffer was removed and it was not the root slash then delete a
- // leading slash from the input buffer; otherwise,
+ // 2C. if the input buffer begins with a prefix of "/../" or "/..",
+ // where ".." is a complete path segment, then replace that prefix
+ // with "/" in the input buffer and if also the output buffer is
+ // empty, last segment in the output buffer equals "../" or "..",
+ // where ".." is a complete path segment, then append ".." or "/.."
+ // for the latter case respectively to the output buffer else
+ // remove the last segment and its preceding "/" (if any) from the
+ // output buffer and if hereby the first character in the output
+ // buffer was removed and it was not the root slash then delete a
+ // leading slash from the input buffer; otherwise,
} else if (input.startsWith("/../")) {
input = input.substring(3);
if (output.length() == 0) {
@@ -594,7 +591,7 @@
} else {
int index = output.lastIndexOf("/");
if (index == -1) {
- output = new StringBuffer();
+ output = new StringBuilder();
if (input.charAt(0) == '/') {
input = input.substring(1);
}
@@ -615,7 +612,7 @@
} else {
int index = output.lastIndexOf("/");
if (index == -1) {
- output = new StringBuffer();
+ output = new StringBuilder();
if (input.charAt(0) == '/') {
input = input.substring(1);
}
@@ -624,23 +621,24 @@
}
}
printStep("2C", output.toString(), input);
- // 2D. if the input buffer consists only of ".", then remove
- // that from the input buffer else if the input buffer consists
- // only of ".." and if the output buffer does not contain only
- // the root slash "/", then move the ".." to the output buffer
- // else delte it.; otherwise,
+ // 2D. if the input buffer consists only of ".", then remove
+ // that from the input buffer else if the input buffer consists
+ // only of ".." and if the output buffer does not contain only
+ // the root slash "/", then move the ".." to the output buffer
+ // else delte it.; otherwise,
} else if (input.equals(".")) {
input = "";
printStep("2D", output.toString(), input);
} else if (input.equals("..")) {
- if (!output.toString().equals("/"))
+ if (!output.toString().equals("/")) {
output.append("..");
+ }
input = "";
printStep("2D", output.toString(), input);
- // 2E. move the first path segment (if any) in the input buffer
- // to the end of the output buffer, including the initial "/"
- // character (if any) and any subsequent characters up to, but not
- // including, the next "/" character or the end of the input buffer.
+ // 2E. move the first path segment (if any) in the input buffer
+ // to the end of the output buffer, including the initial "/"
+ // character (if any) and any subsequent characters up to, but not
+ // including, the next "/" character or the end of the input buffer.
} else {
int end = -1;
int begin = input.indexOf('/');
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_OmitComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11_WithComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
-
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -47,344 +47,348 @@
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
-
/**
* Implements <A HREF="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical
* XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
*
* @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1.5 $
*/
public abstract class Canonicalizer20010315 extends CanonicalizerBase {
- boolean firstCall=true;
- final SortedSet<Attr> result= new TreeSet<Attr>(COMPARE);
- static final String XMLNS_URI=Constants.NamespaceSpecNS;
- static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS;
- static class XmlAttrStack {
- int currentLevel=0;
- int lastlevel=0;
+ private static final String XMLNS_URI = Constants.NamespaceSpecNS;
+ private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
+
+ private boolean firstCall = true;
+ private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+
+ private static class XmlAttrStack {
+ static class XmlsStackElement {
+ int level;
+ boolean rendered = false;
+ List<Attr> nodes = new ArrayList<Attr>();
+ };
+
+ int currentLevel = 0;
+ int lastlevel = 0;
XmlsStackElement cur;
- static class XmlsStackElement {
- int level;
- boolean rendered=false;
- List<Attr> nodes=new ArrayList<Attr>();
- };
- List<XmlsStackElement> levels=new ArrayList<XmlsStackElement>();
+ List<XmlsStackElement> levels = new ArrayList<XmlsStackElement>();
+
void push(int level) {
- currentLevel=level;
- if (currentLevel==-1)
- return;
- cur=null;
- while (lastlevel>=currentLevel) {
- levels.remove(levels.size()-1);
- if (levels.size()==0) {
- lastlevel=0;
- return;
- }
- lastlevel=(levels.get(levels.size()-1)).level;
+ currentLevel = level;
+ if (currentLevel == -1) {
+ return;
+ }
+ cur = null;
+ while (lastlevel >= currentLevel) {
+ levels.remove(levels.size() - 1);
+ int newSize = levels.size();
+ if (newSize == 0) {
+ lastlevel = 0;
+ return;
}
+ lastlevel = (levels.get(newSize - 1)).level;
+ }
}
+
void addXmlnsAttr(Attr n) {
- if (cur==null) {
- cur=new XmlsStackElement();
- cur.level=currentLevel;
- levels.add(cur);
- lastlevel=currentLevel;
- }
- 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<Attr> col) {
- int size=levels.size()-1;
- if (cur==null) {
- cur=new XmlsStackElement();
- cur.level=currentLevel;
- lastlevel=currentLevel;
- levels.add(cur);
- }
- boolean parentRendered=false;
- XmlsStackElement e=null;
- if (size==-1) {
- parentRendered=true;
- } else {
- e=levels.get(size);
- if (e.rendered && e.level+1==currentLevel)
- parentRendered=true;
-
+ int size = levels.size() - 1;
+ if (cur == null) {
+ cur = new XmlsStackElement();
+ cur.level = currentLevel;
+ lastlevel = currentLevel;
+ levels.add(cur);
+ }
+ boolean parentRendered = false;
+ XmlsStackElement e = null;
+ if (size == -1) {
+ parentRendered = true;
+ } else {
+ e = levels.get(size);
+ if (e.rendered && e.level + 1 == currentLevel) {
+ parentRendered = true;
}
- if (parentRendered) {
- col.addAll(cur.nodes);
- cur.rendered=true;
- return;
- }
+ }
+ if (parentRendered) {
+ col.addAll(cur.nodes);
+ cur.rendered = true;
+ return;
+ }
- Map<String,Attr> loa = new HashMap<String,Attr>();
- for (;size>=0;size--) {
- e=levels.get(size);
- Iterator<Attr> it=e.nodes.iterator();
- while (it.hasNext()) {
- Attr n=it.next();
- if (!loa.containsKey(n.getName()))
- loa.put(n.getName(),n);
- }
- //if (e.rendered)
- //break;
+ Map<String, Attr> loa = new HashMap<String, Attr>();
+ for (; size >= 0; size--) {
+ e = levels.get(size);
+ Iterator<Attr> it = e.nodes.iterator();
+ while (it.hasNext()) {
+ Attr n = it.next();
+ if (!loa.containsKey(n.getName())) {
+ loa.put(n.getName(), n);
+ }
+ }
+ }
- };
- //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);
- }
+ * Constructor Canonicalizer20010315
+ *
+ * @param includeComments
+ */
+ public Canonicalizer20010315(boolean includeComments) {
+ super(includeComments);
+ }
- /**
- * Returns the Attr[]s to be outputted for the given element.
- * <br>
- * The code of this method is a copy of {@link #handleAttributes(Element,
- * NameSpaceSymbTable)},
- * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
- * So if the element in question isRoot of c14n, it's parent is not in the
- * node set, as well as all other ancestors.
- *
- * @param E
- * @param ns
- * @return the Attr[]s to be outputted
- * @throws CanonicalizationException
- */
- Iterator<Attr> handleAttributesSubtree(Element E, NameSpaceSymbTable ns )
- throws CanonicalizationException {
- if (!E.hasAttributes() && !firstCall) {
- return null;
- }
- // result will contain the attrs which have to be outputted
- final SortedSet<Attr> result = this.result;
- result.clear();
- NamedNodeMap attrs = E.getAttributes();
- int attrsLength = attrs.getLength();
+ /**
+ * Always throws a CanonicalizationException because this is inclusive c14n.
+ *
+ * @param xpathNodeSet
+ * @param inclusiveNamespaces
+ * @return none it always fails
+ * @throws CanonicalizationException always
+ */
+ public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
+ throws CanonicalizationException {
+
+ /** $todo$ well, should we throw UnsupportedOperationException ? */
+ throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+ }
- 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) {
- //It's not a namespace attr node. Add to the result and continue.
- result.add(N);
- 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)) {
- //The default mapping for xml must not be output.
- continue;
- }
-
- Node n=ns.addMappingAndRender(NName,NValue,N);
+ /**
+ * Returns the Attr[]s to be output for the given element.
+ * <br>
+ * The code of this method is a copy of {@link #handleAttributes(Element,
+ * NameSpaceSymbTable)},
+ * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
+ * So if the element in question isRoot of c14n, it's parent is not in the
+ * node set, as well as all other ancestors.
+ *
+ * @param element
+ * @param ns
+ * @return the Attr[]s to be output
+ * @throws CanonicalizationException
+ */
+ @Override
+ protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ if (!element.hasAttributes() && !firstCall) {
+ return null;
+ }
+ // result will contain the attrs which have to be output
+ final SortedSet<Attr> result = this.result;
+ result.clear();
- if (n!=null) {
- //Render the ns definition
- result.add((Attr)n);
- if (C14nHelper.namespaceIsRelative(N)) {
- Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
- throw new CanonicalizationException(
- "c14n.Canonicalizer.RelativeNamespace", exArgs);
- }
- }
- }
+ if (element.hasAttributes()) {
+ NamedNodeMap attrs = element.getAttributes();
+ int attrsLength = attrs.getLength();
- 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;
- }
+ 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();
- return result.iterator();
- }
+ 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);
- /**
- * Returns the Attr[]s to be outputted for the given element.
- * <br>
- * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
- * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
- * org.w3c.dom.Document)}.
- *
- * @param E
- * @param ns
- * @return the Attr[]s to be outputted
- * @throws CanonicalizationException
- */
- Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException {
- // result will contain the attrs which have to be outputted
- xmlattrStack.push(ns.getLevel());
- boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1;
- NamedNodeMap attrs = null;
- int attrsLength = 0;
- if (E.hasAttributes()) {
- attrs=E.getAttributes();
- attrsLength= attrs.getLength();
+ 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();
}
-
- SortedSet<Attr> result = this.result;
- result.clear();
-
- for (int i = 0; i < attrsLength; i++) {
- Attr N = (Attr) attrs.item(i);
- String NUri =N.getNamespaceURI();
+ /**
+ * Returns the Attr[]s to be output for the given element.
+ * <br>
+ * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has
+ * been prepared using {@link com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
+ * org.w3c.dom.Document)}.
+ *
+ * @param element
+ * @param ns
+ * @return the Attr[]s to be output
+ * @throws CanonicalizationException
+ */
+ @Override
+ protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ // result will contain the attrs which have to be output
+ xmlattrStack.push(ns.getLevel());
+ boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
+ final SortedSet<Attr> result = this.result;
+ result.clear();
- if (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;
- }
+ 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();
- 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;
+ 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);
+ }
+ }
}
- //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) {
+ 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);
- }
- //output the xmlns def if needed.
- if (n!=null) {
- result.add((Attr)n);
+ 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);
}
- //Float all xml:* attributes of the unselected parent elements to this one.
- //addXmlAttributes(E,result);
- xmlattrStack.getXmlnsAttr(result);
- ns.getUnrenderedNodes(getSortedSetAsCollection(result));
+
+ return result.iterator();
+ }
+ protected void circumventBugIfNeeded(XMLSignatureInput input)
+ throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
+ if (!input.isNeedsToBeExpanded()) {
+ return;
+ }
+ Document doc = null;
+ if (input.getSubNode() != null) {
+ doc = XMLUtils.getOwnerDocument(input.getSubNode());
+ } else {
+ doc = XMLUtils.getOwnerDocument(input.getNodeSet());
+ }
+ XMLUtils.circumventBug2650(doc);
}
- return result.iterator();
- }
- /**
- * Always throws a CanonicalizationException because this is inclusive c14n.
- *
- * @param xpathNodeSet
- * @param inclusiveNamespaces
- * @return none it always fails
- * @throws CanonicalizationException always
- */
- public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
- throws CanonicalizationException {
-
- /** $todo$ well, should we throw UnsupportedOperationException ? */
- throw new CanonicalizationException(
- "c14n.Canonicalizer.UnsupportedOperation");
- }
-
- /**
- * Always throws a CanonicalizationException because this is inclusive c14n.
- *
- * @param rootNode
- * @param inclusiveNamespaces
- * @return none it always fails
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
- throws CanonicalizationException {
+ @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();
- /** $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);
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315Excl.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
@@ -25,7 +27,6 @@
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
-
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -40,6 +41,7 @@
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
+
/**
* Implements " <A
* HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
@@ -52,301 +54,279 @@
* <i>THIS </i> implementation is a complete rewrite of the algorithm.
*
* @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1.5 $
+ * @version $Revision: 1147448 $
* @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#">
* XML Canonicalization, Version 1.0</a>
*/
public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
+
+ private static final String XML_LANG_URI = Constants.XML_LANG_SPACE_SpecNS;
+ private static final String XMLNS_URI = Constants.NamespaceSpecNS;
+
/**
* This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
* the inclusive namespaces.
*/
- TreeSet<String> _inclusiveNSSet = new TreeSet<String>();
- static final String XMLNS_URI=Constants.NamespaceSpecNS;
- final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
- /**
- * Constructor Canonicalizer20010315Excl
- *
- * @param includeComments
- */
- public Canonicalizer20010315Excl(boolean includeComments) {
- super(includeComments);
- }
+ private SortedSet<String> inclusiveNSSet;
+
+ private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+
+ /**
+ * Constructor Canonicalizer20010315Excl
+ *
+ * @param includeComments
+ */
+ public Canonicalizer20010315Excl(boolean includeComments) {
+ super(includeComments);
+ }
- /**
- * Method engineCanonicalizeSubTree
- * @inheritDoc
- * @param rootNode
- *
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeSubTree(Node rootNode)
- throws CanonicalizationException {
- return 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
+ /**
+ * 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);
- }
+ * @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);
+ }
- /**
- * Method handleAttributesSubtree
- * @inheritDoc
- * @param E
- * @throws CanonicalizationException
- */
- Iterator<Attr> handleAttributesSubtree(Element E,NameSpaceSymbTable ns)
- throws CanonicalizationException {
- // System.out.println("During the traversal, I encountered " +
- // XMLUtils.getXPath(E));
- // result will contain the attrs which have to be outputted
- SortedSet<Attr> result = this.result;
- result.clear();
- NamedNodeMap attrs=null;
-
- 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<String> visiblyUtilized = getNSSetClone();
-
- for (int i = 0; i < attrsLength; i++) {
- Attr N = (Attr) attrs.item(i);
+ /**
+ *
+ * @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);
+ }
- if (XMLNS_URI!=N.getNamespaceURI()) {
- //Not a namespace definition.
- //The Element is output element, add his prefix(if used) to visibyUtilized
- String prefix = N.getPrefix();
- if ( (prefix != null) && (!prefix.equals(XML) && !prefix.equals(XMLNS)) ) {
- visiblyUtilized.add(prefix);
- }
- //Add to the result.
- result.add(N);
- continue;
- }
- String NName=N.getLocalName();
- String NNodeValue=N.getNodeValue();
+ /**
+ * Method engineCanonicalizeXPathNodeSet
+ * @inheritDoc
+ * @param xpathNodeSet
+ * @param inclusiveNamespaces
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalizeXPathNodeSet(
+ Set<Node> xpathNodeSet, String inclusiveNamespaces
+ ) throws CanonicalizationException {
+ inclusiveNSSet = InclusiveNamespaces.prefixStr2Set(inclusiveNamespaces);
+ return super.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+ }
- 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;
- }
+ @Override
+ protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ // result will contain the attrs which have to be output
+ final SortedSet<Attr> result = this.result;
+ result.clear();
- } else {
- prefix=XMLNS;
- }
- visiblyUtilized.add(prefix);
-
- //This can be optimezed by I don't have time
- Iterator<String> it=visiblyUtilized.iterator();
- while (it.hasNext()) {
- String s=it.next();
- Attr key=ns.getMapping(s);
- if (key==null) {
- continue;
- }
- result.add(key);
- }
-
- return result.iterator();
+ // The prefix visibly utilized (in the attribute or in the name) in
+ // the element
+ SortedSet<String> visiblyUtilized = new TreeSet<String>();
+ if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) {
+ visiblyUtilized.addAll(inclusiveNSSet);
}
- /**
- * Method engineCanonicalizeXPathNodeSet
- * @inheritDoc
- * @param xpathNodeSet
- * @param inclusiveNamespaces
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet,
- String inclusiveNamespaces) throws CanonicalizationException {
+ 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();
- this._inclusiveNSSet = getInclusiveNameSpace(inclusiveNamespaces);
- return super.engineCanonicalizeXPathNodeSet(xpathNodeSet);
+ 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
+ );
+ }
+ }
+ }
+ String prefix = null;
+ if (element.getNamespaceURI() != null
+ && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
+ prefix = element.getPrefix();
+ } else {
+ prefix = XMLNS;
+ }
+ visiblyUtilized.add(prefix);
+ for (String s : visiblyUtilized) {
+ Attr key = ns.getMapping(s);
+ if (key != null) {
+ result.add(key);
+ }
}
- @SuppressWarnings("unchecked")
- private TreeSet<String> getInclusiveNameSpace(String inclusiveNameSpaces) {
- return (TreeSet<String>)InclusiveNamespaces.prefixStr2Set(inclusiveNameSpaces);
- }
-
-
- @SuppressWarnings("unchecked")
- private SortedSet<String> getNSSetClone() {
- return (SortedSet<String>) this._inclusiveNSSet.clone();
+ return result.iterator();
}
-
- /**
+ /**
* @inheritDoc
- * @param E
- * @throws CanonicalizationException
- */
- final Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns)
- throws CanonicalizationException {
- // result will contain the attrs which have to be outputted
- SortedSet<Attr> result = this.result;
- result.clear();
- NamedNodeMap attrs = null;
- int attrsLength = 0;
- if (E.hasAttributes()) {
- attrs = E.getAttributes();
- attrsLength = attrs.getLength();
+ * @param element
+ * @throws CanonicalizationException
+ */
+ @Override
+ protected final Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ // result will contain the attrs which have to be output
+ final SortedSet<Attr> result = this.result;
+ result.clear();
+
+ // The prefix visibly utilized (in the attribute or in the name) in
+ // the element
+ Set<String> visiblyUtilized = null;
+ // It's the output selected.
+ boolean isOutputElement = isVisibleDO(element, ns.getLevel()) == 1;
+ if (isOutputElement) {
+ visiblyUtilized = new TreeSet<String>();
+ if (inclusiveNSSet != null && !inclusiveNSSet.isEmpty()) {
+ visiblyUtilized.addAll(inclusiveNSSet);
+ }
}
- //The prefix visibly utilized(in the attribute or in the name) in the element
- Set<String> visiblyUtilized =null;
- //It's the output selected.
- boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1;
- if (isOutputElement) {
- visiblyUtilized = getNSSetClone();
- }
- for (int i = 0; i < attrsLength; i++) {
- Attr N = (Attr) attrs.item(i);
+ if (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;
+ if (!XMLNS_URI.equals(attribute.getNamespaceURI())) {
+ if (isVisible(attribute) && isOutputElement) {
+ // The Element is output element, add the prefix (if used)
+ // to visibyUtilized
+ String prefix = attribute.getPrefix();
+ if (prefix != null && !(prefix.equals(XML) || prefix.equals(XMLNS))) {
+ visiblyUtilized.add(prefix);
}
- String NName=N.getLocalName();
- if (isOutputElement && !isVisible(N) && NName!=XMLNS) {
- ns.removeMappingIfNotRender(NName);
- continue;
- }
- String NNodeValue=N.getNodeValue();
+ // Add to the result.
+ result.add(attribute);
+ }
+ } else if (isOutputElement && !isVisible(attribute) && !XMLNS.equals(NName)) {
+ ns.removeMappingIfNotRender(NName);
+ } else {
+ if (!isOutputElement && isVisible(attribute)
+ && inclusiveNSSet.contains(NName)
+ && !ns.removeMappingIfRender(NName)) {
+ Node n = ns.addMappingAndRender(NName, NNodeValue, attribute);
+ if (n != null) {
+ result.add((Attr)n);
+ if (C14nHelper.namespaceIsRelative(attribute)) {
+ Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+ throw new CanonicalizationException(
+ "c14n.Canonicalizer.RelativeNamespace", exArgs
+ );
+ }
+ }
+ }
- if (!isOutputElement && isVisible(N) && _inclusiveNSSet.contains(NName) && !ns.removeMappingIfRender(NName)) {
- Node n=ns.addMappingAndRender(NName,NNodeValue,N);
- if (n!=null) {
- result.add((Attr)n);
- if (C14nHelper.namespaceIsRelative(N)) {
- Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
- throw new CanonicalizationException(
- "c14n.Canonicalizer.RelativeNamespace", exArgs);
- }
- }
- }
-
-
-
- if (ns.addMapping(NName, NNodeValue,N)) {
- //New definiton check if it is relative
- if (C14nHelper.namespaceIsRelative(NNodeValue)) {
- Object exArgs[] = {E.getTagName(), NName,
- N.getNodeValue()};
- throw new CanonicalizationException(
- "c14n.Canonicalizer.RelativeNamespace", exArgs);
+ if (ns.addMapping(NName, NNodeValue, attribute)
+ && C14nHelper.namespaceIsRelative(NNodeValue)) {
+ // New definition check if it is relative
+ Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
+ throw new CanonicalizationException(
+ "c14n.Canonicalizer.RelativeNamespace", exArgs
+ );
+ }
}
}
- }
+ }
- if (isOutputElement) {
- //The element is visible, handle the xmlns definition
- Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
- if ((xmlns!=null) && (!isVisible(xmlns))) {
- //There is a definition but the xmlns is not selected by the xpath.
- //then xmlns=""
- ns.addMapping(XMLNS,"",nullNode);
+ if (isOutputElement) {
+ // The element is visible, handle the xmlns definition
+ Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
+ if (xmlns != null && !isVisible(xmlns)) {
+ // There is a definition but the xmlns is not selected by the
+ // xpath. then xmlns=""
+ ns.addMapping(XMLNS, "", nullNode);
}
- if (E.getNamespaceURI() != null) {
- String prefix = E.getPrefix();
- if ((prefix == null) || (prefix.length() == 0)) {
- visiblyUtilized.add(XMLNS);
- } else {
- visiblyUtilized.add( prefix);
- }
- } else {
- visiblyUtilized.add(XMLNS);
- }
- //This can be optimezed by I don't have time
- //visiblyUtilized.addAll(this._inclusiveNSSet);
- Iterator<String> it=visiblyUtilized.iterator();
- while (it.hasNext()) {
- String s=it.next();
- Attr key=ns.getMapping(s);
- if (key==null) {
- continue;
- }
- result.add(key);
- }
+ String prefix = null;
+ if (element.getNamespaceURI() != null
+ && !(element.getPrefix() == null || element.getPrefix().length() == 0)) {
+ prefix = element.getPrefix();
+ } else {
+ prefix = XMLNS;
+ }
+ visiblyUtilized.add(prefix);
+
+ for (String s : visiblyUtilized) {
+ Attr key = ns.getMapping(s);
+ if (key != null) {
+ result.add(key);
}
-
- return result.iterator();
+ }
}
- void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
- if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty())
- return;
- Document doc = null;
- if (input.getSubNode() != null) {
- doc=XMLUtils.getOwnerDocument(input.getSubNode());
- } else {
- doc=XMLUtils.getOwnerDocument(input.getNodeSet());
- }
+
+ return result.iterator();
+ }
- XMLUtils.circumventBug2650(doc);
- }
+ protected void circumventBugIfNeeded(XMLSignatureInput input)
+ throws CanonicalizationException, ParserConfigurationException,
+ IOException, SAXException {
+ if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty() || inclusiveNSSet.isEmpty()) {
+ return;
+ }
+ Document doc = null;
+ if (input.getSubNode() != null) {
+ doc = XMLUtils.getOwnerDocument(input.getSubNode());
+ } else {
+ doc = XMLUtils.getOwnerDocument(input.getNodeSet());
+ }
+ XMLUtils.circumventBug2650(doc);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclOmitComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,48 +2,44 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
-
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-/**
- *
- *
- */
-public class Canonicalizer20010315ExclOmitComments
- extends Canonicalizer20010315Excl {
+public class Canonicalizer20010315ExclOmitComments extends Canonicalizer20010315Excl {
+
+ /**
+ *
+ */
+ public Canonicalizer20010315ExclOmitComments() {
+ super(false);
+ }
- /**
- *
- */
- public Canonicalizer20010315ExclOmitComments() {
- super(false);
- }
+ /** @inheritDoc */
+ public final String engineGetURI() {
+ return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
+ }
- /** @inheritDoc */
- public final String engineGetURI() {
- return Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
- }
-
- /** @inheritDoc */
- public final boolean engineGetIncludeComments() {
- return false;
- }
+ /** @inheritDoc */
+ public final boolean engineGetIncludeComments() {
+ return false;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315ExclWithComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,52 +2,48 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
-
-
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-
/**
* Class Canonicalizer20010315ExclWithComments
- *
- * @version $Revision: 1.5 $
*/
-public class Canonicalizer20010315ExclWithComments
- extends Canonicalizer20010315Excl {
+public class Canonicalizer20010315ExclWithComments extends Canonicalizer20010315Excl {
+
+ /**
+ * Constructor Canonicalizer20010315ExclWithComments
+ *
+ */
+ public Canonicalizer20010315ExclWithComments() {
+ super(true);
+ }
- /**
- * Constructor Canonicalizer20010315ExclWithComments
- *
- */
- public Canonicalizer20010315ExclWithComments() {
- super(true);
- }
+ /** @inheritDoc */
+ public final String engineGetURI() {
+ return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
+ }
- /** @inheritDoc */
- public final String engineGetURI() {
- return Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS;
- }
-
- /** @inheritDoc */
- public final boolean engineGetIncludeComments() {
- return true;
- }
+ /** @inheritDoc */
+ public final boolean engineGetIncludeComments() {
+ return true;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315OmitComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,50 +2,48 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
-
-
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
-
/**
- *
* @author Christian Geuer-Pollmann
*/
public class Canonicalizer20010315OmitComments extends Canonicalizer20010315 {
- /**
- * Constructor Canonicalizer20010315WithXPathOmitComments
- *
- */
- public Canonicalizer20010315OmitComments() {
- super(false);
- }
+ /**
+ * Constructor Canonicalizer20010315WithXPathOmitComments
+ *
+ */
+ public Canonicalizer20010315OmitComments() {
+ super(false);
+ }
- /** @inheritDoc */
- public final String engineGetURI() {
- return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
- }
+ /** @inheritDoc */
+ public final String engineGetURI() {
+ return Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
+ }
- /** @inheritDoc */
- public final boolean engineGetIncludeComments() {
- return false;
- }
+ /** @inheritDoc */
+ public final boolean engineGetIncludeComments() {
+ return false;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer20010315WithComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,47 +2,47 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
- *
* @author Christian Geuer-Pollmann
*/
public class Canonicalizer20010315WithComments extends Canonicalizer20010315 {
- /**
- * Constructor Canonicalizer20010315WithXPathWithComments
- *
- */
- public Canonicalizer20010315WithComments() {
- super(true);
- }
+ /**
+ * Constructor Canonicalizer20010315WithXPathWithComments
+ */
+ public Canonicalizer20010315WithComments() {
+ super(true);
+ }
- /** @inheritDoc */
- public final String engineGetURI() {
- return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
- }
+ /** @inheritDoc */
+ public final String engineGetURI() {
+ return Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS;
+ }
- /** @inheritDoc */
- public final boolean engineGetIncludeComments() {
- return true;
- }
+ /** @inheritDoc */
+ public final boolean engineGetIncludeComments() {
+ return true;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerBase.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
-
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -33,12 +33,10 @@
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
-import java.util.SortedSet;
-import java.util.Collection;
+import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizerSpi;
@@ -56,794 +54,829 @@
import org.w3c.dom.ProcessingInstruction;
import org.xml.sax.SAXException;
-
/**
* Abstract base class for canonicalization algorithms.
*
* @author Christian Geuer-Pollmann <geuerp@apache.org>
- * @version $Revision: 1.5 $
*/
public abstract class CanonicalizerBase extends CanonicalizerSpi {
- //Constants to be outputed, In char array form, so
- //less garbage is generate when outputed.
- private static final byte[] _END_PI = {'?','>'};
- private static final byte[] _BEGIN_PI = {'<','?'};
- private static final byte[] _END_COMM = {'-','-','>'};
- private static final byte[] _BEGIN_COMM = {'<','!','-','-'};
- private static final byte[] __XA_ = {'&','#','x','A',';'};
- private static final byte[] __X9_ = {'&','#','x','9',';'};
- private static final byte[] _QUOT_ = {'&','q','u','o','t',';'};
- private static final byte[] __XD_ = {'&','#','x','D',';'};
- private static final byte[] _GT_ = {'&','g','t',';'};
- private static final byte[] _LT_ = {'&','l','t',';'};
- private static final byte[] _END_TAG = {'<','/'};
- private static final byte[] _AMP_ = {'&','a','m','p',';'};
- final static AttrCompare COMPARE=new AttrCompare();
- final static String XML="xml";
- final static String XMLNS="xmlns";
- final static byte[] equalsStr= {'=','\"'};
- static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
- static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
- static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
- //The null xmlns definiton.
- protected static final Attr nullNode;
- static {
- try {
- nullNode=DocumentBuilderFactory.newInstance().
- newDocumentBuilder().newDocument().createAttributeNS(Constants.NamespaceSpecNS,XMLNS);
- nullNode.setValue("");
- } catch (Exception e) {
- throw new RuntimeException("Unable to create nullNode"/*,*/+e);
+ public static final String XML = "xml";
+ public static final String XMLNS = "xmlns";
+
+ protected static final AttrCompare COMPARE = new AttrCompare();
+ protected static final Attr nullNode;
+
+ private static final byte[] END_PI = {'?','>'};
+ private static final byte[] BEGIN_PI = {'<','?'};
+ private static final byte[] END_COMM = {'-','-','>'};
+ private static final byte[] BEGIN_COMM = {'<','!','-','-'};
+ private static final byte[] XA = {'&','#','x','A',';'};
+ private static final byte[] X9 = {'&','#','x','9',';'};
+ private static final byte[] QUOT = {'&','q','u','o','t',';'};
+ private static final byte[] XD = {'&','#','x','D',';'};
+ private static final byte[] GT = {'&','g','t',';'};
+ private static final byte[] LT = {'&','l','t',';'};
+ private static final byte[] END_TAG = {'<','/'};
+ private static final byte[] AMP = {'&','a','m','p',';'};
+ private static final byte[] equalsStr = {'=','\"'};
+
+ protected static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
+ protected static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
+ protected static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
+
+ static {
+ // The null xmlns definition.
+ try {
+ DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ nullNode = documentBuilder.newDocument().createAttributeNS(Constants.NamespaceSpecNS, XMLNS);
+ nullNode.setValue("");
+ } catch (Exception e) {
+ throw new RuntimeException("Unable to create nullNode: " + e);
+ }
}
- }
- List<NodeFilter> nodeFilter;
+ private List<NodeFilter> nodeFilter;
- boolean _includeComments;
- Set<Node> _xpathNodeSet = null;
- /**
- * The node to be skiped/excluded from the DOM tree
- * in subtree canonicalizations.
- */
- Node _excludeNode =null;
- OutputStream _writer = new UnsyncByteArrayOutputStream();//null;
+ private boolean includeComments;
+ private Set<Node> xpathNodeSet;
+ /**
+ * The node to be skipped/excluded from the DOM tree
+ * in subtree canonicalizations.
+ */
+ private Node excludeNode;
+ private OutputStream writer = new ByteArrayOutputStream();
- /**
- * Constructor CanonicalizerBase
- *
- * @param includeComments
- */
- public CanonicalizerBase(boolean includeComments) {
- this._includeComments = includeComments;
- }
+ /**
+ * Constructor CanonicalizerBase
+ *
+ * @param includeComments
+ */
+ public CanonicalizerBase(boolean includeComments) {
+ this.includeComments = includeComments;
+ }
+
+ /**
+ * Method engineCanonicalizeSubTree
+ * @inheritDoc
+ * @param rootNode
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalizeSubTree(Node rootNode)
+ throws CanonicalizationException {
+ return engineCanonicalizeSubTree(rootNode, (Node)null);
+ }
- /**
- * Method engineCanonicalizeSubTree
- * @inheritDoc
- * @param rootNode
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeSubTree(Node rootNode)
- throws CanonicalizationException {
- return engineCanonicalizeSubTree(rootNode,(Node)null);
- }
- /**
- * Method engineCanonicalizeXPathNodeSet
- * @inheritDoc
- * @param xpathNodeSet
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
- throws CanonicalizationException {
- this._xpathNodeSet = xpathNodeSet;
- return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this._xpathNodeSet));
- }
+ /**
+ * Method engineCanonicalizeXPathNodeSet
+ * @inheritDoc
+ * @param xpathNodeSet
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet)
+ throws CanonicalizationException {
+ this.xpathNodeSet = xpathNodeSet;
+ return engineCanonicalizeXPathNodeSetInternal(XMLUtils.getOwnerDocument(this.xpathNodeSet));
+ }
- /**
- * Canonicalizes a Subtree node.
- * @param input the root of the subtree to canicalize
- * @return The canonicalize stream.
- * @throws CanonicalizationException
- */
- public byte[] engineCanonicalize(XMLSignatureInput input)
- throws CanonicalizationException {
+ /**
+ * Canonicalizes a Subtree node.
+ * @param input the root of the subtree to canicalize
+ * @return The canonicalize stream.
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalize(XMLSignatureInput input) throws CanonicalizationException {
try {
- if (input.isExcludeComments())
- _includeComments = false;
- byte[] bytes;
- if (input.isOctetStream()) {
- return engineCanonicalize(input.getBytes());
- }
- if (input.isElement()) {
- bytes = engineCanonicalizeSubTree(input.getSubNode(), input
- .getExcludeNode());
- return bytes;
- } else if (input.isNodeSet()) {
- nodeFilter=input.getNodeFilters();
+ if (input.isExcludeComments()) {
+ includeComments = false;
+ }
+ if (input.isOctetStream()) {
+ return engineCanonicalize(input.getBytes());
+ }
+ if (input.isElement()) {
+ return engineCanonicalizeSubTree(input.getSubNode(), input.getExcludeNode());
+ } else if (input.isNodeSet()) {
+ nodeFilter = input.getNodeFilters();
circumventBugIfNeeded(input);
- if (input.getSubNode() != null) {
- bytes = engineCanonicalizeXPathNodeSetInternal(input.getSubNode());
- } else {
- bytes = engineCanonicalizeXPathNodeSet(input.getNodeSet());
- }
- return bytes;
+ 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);
+ }
+ }
- }
- 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;
+ /**
+ * @param writer The writer to set.
+ */
+ public void setWriter(OutputStream writer) {
+ this.writer = writer;
}
/**
- * Canonicalizes a Subtree node.
- *
- * @param rootNode
- * the root of the subtree to canicalize
- * @param excludeNode
- * a node to be excluded from the canicalize operation
- * @return The canonicalize stream.
- * @throws CanonicalizationException
- */
- byte[] engineCanonicalizeSubTree(Node rootNode,Node excludeNode)
- throws CanonicalizationException {
- this._excludeNode = excludeNode;
+ * Canonicalizes a Subtree node.
+ *
+ * @param rootNode
+ * the root of the subtree to canonicalize
+ * @param excludeNode
+ * a node to be excluded from the canonicalize operation
+ * @return The canonicalize stream.
+ * @throws CanonicalizationException
+ */
+ protected byte[] engineCanonicalizeSubTree(Node rootNode, Node excludeNode)
+ throws CanonicalizationException {
+ this.excludeNode = excludeNode;
try {
- NameSpaceSymbTable ns=new NameSpaceSymbTable();
- int nodeLevel=NODE_BEFORE_DOCUMENT_ELEMENT;
- if (rootNode != null && rootNode.getNodeType() == Node.ELEMENT_NODE) {
+ NameSpaceSymbTable ns = new NameSpaceSymbTable();
+ int nodeLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
+ if (rootNode != null && Node.ELEMENT_NODE == rootNode.getNodeType()) {
//Fills the nssymbtable with the definitions of the parent of the root subnode
- getParentNameSpaces((Element)rootNode,ns);
- nodeLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
- }
- this.canonicalizeSubTree(rootNode,ns,rootNode,nodeLevel);
- this._writer.close();
- if (this._writer instanceof ByteArrayOutputStream) {
- byte []result=((ByteArrayOutputStream)this._writer).toByteArray();
- if (reset) {
- ((ByteArrayOutputStream)this._writer).reset();
+ getParentNameSpaces((Element)rootNode, ns);
+ nodeLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
}
+ this.canonicalizeSubTree(rootNode, ns, rootNode, nodeLevel);
+ this.writer.flush();
+ if (this.writer instanceof ByteArrayOutputStream) {
+ byte[] result = ((ByteArrayOutputStream)this.writer).toByteArray();
+ if (reset) {
+ ((ByteArrayOutputStream)this.writer).reset();
+ } else {
+ this.writer.close();
+ }
return result;
- } else if (this._writer instanceof UnsyncByteArrayOutputStream) {
- byte []result=((UnsyncByteArrayOutputStream)this._writer).toByteArray();
- if (reset) {
- ((UnsyncByteArrayOutputStream)this._writer).reset();
- }
- return result;
- }
- return null;
+ } else if (this.writer instanceof UnsyncByteArrayOutputStream) {
+ byte[] result = ((UnsyncByteArrayOutputStream)this.writer).toByteArray();
+ if (reset) {
+ ((UnsyncByteArrayOutputStream)this.writer).reset();
+ } else {
+ this.writer.close();
+ }
+ return result;
+ } else {
+ this.writer.close();
+ }
+ return null;
- } catch (UnsupportedEncodingException ex) {
- throw new CanonicalizationException("empty", ex);
- } catch (IOException ex) {
- throw new CanonicalizationException("empty", ex);
- }
- }
+ } catch (UnsupportedEncodingException ex) {
+ throw new CanonicalizationException("empty", ex);
+ } catch (IOException ex) {
+ throw new CanonicalizationException("empty", ex);
+ }
+ }
- /**
- * Method canonicalizeSubTree, this function is a recursive one.
- *
- * @param currentNode
- * @param ns
- * @param endnode
- * @throws CanonicalizationException
- * @throws IOException
- */
- final void canonicalizeSubTree(Node currentNode, NameSpaceSymbTable ns,Node endnode,
- int documentLevel)
- throws CanonicalizationException, IOException {
- if (isVisibleInt(currentNode)==-1)
- return;
- Node sibling=null;
- Node parentNode=null;
- final OutputStream writer=this._writer;
- final Node excludeNode=this._excludeNode;
- final boolean includeComments=this._includeComments;
- Map<String, byte[]> cache=new HashMap<String, byte[]>();
+ /**
+ * Method canonicalizeSubTree, this function is a recursive one.
+ *
+ * @param currentNode
+ * @param ns
+ * @param endnode
+ * @throws CanonicalizationException
+ * @throws IOException
+ */
+ protected final void canonicalizeSubTree(
+ Node currentNode, NameSpaceSymbTable ns, Node endnode, int documentLevel
+ ) throws CanonicalizationException, IOException {
+ if (isVisibleInt(currentNode) == -1) {
+ return;
+ }
+ Node sibling = null;
+ Node parentNode = null;
+ final OutputStream writer = this.writer;
+ final Node excludeNode = this.excludeNode;
+ final boolean includeComments = this.includeComments;
+ Map<String, byte[]> cache = new HashMap<String, byte[]>();
do {
- switch (currentNode.getNodeType()) {
-
- case Node.DOCUMENT_TYPE_NODE :
- default :
- break;
+ 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.ENTITY_NODE :
+ case Node.NOTATION_NODE :
+ case Node.ATTRIBUTE_NODE :
+ // illegal node type during traversal
+ throw new CanonicalizationException("empty");
case Node.DOCUMENT_FRAGMENT_NODE :
- case Node.DOCUMENT_NODE :
- ns.outputNodePush();
- sibling= currentNode.getFirstChild();
- break;
+ case Node.DOCUMENT_NODE :
+ ns.outputNodePush();
+ sibling = currentNode.getFirstChild();
+ break;
- case Node.COMMENT_NODE :
- if (includeComments) {
- outputCommentToWriter((Comment) currentNode, writer, documentLevel);
- }
- break;
+ case Node.COMMENT_NODE :
+ if (includeComments) {
+ outputCommentToWriter((Comment) currentNode, writer, documentLevel);
+ }
+ break;
- case Node.PROCESSING_INSTRUCTION_NODE :
- outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
- break;
+ case Node.PROCESSING_INSTRUCTION_NODE :
+ outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
+ break;
- case Node.TEXT_NODE :
- case Node.CDATA_SECTION_NODE :
- outputTextToWriter(currentNode.getNodeValue(), writer);
- break;
+ case Node.TEXT_NODE :
+ case Node.CDATA_SECTION_NODE :
+ outputTextToWriter(currentNode.getNodeValue(), writer);
+ break;
- case Node.ELEMENT_NODE :
- documentLevel=NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
- if (currentNode==excludeNode) {
- break;
- }
- Element currentElement = (Element) currentNode;
- //Add a level to the nssymbtable. So latter can be pop-back.
- ns.outputNodePush();
- writer.write('<');
- String name=currentElement.getTagName();
- UtfHelpper.writeByte(name,writer,cache);
+ case Node.ELEMENT_NODE :
+ documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
+ if (currentNode == excludeNode) {
+ break;
+ }
+ Element currentElement = (Element)currentNode;
+ //Add a level to the nssymbtable. So latter can be pop-back.
+ ns.outputNodePush();
+ writer.write('<');
+ String name = currentElement.getTagName();
+ UtfHelpper.writeByte(name, writer, cache);
- Iterator<Attr> attrs = this.handleAttributesSubtree(currentElement,ns);
- if (attrs!=null) {
- //we output all Attrs which are available
- while (attrs.hasNext()) {
- Attr attr = attrs.next();
- outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache);
- }
- }
- writer.write('>');
- sibling= currentNode.getFirstChild();
- if (sibling==null) {
- writer.write(_END_TAG);
- UtfHelpper.writeStringToUtf8(name,writer);
- writer.write('>');
- //We fineshed with this level, pop to the previous definitions.
- ns.outputNodePop();
- if (parentNode != null) {
- sibling= currentNode.getNextSibling();
- }
- } else {
- parentNode=currentElement;
- }
- break;
+ Iterator<Attr> attrs = this.handleAttributesSubtree(currentElement, ns);
+ if (attrs != null) {
+ //we output all Attrs which are available
+ while (attrs.hasNext()) {
+ Attr attr = attrs.next();
+ outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+ }
+ }
+ 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;
}
- 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;
- }
+ break;
+
+ case Node.DOCUMENT_TYPE_NODE :
+ default :
+ break;
+ }
+ while (sibling == null && parentNode != null) {
+ writer.write(END_TAG);
+ UtfHelpper.writeByte(((Element)parentNode).getTagName(), writer, cache);
+ writer.write('>');
+ //We finished with this level, pop to the previous definitions.
+ ns.outputNodePop();
+ if (parentNode == endnode) {
+ return;
}
- if (sibling==null)
- return;
- currentNode=sibling;
- sibling=currentNode.getNextSibling();
+ 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.close();
- if (this._writer instanceof ByteArrayOutputStream) {
- byte [] sol=((ByteArrayOutputStream)this._writer).toByteArray();
- if (reset) {
- ((ByteArrayOutputStream)this._writer).reset();
- }
+ 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();
- }
- return result;
- }
- return null;
- } catch (UnsupportedEncodingException ex) {
- throw new CanonicalizationException("empty", ex);
- } catch (IOException ex) {
- throw new CanonicalizationException("empty", ex);
- }
- }
+ } 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);
+ }
+ }
- /**
- * 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;
+ /**
+ * 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 && currentNode.getNodeType() == Node.ELEMENT_NODE)
- getParentNameSpaces((Element)currentNode,ns);
- Node sibling=null;
- Node parentNode=null;
- OutputStream writer=this._writer;
- int documentLevel=NODE_BEFORE_DOCUMENT_ELEMENT;
- Map<String, byte[]> cache=new HashMap<String,byte[]>();
+ NameSpaceSymbTable ns = new NameSpaceSymbTable();
+ if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
+ getParentNameSpaces((Element)currentNode, ns);
+ }
+ if (currentNode == null) {
+ return;
+ }
+ Node sibling = null;
+ Node parentNode = null;
+ OutputStream writer = this.writer;
+ int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
+ Map<String, byte[]> cache = new HashMap<String, byte[]>();
do {
- switch (currentNode.getNodeType()) {
+ 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.DOCUMENT_TYPE_NODE :
- default :
- 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.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.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.COMMENT_NODE :
- if (this._includeComments && (isVisibleDO(currentNode,ns.getLevel())==1)) {
- outputCommentToWriter((Comment) currentNode, writer, documentLevel);
- }
- 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();
+ }
- case Node.PROCESSING_INSTRUCTION_NODE :
- if (isVisible(currentNode))
- outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
- break;
+ Iterator<Attr> attrs = handleAttributes(currentElement,ns);
+ if (attrs != null) {
+ //we output all Attrs which are available
+ while (attrs.hasNext()) {
+ Attr attr = attrs.next();
+ outputAttrToWriter(attr.getNodeName(), attr.getNodeValue(), writer, cache);
+ }
+ }
+ if (currentNodeIsVisible) {
+ writer.write('>');
+ }
+ sibling = currentNode.getFirstChild();
- 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();
+ 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;
}
-
- }
- 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);
+ }
- 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();
- }
+ protected int isVisibleDO(Node currentNode, int level) {
+ if (nodeFilter != null) {
+ Iterator<NodeFilter> it = nodeFilter.iterator();
+ while (it.hasNext()) {
+ int i = (it.next()).isNodeIncludeDO(currentNode, level);
+ if (i != 1) {
+ return i;
+ }
+ }
+ }
+ if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+ return 0;
+ }
+ return 1;
+ }
- Iterator<Attr> attrs = handleAttributes(currentElement,ns);
- if (attrs!=null) {
- //we output all Attrs which are available
- while (attrs.hasNext()) {
- Attr attr = attrs.next();
- outputAttrToWriter(attr.getNodeName(),attr.getNodeValue(), writer,cache);
- }
- }
- if (currentNodeIsVisible) {
- writer.write('>');
- }
- sibling= currentNode.getFirstChild();
+ protected int isVisibleInt(Node currentNode) {
+ if (nodeFilter != null) {
+ Iterator<NodeFilter> it = nodeFilter.iterator();
+ while (it.hasNext()) {
+ int i = (it.next()).isNodeInclude(currentNode);
+ if (i != 1) {
+ return i;
+ }
+ }
+ }
+ if ((this.xpathNodeSet != null) && !this.xpathNodeSet.contains(currentNode)) {
+ return 0;
+ }
+ return 1;
+ }
- 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;
+ protected boolean isVisible(Node currentNode) {
+ if (nodeFilter != null) {
+ Iterator<NodeFilter> it = nodeFilter.iterator();
+ while (it.hasNext()) {
+ if (it.next().isNodeInclude(currentNode) != 1) {
+ return false;
}
- 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 ((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<Element> parents = new ArrayList<Element>();
+ Node parent = n1;
+ while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
+ parents.add((Element)parent);
+ parent = parent.getParentNode();
+ }
+ //Visit them in reverse order.
+ ListIterator<Element> it = parents.listIterator(parents.size());
+ while (it.hasPrevious()) {
+ Element ele = it.previous();
+ handleParent(ele, ns);
+ }
+ parents.clear();
+ Attr nsprefix;
+ if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null)
+ && "".equals(nsprefix.getValue())) {
+ ns.addMappingAndRender(XMLNS, "", nullNode);
+ }
+ }
+
+ /**
+ * Obtain the attributes to output for this node in XPathNodeSet c14n.
+ *
+ * @param element
+ * @param ns
+ * @return the attributes nodes to output.
+ * @throws CanonicalizationException
+ */
+ abstract Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException;
+
+ /**
+ * Obtain the attributes to output for this node in a Subtree c14n.
+ *
+ * @param element
+ * @param ns
+ * @return the attributes nodes to output.
+ * @throws CanonicalizationException
+ */
+ abstract Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException;
+
+ abstract void circumventBugIfNeeded(XMLSignatureInput input)
+ throws CanonicalizationException, ParserConfigurationException, IOException, SAXException;
+
+ /**
+ * Outputs an Attribute to the internal Writer.
+ *
+ * The string value of the node is modified by replacing
+ * <UL>
+ * <LI>all ampersands (&) with <CODE>&amp;</CODE></LI>
+ * <LI>all open angle brackets (<) with <CODE>&lt;</CODE></LI>
+ * <LI>all quotation mark characters with <CODE>&quot;</CODE></LI>
+ * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
+ * references. The character references are written in uppercase
+ * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
+ * by the character reference <CODE>&#xD;</CODE>)</LI>
+ * </UL>
+ *
+ * @param name
+ * @param value
+ * @param writer
+ * @throws IOException
+ */
+ protected static final void outputAttrToWriter(
+ final String name, final String value,
+ final OutputStream writer, final Map<String, byte[]> cache
+ ) throws IOException {
+ writer.write(' ');
+ UtfHelpper.writeByte(name, writer, cache);
+ writer.write(equalsStr);
+ byte[] toWrite;
+ final int length = value.length();
+ int i = 0;
+ while (i < length) {
+ char c = value.charAt(i++);
+
+ switch (c) {
+
+ case '&' :
+ toWrite = AMP;
+ break;
+
+ case '<' :
+ toWrite = LT;
+ break;
+
+ case '"' :
+ toWrite = QUOT;
+ break;
+
+ case 0x09 : // '\t'
+ toWrite = X9;
+ break;
+
+ case 0x0A : // '\n'
+ toWrite = XA;
+ break;
+
+ case 0x0D : // '\r'
+ toWrite = XD;
+ break;
+
+ default :
+ if (c < 0x80) {
+ writer.write(c);
+ } else {
+ UtfHelpper.writeCharToUtf8(c, writer);
}
- if (sibling==null)
- return;
- currentNode=sibling;
- sibling=currentNode.getNextSibling();
- } while(true);
- }
- int isVisibleDO(Node currentNode,int level) {
- if (nodeFilter!=null) {
- Iterator<NodeFilter> it=nodeFilter.iterator();
- while (it.hasNext()) {
- int i=(it.next()).isNodeIncludeDO(currentNode,level);
- if (i!=1)
- return i;
- }
- }
- if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode))
- return 0;
- return 1;
- }
- int isVisibleInt(Node currentNode) {
- if (nodeFilter!=null) {
- Iterator<NodeFilter> it=nodeFilter.iterator();
- while (it.hasNext()) {
- int i=(it.next()).isNodeInclude(currentNode);
- if (i!=1)
- return i;
- }
- }
- if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode))
- return 0;
- return 1;
- }
-
- boolean isVisible(Node currentNode) {
- if (nodeFilter!=null) {
- Iterator<NodeFilter> it=nodeFilter.iterator();
- while (it.hasNext()) {
- if ((it.next()).isNodeInclude(currentNode)!=1)
- return false;
- }
- }
- if ((this._xpathNodeSet!=null) && !this._xpathNodeSet.contains(currentNode))
- return false;
- return true;
+ continue;
+ }
+ writer.write(toWrite);
}
- 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<Element> parents=new ArrayList<Element>(10);
- Node n1=el.getParentNode();
- if (n1 == null || n1.getNodeType() != Node.ELEMENT_NODE) {
- return;
- }
- //Obtain all the parents of the elemnt
- Node parent = n1;
- while (parent!=null && parent.getNodeType() == Node.ELEMENT_NODE) {
- parents.add((Element)parent);
- parent = parent.getParentNode();
- }
- //Visit them in reverse order.
- ListIterator<Element> it=parents.listIterator(parents.size());
- while (it.hasPrevious()) {
- Element ele=it.previous();
- handleParent(ele, ns);
- }
- Attr nsprefix;
- if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null)
- && "".equals(nsprefix.getValue())) {
- ns.addMappingAndRender("xmlns","",nullNode);
- }
- }
- /**
- * Obtain the attributes to output for this node in XPathNodeSet c14n.
- *
- * @param E
- * @param ns
- * @return the attributes nodes to output.
- * @throws CanonicalizationException
- */
- abstract Iterator<Attr> handleAttributes(Element E, NameSpaceSymbTable ns )
- throws CanonicalizationException;
+ writer.write('\"');
+ }
- /**
- * Obtain the attributes to output for this node in a Subtree c14n.
- *
- * @param E
- * @param ns
- * @return the attributes nodes to output.
- * @throws CanonicalizationException
- */
- abstract Iterator<Attr> handleAttributesSubtree(Element E, NameSpaceSymbTable ns)
- throws CanonicalizationException;
-
- abstract void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException;
+ /**
+ * Outputs 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);
- /**
- * Outputs an Attribute to the internal Writer.
- *
- * The string value of the node is modified by replacing
- * <UL>
- * <LI>all ampersands (&) with <CODE>&amp;</CODE></LI>
- * <LI>all open angle brackets (<) with <CODE>&lt;</CODE></LI>
- * <LI>all quotation mark characters with <CODE>&quot;</CODE></LI>
- * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD, with character
- * references. The character references are written in uppercase
- * hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE> is represented
- * by the character reference <CODE>&#xD;</CODE>)</LI>
- * </UL>
- *
- * @param name
- * @param value
- * @param writer
- * @throws IOException
- */
- static final void outputAttrToWriter(final String name, final String value, final OutputStream writer,
- final Map<String, byte[]> cache) throws IOException {
- writer.write(' ');
- UtfHelpper.writeByte(name,writer,cache);
- writer.write(equalsStr);
- byte []toWrite;
- final int length = value.length();
- int i=0;
- while (i < length) {
- char c = value.charAt(i++);
-
- switch (c) {
-
- case '&' :
- toWrite=_AMP_;
- break;
-
- case '<' :
- toWrite=_LT_;
- break;
-
- case '"' :
- toWrite=_QUOT_;
- break;
-
- case 0x09 : // '\t'
- toWrite=__X9_;
- break;
-
- case 0x0A : // '\n'
- toWrite=__XA_;
- break;
-
- case 0x0D : // '\r'
- toWrite=__XD_;
- break;
+ final String target = currentPI.getTarget();
+ int length = target.length();
- 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);
+ }
+ }
+ }
- 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();
+ final String data = currentPI.getData();
- 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');
- }
- }
+ length = data.length();
- /**
- * 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');
- }
- }
+ if (length > 0) {
+ writer.write(' ');
- /**
- * 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;
+ for (int i = 0; i < length; i++) {
+ char c = data.charAt(i);
+ if (c == 0x0D) {
+ writer.write(XD);
+ } else {
+ UtfHelpper.writeCharToUtf8(c, writer);
+ }
+ }
+ }
- case '>' :
- toWrite=_GT_;
- break;
-
- case 0xD :
- toWrite=__XD_;
- break;
-
- default :
- if (c < 0x80) {
- writer.write(c);
- } else {
- UtfHelpper.writeCharToUtf8(c,writer);
- };
- continue;
- }
- writer.write(toWrite);
- }
- }
-
- @SuppressWarnings("unchecked")
- protected Collection<Attr> getSortedSetAsCollection(SortedSet<Attr> result) {
- return (Collection<Attr>)(Collection)result;
+ 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);
+ }
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/CanonicalizerPhysical.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,184 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.c14n.implementations;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
+import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
+import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Comment;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.ProcessingInstruction;
+import org.xml.sax.SAXException;
+
+/**
+ * Serializes the physical representation of the subtree. All the attributes
+ * present in the subtree are emitted. The attributes are sorted within an element,
+ * with the namespace declarations appearing before the regular attributes.
+ * This algorithm is not a true canonicalization since equivalent subtrees
+ * may produce different output. It is therefore unsuitable for digital signatures.
+ * This same property makes it ideal for XML Encryption Syntax and Processing,
+ * because the decrypted XML content will share the same physical representation
+ * as the original XML content that was encrypted.
+ */
+public class CanonicalizerPhysical extends CanonicalizerBase {
+
+ private final SortedSet<Attr> result = new TreeSet<Attr>(COMPARE);
+
+ /**
+ * Constructor Canonicalizer20010315
+ */
+ public CanonicalizerPhysical() {
+ super(true);
+ }
+
+ /**
+ * Always throws a CanonicalizationException.
+ *
+ * @param xpathNodeSet
+ * @param inclusiveNamespaces
+ * @return none it always fails
+ * @throws CanonicalizationException always
+ */
+ public byte[] engineCanonicalizeXPathNodeSet(Set<Node> xpathNodeSet, String inclusiveNamespaces)
+ throws CanonicalizationException {
+
+ /** $todo$ well, should we throw UnsupportedOperationException ? */
+ throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+ }
+
+ /**
+ * Always throws a CanonicalizationException.
+ *
+ * @param rootNode
+ * @param inclusiveNamespaces
+ * @return none it always fails
+ * @throws CanonicalizationException
+ */
+ public byte[] engineCanonicalizeSubTree(Node rootNode, String inclusiveNamespaces)
+ throws CanonicalizationException {
+
+ /** $todo$ well, should we throw UnsupportedOperationException ? */
+ throw new CanonicalizationException("c14n.Canonicalizer.UnsupportedOperation");
+ }
+
+ /**
+ * Returns the Attr[]s to be output for the given element.
+ * <br>
+ * The code of this method is a copy of {@link #handleAttributes(Element,
+ * NameSpaceSymbTable)},
+ * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
+ * So if the element in question isRoot of c14n, it's parent is not in the
+ * node set, as well as all other ancestors.
+ *
+ * @param element
+ * @param ns
+ * @return the Attr[]s to be output
+ * @throws CanonicalizationException
+ */
+ @Override
+ protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
+ throws CanonicalizationException {
+ if (!element.hasAttributes()) {
+ return null;
+ }
+
+ // result will contain all the attrs declared directly on that element
+ final SortedSet<Attr> result = this.result;
+ result.clear();
+
+ if (element.hasAttributes()) {
+ NamedNodeMap attrs = element.getAttributes();
+ int attrsLength = attrs.getLength();
+
+ for (int i = 0; i < 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<Attr> 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);
+ }
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/NameSpaceSymbTable.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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;
@@ -29,191 +31,185 @@
import org.w3c.dom.Attr;
import org.w3c.dom.Node;
-
-
/**
- * A stack based Symble Table.
+ * A stack based Symbol Table.
*<br>For speed reasons all the symbols are introduced in the same map,
* and at the same time in a list so it can be removed when the frame is pop back.
* @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<SymbMap> 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<SymbMap> level;
+ private boolean cloned = true;
+
/**
* Default constractor
**/
public NameSpaceSymbTable() {
- level = new ArrayList<SymbMap>(10);
+ level = new ArrayList<SymbMap>();
//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<Attr> result) {
- //List result=new ArrayList();
- Iterator<NameSpaceSymbEntry> 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<Attr> result) {
+ Iterator<NameSpaceSymbEntry> 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;
-
- result.add(n.n);
+ symb.put(n.prefix, n);
+ n.lastrendered = n.uri;
+ n.rendered = true;
- }
- }
+ 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();
+ 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;
- }
+ 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);
+ public boolean addMapping(String prefix, String uri, Attr n) {
+ NameSpaceSymbEntry ob = symb.get(prefix);
+ if ((ob != null) && uri.equals(ob.uri)) {
+ //If we have it previously defined. Don't keep working.
+ return false;
+ }
+ //Creates and entry in the table for this new definition.
+ NameSpaceSymbEntry ne = new NameSpaceSymbEntry(uri, n, false, prefix);
needsClone();
- symb.put(prefix, ne);
- if (ob != null) {
- //We have a previous definition store it for the pop.
- //Check if a previous definition(not the inmidiatly one) has been rendered.
- ne.lastrendered=ob.lastrendered;
- if ((ob.lastrendered!=null)&& (ob.lastrendered.equals(uri))) {
- //Yes it is. Mark as rendered.
- ne.rendered=true;
- }
- }
+ symb.put(prefix, ne);
+ if (ob != null) {
+ //We have a previous definition store it for the pop.
+ //Check if a previous definition(not the inmidiatly one) has been rendered.
+ ne.lastrendered = ob.lastrendered;
+ if ((ob.lastrendered != null) && (ob.lastrendered.equals(uri))) {
+ //Yes it is. Mark as rendered.
+ ne.rendered = true;
+ }
+ }
return true;
- }
+ }
/**
* Adds a definition and mark it as render.
@@ -223,79 +219,91 @@
* @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);
+ }
- if (ob!=null && ob.rendered) {
+ public boolean removeMappingIfRender(String prefix) {
+ NameSpaceSymbEntry ob = symb.get(prefix);
+
+ 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 @@
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<NameSpaceSymbEntry> entrySet() {
- List<NameSpaceSymbEntry> a=new ArrayList<NameSpaceSymbEntry>();
- for (int i=0;i<entries.length;i++) {
- if ((entries[i]!=null) && !("".equals(entries[i].uri))) {
- a.add(entries[i]);
+ List<NameSpaceSymbEntry> a = new ArrayList<NameSpaceSymbEntry>();
+ 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 @@
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 @@
entries = new NameSpaceSymbEntry[newCapacity];
for (int i = oldCapacity; i-- > 0;) {
- if(oldKeys[i] != null) {
+ if (oldKeys[i] != null) {
String o = oldKeys[i];
int index = index(o);
keys[index] = o;
@@ -391,20 +388,19 @@
}
NameSpaceSymbEntry get(String key) {
- return entries[index(key)];
+ return entries[index(key)];
}
protected Object clone() {
try {
- SymbMap copy=(SymbMap) super.clone();
- copy.entries=new NameSpaceSymbEntry[entries.length];
- System.arraycopy(entries,0,copy.entries,0,entries.length);
- copy.keys=new String[keys.length];
- System.arraycopy(keys,0,copy.keys,0,keys.length);
+ SymbMap copy = (SymbMap) super.clone();
+ copy.entries = new NameSpaceSymbEntry[entries.length];
+ System.arraycopy(entries, 0, copy.entries, 0, entries.length);
+ copy.keys = new String[keys.length];
+ System.arraycopy(keys, 0, copy.keys, 0, keys.length);
- return copy;
+ return copy;
} catch (CloneNotSupportedException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
return null;
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java Fri Jul 05 14:37:41 2013 -0700
@@ -1,3 +1,25 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
@@ -6,150 +28,153 @@
public class UtfHelpper {
- final static void writeByte(final String str,final OutputStream out,Map<String,byte[]> 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<String, byte[]> cache
+ ) throws IOException {
+ byte[] result = cache.get(str);
+ if (result == null) {
+ result = getStringInUtf8(str);
+ cache.put(str, result);
+ }
- out.write(result);
+ out.write(result);
+ }
- }
+ static final void writeCharToUtf8(final char c, final OutputStream out) throws IOException {
+ if (c < 0x80) {
+ out.write(c);
+ return;
+ }
+ if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
+ //No Surrogates in sun java
+ out.write(0x3f);
+ return;
+ }
+ int bias;
+ int write;
+ char ch;
+ if (c > 0x07FF) {
+ ch = (char)(c>>>12);
+ write = 0xE0;
+ if (ch > 0) {
+ write |= (ch & 0x0F);
+ }
+ out.write(write);
+ write = 0x80;
+ bias = 0x3F;
+ } else {
+ write = 0xC0;
+ bias = 0x1F;
+ }
+ ch = (char)(c>>>6);
+ if (ch > 0) {
+ write |= (ch & bias);
+ }
+ out.write(write);
+ out.write(0x80 | ((c) & 0x3F));
- final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{
- if (c < 0x80) {
+ }
+
+ static final void writeStringToUtf8(
+ final String str,
+ final OutputStream out
+ ) throws IOException{
+ final int length = str.length();
+ int i = 0;
+ char c;
+ while (i < length) {
+ c = str.charAt(i++);
+ if (c < 0x80) {
out.write(c);
- return;
+ continue;
}
- if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
+ if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
//No Surrogates in sun java
out.write(0x3f);
- return;
- }
+ continue;
+ }
+ char ch;
int bias;
int write;
- char ch;
if (c > 0x07FF) {
- ch=(char)(c>>>12);
- write=0xE0;
- if (ch>0) {
- write |= ( ch & 0x0F);
+ ch = (char)(c>>>12);
+ write = 0xE0;
+ if (ch > 0) {
+ write |= (ch & 0x0F);
}
out.write(write);
- write=0x80;
- bias=0x3F;
+ write = 0x80;
+ bias = 0x3F;
} else {
- write=0xC0;
- bias=0x1F;
+ 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<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);
- 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<length) {
- c=str.charAt(i++);
- if ( c < 0x80 ) {
- result[out++]=(byte)c;
- continue;
- }
- if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
- //No Surrogates in sun java
- result[out++]=0x3f;
-
- continue;
- }
- if (!expanded) {
- byte newResult[]=new byte[3*length];
- System.arraycopy(result, 0, newResult, 0, out);
- result=newResult;
- expanded=true;
- }
- char ch;
- int bias;
- byte write;
- if (c > 0x07FF) {
- ch=(char)(c>>>12);
- write=(byte)0xE0;
- if (ch>0) {
- write |= ( ch & 0x0F);
- }
- result[out++]=write;
- write=(byte)0x80;
- bias=0x3F;
- } else {
- write=(byte)0xC0;
- bias=0x1F;
- }
- ch=(char)(c>>>6);
- if (ch>0) {
- write|= (ch & bias);
- }
- result[out++]=write;
- result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/
-
- }
- if (expanded) {
- byte newResult[]=new byte[out];
- System.arraycopy(result, 0, newResult, 0, out);
- result=newResult;
- }
- return result;
- }
-
-
+ public static final byte[] getStringInUtf8(final String str) {
+ final int length = str.length();
+ boolean expanded = false;
+ byte[] result = new byte[length];
+ int i = 0;
+ int out = 0;
+ char c;
+ while (i < length) {
+ c = str.charAt(i++);
+ if (c < 0x80) {
+ result[out++] = (byte)c;
+ continue;
+ }
+ if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF)) {
+ //No Surrogates in sun java
+ result[out++] = 0x3f;
+ continue;
+ }
+ if (!expanded) {
+ byte newResult[] = new byte[3*length];
+ System.arraycopy(result, 0, newResult, 0, out);
+ result = newResult;
+ expanded = true;
+ }
+ char ch;
+ int bias;
+ byte write;
+ if (c > 0x07FF) {
+ ch = (char)(c>>>12);
+ write = (byte)0xE0;
+ if (ch > 0) {
+ write |= (ch & 0x0F);
+ }
+ result[out++] = write;
+ write = (byte)0x80;
+ bias = 0x3F;
+ } else {
+ write = (byte)0xC0;
+ bias = 0x1F;
+ }
+ ch = (char)(c>>>6);
+ if (ch > 0) {
+ write |= (ch & bias);
+ }
+ result[out++] = write;
+ result[out++] = (byte)(0x80 | ((c) & 0x3F));
+ }
+ if (expanded) {
+ byte newResult[] = new byte[out];
+ System.arraycopy(result, 0, newResult, 0, out);
+ result = newResult;
+ }
+ return result;
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>String</code>s into <code>Node</code>s 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 <code>String</code> representation of the specified
+ * <code>Element</code>.
+ * <p/>
+ * Refer also to comments about setup of format.
+ *
+ * @param element the <code>Element</code> to serialize.
+ * @return the <code>String</code> representation of the serilaized
+ * <code>Element</code>.
+ * @throws Exception
+ */
+ public String serialize(Element element) throws Exception {
+ return canonSerialize(element);
+ }
+
+ /**
+ * Returns a <code>byte[]</code> representation of the specified
+ * <code>Element</code>.
+ *
+ * @param element the <code>Element</code> to serialize.
+ * @return the <code>byte[]</code> representation of the serilaized
+ * <code>Element</code>.
+ * @throws Exception
+ */
+ public byte[] serializeToByteArray(Element element) throws Exception {
+ return canonSerializeToByteArray(element);
+ }
+
+ /**
+ * Returns a <code>String</code> representation of the specified
+ * <code>NodeList</code>.
+ * <p/>
+ * This is a special case because the NodeList may represent a
+ * <code>DocumentFragment</code>. 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.
+ * <p/>
+ * 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.
+ * <p/>
+ * Refer also to comments about setup of format.
+ *
+ * @param content the <code>NodeList</code> to serialize.
+ * @return the <code>String</code> representation of the serialized
+ * <code>NodeList</code>.
+ * @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 <code>byte[]</code> representation of the specified
+ * <code>NodeList</code>.
+ *
+ * @param content the <code>NodeList</code> to serialize.
+ * @return the <code>byte[]</code> representation of the serialized
+ * <code>NodeList</code>.
+ * @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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
+
+ // Run through each node up to the document node and find any xmlns: nodes
+ Map<String, String> storedNamespaces = new HashMap<String, String>();
+ 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("</dummy>");
+ 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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
+
+ // Run through each node up to the document node and find any xmlns: nodes
+ Map<String, String> storedNamespaces = new HashMap<String, String>();
+ 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 + "</dummy>");
+ return sb.toString();
+ }
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AgreementMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
import org.w3c.dom.Element;
-
/**
* A Key Agreement algorithm provides for the derivation of a shared secret key
* based on a shared secret computed from certain types of compatible public
@@ -79,9 +79,10 @@
* @author Axl Mattheus
*/
public interface AgreementMethod {
+
/**
- * Returns an <code>byte</code> array.
- * @return
+ * Returns a <code>byte</code> array.
+ * @return a <code>byte</code> array.
*/
byte[] getKANonce();
@@ -92,8 +93,8 @@
void setKANonce(byte[] kanonce);
/**
- * Returns aditional information regarding the <code>AgreementMethod</code>.
- * @return
+ * Returns additional information regarding the <code>AgreementMethod</code>.
+ * @return additional information regarding the <code>AgreementMethod</code>.
*/
Iterator<Element> getAgreementMethodInformation();
@@ -134,7 +135,7 @@
void setOriginatorKeyInfo(KeyInfo keyInfo);
/**
- * Retruns information relating to the recipient's shared secret.
+ * Returns information relating to the recipient's shared secret.
*
* @return information relating to the recipient's shared secret.
*/
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,25 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
/**
* <code>CipherData</code> provides encrypted data. It must either contain the
* encrypted octet sequence as base64 encoded text of the
@@ -42,10 +43,12 @@
* @author Axl Mattheus
*/
public interface CipherData {
+
/** VALUE_TYPE ASN */
- public static final int VALUE_TYPE = 0x00000001;
+ int VALUE_TYPE = 0x00000001;
+
/** REFERENCE_TYPE ASN */
- public static final int REFERENCE_TYPE = 0x00000002;
+ int REFERENCE_TYPE = 0x00000002;
/**
* Returns the type of encrypted data contained in the
@@ -76,18 +79,17 @@
* Returns a reference to an external location containing the encrypted
* octet sequence (<code>byte</code> 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 <code>CipherData</code>'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;
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,34 +2,34 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
import org.w3c.dom.Attr;
-
/**
* <code>CipherReference</code> identifies a source which, when processed,
* yields the encrypted octet sequence.
* <p>
* The actual value is obtained as follows. The <code>CipherReference URI</code>
* contains an identifier that is dereferenced. Should the
- * <code>CipherReference</code> element contain an OPTIONAL sequence of
* Transforms, the data resulting from dereferencing the <code>URI</code> is
* transformed as specified so as to yield the intended cipher value. For
* example, if the value is base64 encoded within an XML document; the
@@ -62,20 +62,21 @@
/**
* Returns an <code>URI</code> that contains an identifier that should be
* dereferenced.
- * @return
+ * @return an <code>URI</code> 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 <code>Transforms</code> that specifies how to transform the
- * <code>URI</code> to yield the appropiate cipher value.
+ * <code>URI</code> to yield the appropriate cipher value.
*
* @return the transform that specifies how to transform the reference to
* yield the intended cipher value.
@@ -84,10 +85,11 @@
/**
* Sets the <code>Transforms</code> that specifies how to transform the
- * <code>URI</code> to yield the appropiate cipher value.
+ * <code>URI</code> to yield the appropriate cipher value.
*
* @param transforms the set of <code>Transforms</code> that specifies how
* to transform the reference to yield the intended cipher value.
*/
void setTransforms(Transforms transforms);
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,25 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
/**
* <code>CipherValue</code> is the wrapper for cipher text.
*
@@ -28,20 +29,18 @@
*/
public interface CipherValue {
/**
- * Resturns the Base 64 encoded, encrypted octets that is the
- * <code>CihperValue</code>.
+ * Returns the Base 64 encoded, encrypted octets that is the
+ * <code>CipherValue</code>.
*
* @return cipher value.
*/
- String getValue();
- // byte[] getValue();
+ String getValue();
/**
* Sets the Base 64 encoded, encrypted octets that is the
- * <code>CihperValue</code>.
+ * <code>CipherValue</code>.
*
* @param value the cipher value.
*/
- void setValue(String value);
- // void setValue(byte[] value);
+ void setValue(String value);
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>String</code>s into <code>Node</code>s 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);
+ }
+ }
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,25 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
/**
* The <code>EncryptedData</code> element is the core element in the syntax. Not
* only does its <code>CipherData</code> child contain the encrypted data, but
@@ -42,3 +43,4 @@
*/
public interface EncryptedData extends EncryptedType {
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
-
/**
* The <code>EncryptedKey</code> element is used to transport encryption keys
* from the originator to a known recipient(s). It may be used as a stand-alone
@@ -51,9 +51,9 @@
* @author Axl Mattheus
*/
public interface EncryptedKey extends EncryptedType {
+
/**
- * Returns a hint as to which recipient this encrypted key value is intended
- * for.
+ * Returns a hint as to which recipient this encrypted key value is intended for.
*
* @return the recipient of the <code>EncryptedKey</code>.
*/
@@ -110,3 +110,4 @@
*/
void setCarriedName(String name);
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
-
/**
* EncryptedType is the abstract type from which <code>EncryptedData</code> and
* <code>EncryptedKey</code> are derived. While these two latter element types
@@ -50,6 +50,7 @@
* @author Axl Mattheus
*/
public interface EncryptedType {
+
/**
* Returns a <code>String</code> providing for the standard method of
* assigning an id to the element within the document context.
@@ -61,7 +62,7 @@
/**
* Sets the id.
*
- * @param id.
+ * @param id
*/
void setId(String id);
@@ -117,7 +118,7 @@
void setMimeType(String type);
/**
- * Retusn an <code>URI</code> representing the encoding of the
+ * Return an <code>URI</code> representing the encoding of the
* <code>EncryptedType</code>.
*
* @return the encoding of this <code>EncryptedType</code>.
@@ -128,7 +129,7 @@
* Sets the <code>URI</code> representing the encoding of the
* <code>EncryptedType</code>.
*
- * @param encoding.
+ * @param encoding
*/
void setEncoding(String encoding);
@@ -189,7 +190,8 @@
* Sets the <code>EncryptionProperties</code> that supplies additional
* information about the generation of the <code>EncryptedType</code>.
*
- * @param properties.
+ * @param properties
*/
void setEncryptionProperties(EncryptionProperties properties);
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,29 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.util.Iterator;
import org.w3c.dom.Element;
-
/**
* <code>EncryptionMethod</code> describes the encryption algorithm applied to
* the cipher data. If the element is absent, the encryption algorithm must be
@@ -83,6 +83,30 @@
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
* <code>EncryptionMethod</code>.
*
@@ -106,3 +130,4 @@
*/
void removeEncryptionMethodInformation(Element information);
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.util.Iterator;
-
/**
* <code>EncryptionProperties</code> can hold additional information concerning
* the generation of the <code>EncryptedData</code> or
@@ -46,6 +46,7 @@
* @author Axl Mattheus
*/
public interface EncryptionProperties {
+
/**
* Returns the <code>EncryptionProperties</code>' id.
*
@@ -72,14 +73,15 @@
/**
* Adds an <code>EncryptionProperty</code>.
*
- * @param property.
+ * @param property
*/
void addEncryptionProperty(EncryptionProperty property);
/**
* Removes the specified <code>EncryptionProperty</code>.
*
- * @param property.
+ * @param property
*/
void removeEncryptionProperty(EncryptionProperty property);
}
+
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,25 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.util.Iterator;
import org.w3c.dom.Element;
@@ -50,6 +51,7 @@
* @author Axl Mattheus
*/
public interface EncryptionProperty {
+
/**
* Returns the <code>EncryptedType</code> being described.
*
@@ -61,7 +63,7 @@
/**
* Sets the target.
*
- * @param target.
+ * @param target
*/
void setTarget(String target);
@@ -75,7 +77,7 @@
/**
* Sets the id.
*
- * @param id.
+ * @param id
*/
void setId(String id);
@@ -98,7 +100,7 @@
/**
* Returns the properties of the <CODE>EncryptionProperty</CODE>.
*
- * @return an <code>Iterator</code> over all the addiitonal encryption
+ * @return an <code>Iterator</code> over all the additional encryption
* information contained in this class.
*/
Iterator<Element> getEncryptionInformation();
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,29 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.util.Iterator;
import org.w3c.dom.Element;
-
/**
* A wrapper for a pointer from a key value of an <code>EncryptedKey</code> to
* items encrypted by that key value (<code>EncryptedData</code> or
@@ -45,6 +45,13 @@
*/
public interface Reference {
/**
+ * Returns the <code>Element</code> tag name for this <code>Reference</code>.
+ *
+ * @return the tag name of this <code>Reference</code>.
+ */
+ String getType();
+
+ /**
* Returns a <code>URI</code> that points to an <code>Element</code> that
* were encrypted using the key defined in the enclosing
* <code>EncryptedKey</code> element.
@@ -79,14 +86,14 @@
/**
* Adds retrieval information.
*
- * @param info.
+ * @param info
*/
void addElementRetrievalInformation(Element info);
/**
* Removes the specified retrieval information.
*
- * @param info.
+ * @param info
*/
void removeElementRetrievalInformation(Element info);
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.util.Iterator;
-
/**
* <code>ReferenceList</code> is an element that contains pointers from a key
* value of an <code>EncryptedKey</code> to items encrypted by that key value
@@ -45,10 +45,12 @@
* @see Reference
*/
public interface ReferenceList {
- /** DATA TAG */
- public static final int DATA_REFERENCE = 0x00000001;
+
+ /** DATA TAG */
+ int DATA_REFERENCE = 0x00000001;
+
/** KEY TAG */
- public static final int KEY_REFERENCE = 0x00000002;
+ int KEY_REFERENCE = 0x00000002;
/**
* Adds a reference to this reference list.
@@ -57,21 +59,21 @@
* @throws IllegalAccessException if the <code>Reference</code> is not an
* instance of <code>DataReference</code> or <code>KeyReference</code>.
*/
- public void add(Reference reference);
+ void add(Reference reference);
/**
* Removes a reference from the <code>ReferenceList</code>.
*
* @param reference the reference to remove.
*/
- public void remove(Reference reference);
+ void remove(Reference reference);
/**
* Returns the size of the <code>ReferenceList</code>.
*
* @return the size of the <code>ReferenceList</code>.
*/
- public int size();
+ int size();
/**
* Indicates if the <code>ReferenceList</code> is empty.
@@ -79,29 +81,29 @@
* @return <code><b>true</b></code> if the <code>ReferenceList</code> is
* empty, else <code><b>false</b></code>.
*/
- public boolean isEmpty();
+ boolean isEmpty();
/**
* Returns an <code>Iterator</code> over all the <code>Reference</code>s
- * contatined in this <code>ReferenceList</code>.
+ * contained in this <code>ReferenceList</code>.
*
* @return Iterator.
*/
- public Iterator<Reference> getReferences();
+ Iterator<Reference> getReferences();
/**
* <code>DataReference</code> factory method. Returns a
* <code>DataReference</code>.
* @param uri
- * @return
+ * @return a <code>DataReference</code>.
*/
- public Reference newDataReference(String uri);
+ Reference newDataReference(String uri);
/**
* <code>KeyReference</code> factory method. Returns a
* <code>KeyReference</code>.
* @param uri
- * @return
+ * @return a <code>KeyReference</code>.
*/
- public Reference newKeyReference(String uri);
+ Reference newKeyReference(String uri);
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>String</code>s into <code>Node</code>s and visa versa.
+ */
+public interface Serializer {
+
+ /**
+ * Set the Canonicalizer object to use.
+ */
+ void setCanonicalizer(Canonicalizer canon);
+
+ /**
+ * Returns a <code>byte[]</code> representation of the specified
+ * <code>Element</code>.
+ *
+ * @param element the <code>Element</code> to serialize.
+ * @return the <code>byte[]</code> representation of the serilaized
+ * <code>Element</code>.
+ * @throws Exception
+ */
+ byte[] serializeToByteArray(Element element) throws Exception;
+
+ /**
+ * Returns a <code>byte[]</code> representation of the specified
+ * <code>NodeList</code>.
+ *
+ * @param content the <code>NodeList</code> to serialize.
+ * @return the <code>byte[]</code> representation of the serialized
+ * <code>NodeList</code>.
+ * @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;
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
-
-
/**
* A container for <code>ds:Transform</code>s.
* <p>
@@ -40,36 +39,12 @@
*/
public interface Transforms {
/**
- * Returns an <code>Iterator</code> over all the transforms contained in
- * this transform list.
- *
- * @return all transforms.
- */
- /* Iterator getTransforms(); */
-
- /**
- * Adds a <code>ds:Transform</code> to the list of transforms.
- *
- * @param transform.
+ * Temporary method to turn the XMLEncryption Transforms class
+ * into a DS class. The main logic is currently implemented in the
+ * DS class, so we need to get to get the base class.
+ * <p>
+ * <b>Note</b> This will be removed in future versions
*/
- /* void addTransform(Transform transform); */
-
- /**
- * Removes the specified transform.
- *
- * @param transform.
- */
- /* void removeTransform(Transform transform); */
-
- /**
- * Temporary method to turn the XMLEncryption Transforms class
- * into a DS class. The main logic is currently implemented in the
- * DS class, so we need to get to get the base class.
- * <p>
- * <b>Note</b> 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();
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,57 +2,62 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
-
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
-import java.io.IOException;
-import java.io.StringReader;
import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
+import java.security.SecureRandom;
+import java.security.spec.MGF1ParameterSpec;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
+import javax.crypto.spec.OAEPParameterSpec;
+import javax.crypto.spec.PSource;
import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
+import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.EncryptedKeyResolver;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
@@ -62,17 +67,11 @@
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import com.sun.org.apache.xml.internal.utils.URI;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
-import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
/**
* <code>XMLCipher</code> encrypts and decrypts the contents of
@@ -85,133 +84,245 @@
*/
public class XMLCipher {
- private static java.util.logging.Logger logger =
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(XMLCipher.class.getName());
- //J-
- /** Triple DES EDE (192 bit key) in CBC mode */
+ /** 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";
-
- /** Cipher created during initialisation that is used for encryption */
- private Cipher _contextCipher;
- /** Mode that the XMLCipher object is operating in */
- private int _cipherMode = Integer.MIN_VALUE;
- /** URI of algorithm that is being used for cryptographic operation */
- private String _algorithm = null;
- /** Cryptographic provider requested by caller */
- private String _requestedJCEProvider = null;
- /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */
- private Canonicalizer _canon;
- /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */
- private Document _contextDocument;
- /** Instance of factory used to create XML Encryption objects */
- private Factory _factory;
- /** Internal serializer class for going to/from UTF-8 */
- private Serializer _serializer;
-
- /** Local copy of user's key */
- private Key _key;
- /** Local copy of the kek (used to decrypt EncryptedKeys during a
+ AES_128 + "\n" + AES_256 + "\n" + AES_192 + "\n" + RSA_v1dot5 + "\n" +
+ RSA_OAEP + "\n" + RSA_OAEP_11 + "\n" + TRIPLEDES_KeyWrap + "\n" +
+ AES_128_KeyWrap + "\n" + AES_256_KeyWrap + "\n" + AES_192_KeyWrap + "\n" +
+ AES_128_GCM + "\n" + AES_192_GCM + "\n" + AES_256_GCM + "\n";
+
+ /** Cipher created during initialisation that is used for encryption */
+ private Cipher contextCipher;
+
+ /** Mode that the XMLCipher object is operating in */
+ private int cipherMode = Integer.MIN_VALUE;
+
+ /** URI of algorithm that is being used for cryptographic operation */
+ private String algorithm = null;
+
+ /** Cryptographic provider requested by caller */
+ private String requestedJCEProvider = null;
+
+ /** Holds c14n to serialize, if initialized then _always_ use this c14n to serialize */
+ private Canonicalizer canon;
+
+ /** Used for creation of DOM nodes in WRAP and ENCRYPT modes */
+ private Document contextDocument;
+
+ /** Instance of factory used to create XML Encryption objects */
+ private Factory factory;
+
+ /** Serializer class for going to/from UTF-8 */
+ private Serializer serializer;
+
+ /** Local copy of user's key */
+ private Key key;
+
+ /** Local copy of the kek (used to decrypt EncryptedKeys during a
* DECRYPT_MODE operation */
- private Key _kek;
-
- // The EncryptedKey being built (part of a WRAP operation) or read
- // (part of an UNWRAP operation)
-
- private EncryptedKey _ek;
-
- // The EncryptedData being built (part of a WRAP operation) or read
- // (part of an UNWRAP operation)
-
- private EncryptedData _ed;
+ private Key kek;
+
+ // The EncryptedKey being built (part of a WRAP operation) or read
+ // (part of an UNWRAP operation)
+ private EncryptedKey ek;
+
+ // The EncryptedData being built (part of a WRAP operation) or read
+ // (part of an UNWRAP operation)
+ private EncryptedData ed;
+
+ private SecureRandom random;
+
+ private boolean secureValidation;
+
+ private String digestAlg;
+
+ /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */
+ private List<KeyResolverSpi> 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 <code>XMLCipher</code>.
*
- * @since 1.0.
+ * @param transformation the name of the transformation, e.g.,
+ * <code>XMLCipher.TRIPLEDES</code>. If null the XMLCipher can only
+ * be used for decrypt or unwrap operations where the encryption method
+ * is defined in the <code>EncryptionMethod</code> 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
+ * <code>null</code> use standard serializer
+ * @param digestMethod An optional digestMethod to use.
*/
- private XMLCipher() {
- logger.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
-
- _factory = new Factory();
- _serializer = new Serializer();
-
+ private XMLCipher(
+ String transformation,
+ String provider,
+ String canonAlg,
+ String digestMethod
+ ) throws XMLEncryptionException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Constructing XMLCipher...");
+ }
+
+ factory = new Factory();
+
+ algorithm = transformation;
+ requestedJCEProvider = provider;
+ digestAlg = digestMethod;
+
+ // Create a canonicalizer - used when serializing DOM to octets
+ // prior to encryption (and for the reverse)
+
+ try {
+ if (canonAlg == null) {
+ // The default is to preserve the physical representation.
+ this.canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_PHYSICAL);
+ } else {
+ this.canon = Canonicalizer.getInstance(canonAlg);
+ }
+ } catch (InvalidCanonicalizerException ice) {
+ throw new XMLEncryptionException("empty", ice);
+ }
+
+ if (serializer == null) {
+ serializer = new DocumentSerializer();
+ }
+ serializer.setCanonicalizer(this.canon);
+
+ if (transformation != null) {
+ contextCipher = constructCipher(transformation, digestMethod);
+ }
}
/**
@@ -222,20 +333,38 @@
* @since 1.0.
*/
private static boolean isValidEncryptionAlgorithm(String algorithm) {
- boolean result = (
+ return (
algorithm.equals(TRIPLEDES) ||
algorithm.equals(AES_128) ||
algorithm.equals(AES_256) ||
algorithm.equals(AES_192) ||
+ algorithm.equals(AES_128_GCM) ||
+ algorithm.equals(AES_192_GCM) ||
+ algorithm.equals(AES_256_GCM) ||
algorithm.equals(RSA_v1dot5) ||
algorithm.equals(RSA_OAEP) ||
+ algorithm.equals(RSA_OAEP_11) ||
algorithm.equals(TRIPLEDES_KeyWrap) ||
algorithm.equals(AES_128_KeyWrap) ||
algorithm.equals(AES_256_KeyWrap) ||
algorithm.equals(AES_192_KeyWrap)
);
-
- return (result);
+ }
+
+ /**
+ * Validate the transformation argument of getInstance or getProviderInstance
+ *
+ * @param transformation the name of the transformation, e.g.,
+ * <code>XMLCipher.TRIPLEDES</code> which is shorthand for
+ * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"
+ */
+ private static void validateTransformation(String transformation) {
+ if (null == transformation) {
+ throw new NullPointerException("Transformation unexpectedly null...");
+ }
+ if (!isValidEncryptionAlgorithm(transformation)) {
+ log.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
+ }
}
/**
@@ -248,7 +377,7 @@
* the default provider package, other provider packages are searched.
* <p>
* <b>NOTE<sub>1</sub>:</b> The transformation name does not follow the same
- * pattern as that oulined in the Java Cryptography Extension Reference
+ * pattern as that outlined in the Java Cryptography Extension Reference
* Guide but rather that specified by the XML Encryption Syntax and
* Processing document. The rational behind this is to make it easier for a
* novice at writing Java Encryption software to use the library.
@@ -257,7 +386,7 @@
* same pattern regarding exceptional conditions as that used in
* <code>javax.crypto.Cipher</code>. Instead, it only throws an
* <code>XMLEncryptionException</code> 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.,
* <code>XMLCipher.TRIPLEDES</code> which is shorthand for
@@ -266,293 +395,169 @@
* @return the XMLCipher
* @see javax.crypto.Cipher#getInstance(java.lang.String)
*/
- public static XMLCipher getInstance(String transformation) throws
- XMLEncryptionException {
- // sanity checks
- logger.log(java.util.logging.Level.FINE, "Getting XMLCipher...");
- if (null == transformation)
- logger.log(java.util.logging.Level.SEVERE, "Transformation unexpectedly null...");
- if(!isValidEncryptionAlgorithm(transformation))
- logger.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS);
-
- XMLCipher instance = new XMLCipher();
-
- instance._algorithm = transformation;
- instance._key = null;
- instance._kek = null;
-
-
- /* Create a canonicaliser - used when serialising DOM to octets
- * prior to encryption (and for the reverse) */
-
- try {
- instance._canon = Canonicalizer.getInstance
- (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
-
- } catch (InvalidCanonicalizerException ice) {
- throw new XMLEncryptionException("empty", ice);
- }
-
- String jceAlgorithm = JCEMapper.translateURItoJCEID(transformation);
-
- try {
- instance._contextCipher = Cipher.getInstance(jceAlgorithm);
- logger.log(java.util.logging.Level.FINE, "cihper.algoritm = " +
- instance._contextCipher.getAlgorithm());
- } catch (NoSuchAlgorithmException nsae) {
- throw new XMLEncryptionException("empty", nsae);
- } catch (NoSuchPaddingException nspe) {
- throw new XMLEncryptionException("empty", nspe);
+ public static XMLCipher getInstance(String transformation) throws XMLEncryptionException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation");
}
-
- return (instance);
+ validateTransformation(transformation);
+ return new XMLCipher(transformation, null, null, null);
}
- /**
- * Returns an <code>XMLCipher</code> 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.
- * <p>
- *
- * @param transformation the name of the transformation, e.g.,
- * <code>XMLCipher.TRIPLEDES</code> which is
- * shorthand for
- * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"
- * @param canon the name of the c14n algorithm, if
- * <code>null</code> 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 <code>XMLCipher</code> 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.
+ * <p>
+ *
+ * @param transformation the name of the transformation
+ * @param canon the name of the c14n algorithm, if <code>null</code> 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");
}
-
- 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);
+ validateTransformation(transformation);
+ return new XMLCipher(transformation, null, canon, null);
+ }
+
+ /**
+ * Returns an <code>XMLCipher</code> 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.
+ * <p>
+ *
+ * @param transformation the name of the transformation
+ * @param canon the name of the c14n algorithm, if <code>null</code> 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 <code>XMLCipher</code> that implements the specified
* transformation and operates on the specified context document.
*
- * @param transformation the name of the transformation, e.g.,
- * <code>XMLCipher.TRIPLEDES</code> 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");
+ }
+ if (null == provider) {
+ throw new NullPointerException("Provider unexpectedly null..");
}
-
- return (instance);
+ validateTransformation(transformation);
+ return new XMLCipher(transformation, provider, null, null);
}
- /**
- * Returns an <code>XMLCipher</code> that implements the specified
+ /**
+ * Returns an <code>XMLCipher</code> 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.
+ * <p>
+ *
+ * @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 <code>null</code> use standard
+ * serializer
+ * @return the XMLCipher
+ * @throws XMLEncryptionException
+ */
+ public static XMLCipher getProviderInstance(
+ String transformation, String provider, String canon
+ ) throws XMLEncryptionException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm");
+ }
+ if (null == provider) {
+ throw new NullPointerException("Provider unexpectedly null..");
+ }
+ validateTransformation(transformation);
+ return new XMLCipher(transformation, provider, canon, null);
+ }
+
+ /**
+ * Returns an <code>XMLCipher</code> 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.
* <p>
- *
- * @param transformation the name of the transformation, e.g.,
- * <code>XMLCipher.TRIPLEDES</code> 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
- * <code>null</code> 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 <code>XMLCipher</code> that implements no specific
- * transformation, and can therefore only be used for decrypt or
- * unwrap operations where the encryption method is defined in the
- * <code>EncryptionMethod</code> 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 <code>null</code> use standard
+ * serializer
+ * @param digestMethod An optional digestMethod to use
+ * @return the XMLCipher
* @throws XMLEncryptionException
*/
-
- public static XMLCipher getInstance()
- throws XMLEncryptionException {
- // sanity checks
- logger.log(java.util.logging.Level.FINE, "Getting XMLCipher for no transformation...");
-
- XMLCipher instance = new XMLCipher();
-
- instance._algorithm = null;
- instance._requestedJCEProvider = null;
- instance._key = null;
- instance._kek = null;
- instance._contextCipher = null;
-
- /* Create a canonicaliser - used when serialising DOM to octets
- * prior to encryption (and for the reverse) */
-
- try {
- instance._canon = Canonicalizer.getInstance
- (Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
- } catch (InvalidCanonicalizerException ice) {
- throw new XMLEncryptionException("empty", ice);
- }
-
- return (instance);
+ public static XMLCipher 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 <code>XMLCipher</code> that implements no specific
- * transformation, and can therefore only be used for decrypt or
- * unwrap operations where the encryption method is defined in the
- * <code>EncryptionMethod</code> 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
+ * <code>EncryptionMethod</code> 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 <code>XMLCipher</code> that implements no specific
+ * transformation, and can therefore only be used for decrypt or
+ * unwrap operations where the encryption method is defined in the
+ * <code>EncryptionMethod</code> 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 @@
* 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 void init(int opmode, Key key) throws XMLEncryptionException {
// sanity checks
- logger.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
-
- _ek = null;
- _ed = null;
-
- switch (opmode) {
-
- case ENCRYPT_MODE :
- logger.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
- _ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
- break;
- case DECRYPT_MODE :
- logger.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
- break;
- case WRAP_MODE :
- logger.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
- _ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
- break;
- case UNWRAP_MODE :
- logger.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
- break;
- default :
- logger.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid");
- throw new XMLEncryptionException("Invalid mode in init");
- }
-
- _cipherMode = opmode;
- _key = key;
-
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Initializing XMLCipher...");
+ }
+
+ ek = null;
+ ed = null;
+
+ switch (opmode) {
+
+ case ENCRYPT_MODE :
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "opmode = ENCRYPT_MODE");
+ }
+ ed = createEncryptedData(CipherData.VALUE_TYPE, "NO VALUE YET");
+ break;
+ case DECRYPT_MODE :
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "opmode = DECRYPT_MODE");
+ }
+ break;
+ case WRAP_MODE :
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "opmode = WRAP_MODE");
+ }
+ ek = createEncryptedKey(CipherData.VALUE_TYPE, "NO VALUE YET");
+ break;
+ case UNWRAP_MODE :
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "opmode = UNWRAP_MODE");
+ }
+ break;
+ default :
+ log.log(java.util.logging.Level.SEVERE, "Mode unexpectedly invalid");
+ throw new XMLEncryptionException("Invalid mode in init");
+ }
+
+ cipherMode = opmode;
+ this.key = key;
+ }
+
+ /**
+ * Set whether secure validation is enabled or not. The default is false.
+ */
+ public void setSecureValidation(boolean secureValidation) {
+ this.secureValidation = secureValidation;
}
- /**
- * 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;
-
+ /**
+ * 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<KeyResolverSpi>();
}
-
- /**
- * 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;
+ internalKeyResolvers.add(keyResolver);
+ }
+
+ /**
+ * Get the EncryptedData being built
+ * <p>
+ * 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;
+ }
+
+ /**
+ * 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");
}
-
- /**
- * Set a Key Encryption Key.
- * <p>
- * 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;
-
- }
-
- /**
- * Martial an EncryptedData
- *
- * Takes an EncryptedData object and returns a DOM Element that
- * represents the appropriate <code>EncryptedData</code>
- * <p>
- * <b>Note:</b> 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 <code>Element</code> representing the passed in
- * object
+ return ek;
+ }
+
+ /**
+ * Set a Key Encryption Key.
+ * <p>
+ * 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) {
+ this.kek = kek;
+ }
+
+ /**
+ * Martial an EncryptedData
+ *
+ * Takes an EncryptedData object and returns a DOM Element that
+ * represents the appropriate <code>EncryptedData</code>
+ * <p>
+ * <b>Note:</b> 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 <code>Element</code> 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 <code>EncryptedData</code>
+ *
+ * @param context The document that will own the returned nodes
+ * @param encryptedData EncryptedData object to martial
+ * @return the DOM <code>Element</code> representing the passed in
+ * object
*/
-
- public Element martial(EncryptedData encryptedData) {
-
- return (_factory.toElement (encryptedData));
-
- }
-
- /**
- * Martial an EncryptedKey
- *
- * Takes an EncryptedKey object and returns a DOM Element that
- * represents the appropriate <code>EncryptedKey</code>
- *
- * <p>
- * <b>Note:</b> 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 <code>Element</code> representing the passed in
- * object */
-
- public Element martial(EncryptedKey encryptedKey) {
-
- return (_factory.toElement (encryptedKey));
-
- }
-
- /**
- * Martial an EncryptedData
- *
- * Takes an EncryptedData object and returns a DOM Element that
- * represents the appropriate <code>EncryptedData</code>
- *
- * @param context The document that will own the returned nodes
- * @param encryptedData EncryptedData object to martial
- * @return the DOM <code>Element</code> 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 <code>EncryptedKey</code>
- *
- * @param context The document that will own the created nodes
- * @param encryptedKey EncryptedKey object to martial
- * @return the DOM <code>Element</code> representing the passed in
- * object */
-
- public Element martial(Document context, EncryptedKey encryptedKey) {
-
- _contextDocument = context;
- return (_factory.toElement (encryptedKey));
-
- }
+ 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 <code>EncryptedKey</code>
+ *
+ * <p>
+ * <b>Note:</b> 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 <code>Element</code> representing the passed in
+ * object
+ */
+ public Element martial(EncryptedKey encryptedKey) {
+ return factory.toElement(encryptedKey);
+ }
+
+ /**
+ * Martial an EncryptedKey
+ *
+ * Takes an EncryptedKey object and returns a DOM Element that
+ * represents the appropriate <code>EncryptedKey</code>
+ *
+ * @param context The document that will own the created nodes
+ * @param encryptedKey EncryptedKey object to martial
+ * @return the DOM <code>Element</code> 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 <code>ReferenceList</code>
+ *
+ * <p>
+ * <b>Note:</b> 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 <code>Element</code> representing the passed in
+ * object
+ */
+ public Element martial(ReferenceList referenceList) {
+ return factory.toElement(referenceList);
+ }
+
+ /**
+ * Martial a ReferenceList
+ *
+ * Takes a ReferenceList object and returns a DOM Element that
+ * represents the appropriate <code>ReferenceList</code>
+ *
+ * @param context The document that will own the created nodes
+ * @param referenceList ReferenceList object to martial
+ * @return the DOM <code>Element</code> representing the passed in
+ * object
+ */
+ public Element martial(Document context, ReferenceList referenceList) {
+ contextDocument = context;
+ return factory.toElement(referenceList);
+ }
/**
* Encrypts an <code>Element</code> and replaces it with its encrypted
@@ -747,25 +804,28 @@
* <code>Element</code> having replaced the source <code>Element</code>.
* @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 (_algorithm == null) {
- throw new XMLEncryptionException("XMLCipher instance without transformation specified");
- }
- encryptData(_contextDocument, element, false);
-
- Element encryptedElement = _factory.toElement(_ed);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Encrypting element...");
+ }
+ if (null == element) {
+ log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
+ }
+ if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+ }
+
+ if (algorithm == null) {
+ throw new XMLEncryptionException("XMLCipher instance without transformation specified");
+ }
+ encryptData(contextDocument, element, false);
+
+ Element encryptedElement = factory.toElement(ed);
Node sourceParent = element.getParentNode();
sourceParent.replaceChild(encryptedElement, element);
- return (_contextDocument);
+ return contextDocument;
}
/**
@@ -782,25 +842,28 @@
* <code>Element</code>.
* @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...");
-
- if (_algorithm == null) {
- throw new XMLEncryptionException("XMLCipher instance without transformation specified");
- }
- encryptData(_contextDocument, element, true);
-
- Element encryptedElement = _factory.toElement(_ed);
+ 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);
+
+ Element encryptedElement = factory.toElement(ed);
removeContent(element);
element.appendChild(encryptedElement);
- return (_contextDocument);
+ return contextDocument;
}
/**
@@ -812,19 +875,22 @@
* @return the processed <code>Document</code>.
* @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...");
-
- _contextDocument = context;
+ 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;
Document result = null;
- switch (_cipherMode) {
+ switch (cipherMode) {
case DECRYPT_MODE:
result = decryptElement(source.getDocumentElement());
break;
@@ -832,15 +898,13 @@
result = encryptElement(source.getDocumentElement());
break;
case UNWRAP_MODE:
- break;
case WRAP_MODE:
break;
default:
- throw new XMLEncryptionException(
- "empty", new IllegalStateException());
+ throw new XMLEncryptionException("empty", new IllegalStateException());
}
- return (result);
+ return result;
}
/**
@@ -852,19 +916,22 @@
* @return the processed <code>Document</code>.
* @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...");
-
- _contextDocument = context;
+ 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;
Document result = null;
- switch (_cipherMode) {
+ switch (cipherMode) {
case DECRYPT_MODE:
result = decryptElement(element);
break;
@@ -872,15 +939,13 @@
result = encryptElement(element);
break;
case UNWRAP_MODE:
- break;
case WRAP_MODE:
break;
default:
- throw new XMLEncryptionException(
- "empty", new IllegalStateException());
+ throw new XMLEncryptionException("empty", new IllegalStateException());
}
- return (result);
+ return result;
}
/**
@@ -896,18 +961,22 @@
* @throws Exception to indicate any exceptional conditions.
*/
public Document doFinal(Document context, Element element, boolean content)
- throws /* XMLEncryption*/ Exception {
- logger.log(java.util.logging.Level.FINE, "Processing source element...");
- if(null == context)
- logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
- if(null == element)
- logger.log(java.util.logging.Level.SEVERE, "Source element unexpectedly null...");
-
- _contextDocument = context;
+ 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;
Document result = null;
- switch (_cipherMode) {
+ switch (cipherMode) {
case DECRYPT_MODE:
if (content) {
result = decryptElementContent(element);
@@ -923,15 +992,13 @@
}
break;
case UNWRAP_MODE:
- break;
case WRAP_MODE:
break;
default:
- throw new XMLEncryptionException(
- "empty", new IllegalStateException());
+ throw new XMLEncryptionException("empty", new IllegalStateException());
}
- return (result);
+ return result;
}
/**
@@ -939,7 +1006,7 @@
* you want to have full control over the contents of the
* <code>EncryptedData</code> 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 <code>Document</code>.
* @param element the <code>Element</code> that will be encrypted.
@@ -947,7 +1014,7 @@
* @throws Exception
*/
public EncryptedData encryptData(Document context, Element element) throws
- /* XMLEncryption */Exception {
+ /* XMLEncryption */Exception {
return encryptData(context, element, false);
}
@@ -965,16 +1032,21 @@
* @return the <code>EncryptedData</code>
* @throws Exception
*/
- public EncryptedData encryptData(Document context, String type,
- InputStream serializedData) throws Exception {
-
- logger.log(java.util.logging.Level.FINE, "Encrypting element...");
- if (null == context)
- logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
- if (null == serializedData)
- logger.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null...");
- if (_cipherMode != ENCRYPT_MODE)
- logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+ public EncryptedData encryptData(
+ Document context, String type, InputStream serializedData
+ ) throws Exception {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Encrypting element...");
+ }
+ if (null == context) {
+ log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+ }
+ if (null == serializedData) {
+ log.log(java.util.logging.Level.SEVERE, "Serialized data unexpectedly null...");
+ }
+ if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+ }
return encryptData(context, null, type, serializedData);
}
@@ -984,7 +1056,7 @@
* you want to have full control over the contents of the
* <code>EncryptedData</code> 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 <code>Document</code>.
* @param element the <code>Element</code> that will be encrypted.
@@ -994,84 +1066,84 @@
* @throws Exception
*/
public EncryptedData encryptData(
- Document context, Element element, boolean contentMode)
- throws /* XMLEncryption */ Exception {
-
- logger.log(java.util.logging.Level.FINE, "Encrypting element...");
- if (null == context)
- logger.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
- if (null == element)
- logger.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
- if (_cipherMode != ENCRYPT_MODE)
- logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+ Document context, Element element, boolean contentMode
+ ) throws /* XMLEncryption */ Exception {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Encrypting element...");
+ }
+ if (null == context) {
+ log.log(java.util.logging.Level.SEVERE, "Context document unexpectedly null...");
+ }
+ if (null == element) {
+ log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
+ }
+ if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
+ }
if (contentMode) {
- return encryptData
- (context, element, EncryptionConstants.TYPE_CONTENT, null);
+ return encryptData(context, element, EncryptionConstants.TYPE_CONTENT, null);
} else {
- return encryptData
- (context, element, EncryptionConstants.TYPE_ELEMENT, null);
+ return encryptData(context, element, EncryptionConstants.TYPE_ELEMENT, null);
}
}
private EncryptedData encryptData(
- Document context, Element element, String type,
- InputStream serializedData) throws /* XMLEncryption */ Exception {
-
- _contextDocument = context;
-
- if (_algorithm == null) {
- throw new XMLEncryptionException
- ("XMLCipher instance without transformation specified");
+ Document context, Element element, String type, InputStream serializedData
+ ) throws /* XMLEncryption */ Exception {
+ contextDocument = context;
+
+ 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);
}
- logger.log(java.util.logging.Level.FINE, "Serialized octets:\n" + serializedOctets);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8"));
+ }
}
byte[] encryptedBytes = null;
// Now create the working cipher if none was created already
Cipher c;
- if (_contextCipher == null) {
- String jceAlgorithm = JCEMapper.translateURItoJCEID(_algorithm);
- logger.log(java.util.logging.Level.FINE, "alg = " + jceAlgorithm);
-
- try {
- if (_requestedJCEProvider == null)
- c = Cipher.getInstance(jceAlgorithm);
- else
- c = Cipher.getInstance(jceAlgorithm, _requestedJCEProvider);
- } catch (NoSuchAlgorithmException nsae) {
- throw new XMLEncryptionException("empty", nsae);
- } catch (NoSuchProviderException nspre) {
- throw new XMLEncryptionException("empty", nspre);
- } catch (NoSuchPaddingException nspae) {
- throw new XMLEncryptionException("empty", nspae);
- }
+ if (contextCipher == null) {
+ c = constructCipher(algorithm, null);
} else {
- c = _contextCipher;
+ c = contextCipher;
}
// Now perform the encryption
try {
- // Should internally generate an IV
- // todo - allow user to set an IV
- c.init(_cipherMode, _key);
+ // The Spec mandates a 96-bit IV for GCM algorithms
+ if (AES_128_GCM.equals(algorithm) || AES_192_GCM.equals(algorithm)
+ || AES_256_GCM.equals(algorithm)) {
+ if (random == null) {
+ random = SecureRandom.getInstance("SHA1PRNG");
+ }
+ byte[] temp = new byte[12];
+ random.nextBytes(temp);
+ IvParameterSpec paramSpec = new IvParameterSpec(temp);
+ c.init(cipherMode, key, paramSpec);
+ } else {
+ c.init(cipherMode, key);
+ }
} catch (InvalidKeyException ike) {
throw new XMLEncryptionException("empty", ike);
+ } catch (NoSuchAlgorithmException ex) {
+ throw new XMLEncryptionException("empty", ex);
}
try {
@@ -1086,13 +1158,16 @@
baos.write(c.doFinal());
encryptedBytes = baos.toByteArray();
} else {
- encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8"));
- logger.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
- Integer.toString(c.getOutputSize(
- serializedOctets.getBytes().length)));
+ encryptedBytes = c.doFinal(serializedOctets);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " +
+ Integer.toString(c.getOutputSize(serializedOctets.length)));
+ }
}
- logger.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " +
- Integer.toString(encryptedBytes.length));
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = "
+ + Integer.toString(encryptedBytes.length));
+ }
} catch (IllegalStateException ise) {
throw new XMLEncryptionException("empty", ise);
} catch (IllegalBlockSizeException ibse) {
@@ -1106,300 +1181,410 @@
// Now build up to a properly XML Encryption encoded octet stream
// IvParameterSpec iv;
byte[] iv = c.getIV();
- byte[] finalEncryptedBytes =
- new byte[iv.length + encryptedBytes.length];
+ byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length];
System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length);
- System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length,
- encryptedBytes.length);
+ System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length);
String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);
- logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
- logger.log(java.util.logging.Level.FINE, "Encrypted octets length = " +
- base64EncodedEncryptedOctets.length());
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
+ log.log(java.util.logging.Level.FINE, "Encrypted octets length = " + base64EncodedEncryptedOctets.length());
+ }
try {
- CipherData cd = _ed.getCipherData();
+ CipherData cd = ed.getCipherData();
CipherValue cv = cd.getCipherValue();
// cv.setValue(base64EncodedEncryptedOctets.getBytes());
cv.setValue(base64EncodedEncryptedOctets);
if (type != null) {
- _ed.setType(new URI(type).toString());
+ ed.setType(new URI(type).toString());
}
EncryptionMethod method =
- _factory.newEncryptionMethod(new URI(_algorithm).toString());
- _ed.setEncryptionMethod(method);
- } catch (URI.MalformedURIException mfue) {
- throw new XMLEncryptionException("empty", mfue);
+ factory.newEncryptionMethod(new URI(algorithm).toString());
+ method.setDigestAlgorithm(digestAlg);
+ ed.setEncryptionMethod(method);
+ } catch (URISyntaxException ex) {
+ throw new XMLEncryptionException("empty", ex);
}
- return (_ed);
+ return ed;
}
/**
* Returns an <code>EncryptedData</code> interface. Use this operation if
* you want to load an <code>EncryptedData</code> structure from a DOM
- * structure and manipulate the contents
+ * structure and manipulate the contents.
*
* @param context the context <code>Document</code>.
* @param element the <code>Element</code> that will be loaded
* @throws XMLEncryptionException
- * @return
+ * @return the <code>EncryptedData</code>
*/
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...");
-
- _contextDocument = context;
- _ed = _factory.newEncryptedData(element);
-
- return (_ed);
+ 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);
+
+ return ed;
}
/**
* Returns an <code>EncryptedKey</code> interface. Use this operation if
* you want to load an <code>EncryptedKey</code> structure from a DOM
- * structure and manipulate the contents.
+ * structure and manipulate the contents.
*
* @param context the context <code>Document</code>.
* @param element the <code>Element</code> that will be loaded
- * @return
+ * @return the <code>EncryptedKey</code>
* @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...");
-
- _contextDocument = context;
- _ek = _factory.newEncryptedKey(element);
- return (_ek);
+ 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;
}
/**
* Returns an <code>EncryptedKey</code> interface. Use this operation if
* you want to load an <code>EncryptedKey</code> 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 <code>Element</code> that will be loaded
- * @return
+ * @return the <code>EncryptedKey</code>
* @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 the <code>EncryptedKey</code>
+ * @throws XMLEncryptionException
+ */
+ public EncryptedKey encryptKey(Document doc, Key key) throws XMLEncryptionException {
+ return encryptKey(doc, key, null, null);
}
/**
* 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
+ * @param mgfAlgorithm The xenc11 MGF Algorithm to use
+ * @param oaepParams The OAEPParams to use
+ * @return the <code>EncryptedKey</code>
* @throws XMLEncryptionException
*/
-
- public EncryptedKey encryptKey(Document doc, Key key) throws
- XMLEncryptionException {
-
- logger.log(java.util.logging.Level.FINE, "Encrypting key ...");
-
- if(null == key)
- logger.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
- if(_cipherMode != WRAP_MODE)
- logger.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
-
- if (_algorithm == null) {
-
- throw new XMLEncryptionException("XMLCipher instance without transformation specified");
- }
-
- _contextDocument = doc;
-
- byte[] encryptedBytes = null;
- Cipher c;
-
- 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);
- }
+ public EncryptedKey encryptKey(
+ Document doc,
+ Key key,
+ String mgfAlgorithm,
+ byte[] oaepParams
+ ) throws XMLEncryptionException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Encrypting key ...");
+ }
+
+ if (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");
+ }
+
+ contextDocument = doc;
+
+ byte[] encryptedBytes = null;
+ Cipher c;
+
+ if (contextCipher == null) {
+ // Now create the working cipher
+ c = constructCipher(algorithm, null);
+ } else {
+ c = contextCipher;
+ }
+ // Now perform the encryption
+
+ try {
+ // Should internally generate an IV
+ // todo - allow user to set an IV
+ OAEPParameterSpec oaepParameters =
+ constructOAEPParameters(
+ algorithm, digestAlg, mgfAlgorithm, oaepParams
+ );
+ if (oaepParameters == null) {
+ c.init(Cipher.WRAP_MODE, this.key);
+ } else {
+ c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
+ }
+ encryptedBytes = c.wrap(key);
+ } catch (InvalidKeyException ike) {
+ throw new XMLEncryptionException("empty", ike);
+ } catch (IllegalBlockSizeException ibse) {
+ throw new XMLEncryptionException("empty", ibse);
+ } catch (InvalidAlgorithmParameterException e) {
+ throw new XMLEncryptionException("empty", e);
+ }
String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
-
- 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 (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());
- _ek.setEncryptionMethod(method);
- } catch (URI.MalformedURIException mfue) {
- throw new XMLEncryptionException("empty", mfue);
+ EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
+ method.setDigestAlgorithm(digestAlg);
+ method.setMGFAlgorithm(mgfAlgorithm);
+ method.setOAEPparams(oaepParams);
+ ek.setEncryptionMethod(method);
+ } catch (URISyntaxException ex) {
+ throw new XMLEncryptionException("empty", ex);
}
- return _ek;
-
+ return ek;
}
- /**
- * Decrypt a key from a passed in EncryptedKey structure
- *
- * @param encryptedKey Previously loaded EncryptedKey that needs
- * to be decrypted.
- * @param algorithm Algorithm for the decryption
- * @return a key corresponding to the give type
+ /**
+ * Decrypt a key from a passed in EncryptedKey structure
+ *
+ * @param encryptedKey Previously loaded EncryptedKey that needs
+ * to be decrypted.
+ * @param algorithm Algorithm for the decryption
+ * @return a key corresponding to the given type
* @throws XMLEncryptionException
- */
-
- public Key decryptKey(EncryptedKey encryptedKey, String algorithm) throws
- XMLEncryptionException {
-
- logger.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey...");
-
- 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");
+ */
+ 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...");
+ }
+
+ if (cipherMode != UNWRAP_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
+ log.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) {
+ 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 {
+ String keyWrapAlg = encryptedKey.getEncryptionMethod().getAlgorithm();
+ String keyType = JCEMapper.getJCEKeyAlgorithmFromURI(keyWrapAlg);
+ if ("RSA".equals(keyType)) {
+ key = ki.getPrivateKey();
+ } else {
+ key = ki.getSecretKey();
+ }
}
-
- 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");
- }
+ catch (Exception e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+ }
}
-
- // 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;
+ }
+ 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");
+ }
+ }
+
+ // Obtain the encrypted octets
+ XMLCipherInput cipherInput = new XMLCipherInput(encryptedKey);
+ cipherInput.setSecureValidation(secureValidation);
+ byte[] encryptedBytes = cipherInput.getBytes();
+
+ 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;
+ }
+
+ /**
+ * Construct an OAEPParameterSpec object from the given parameters
+ */
+ private OAEPParameterSpec constructOAEPParameters(
+ String encryptionAlgorithm,
+ String digestAlgorithm,
+ String mgfAlgorithm,
+ byte[] oaepParams
+ ) {
+ if (XMLCipher.RSA_OAEP.equals(encryptionAlgorithm)
+ || XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
+
+ String jceDigestAlgorithm = "SHA-1";
+ if (digestAlgorithm != null) {
+ jceDigestAlgorithm = JCEMapper.translateURItoJCEID(digestAlgorithm);
+ }
+
+ PSource.PSpecified pSource = PSource.PSpecified.DEFAULT;
+ if (oaepParams != null) {
+ pSource = new PSource.PSpecified(oaepParams);
+ }
+
+ MGF1ParameterSpec mgfParameterSpec = new MGF1ParameterSpec("SHA-1");
+ if (XMLCipher.RSA_OAEP_11.equals(encryptionAlgorithm)) {
+ if (EncryptionConstants.MGF1_SHA256.equals(mgfAlgorithm)) {
+ mgfParameterSpec = new MGF1ParameterSpec("SHA-256");
+ } else if (EncryptionConstants.MGF1_SHA384.equals(mgfAlgorithm)) {
+ mgfParameterSpec = new MGF1ParameterSpec("SHA-384");
+ } else if (EncryptionConstants.MGF1_SHA512.equals(mgfAlgorithm)) {
+ mgfParameterSpec = new MGF1ParameterSpec("SHA-512");
}
-
- Key ret;
-
- 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);
- }
-
- logger.log(java.util.logging.Level.FINE, "Decryption of key type " + algorithm + " OK");
-
- return ret;
-
+ }
+ return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource);
+ }
+
+ return null;
}
- /**
- * 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
+ /**
+ * 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());
-
- }
+ */
+ public Key decryptKey(EncryptedKey encryptedKey) throws XMLEncryptionException {
+ return decryptKey(encryptedKey, ed.getEncryptionMethod().getAlgorithm());
+ }
/**
* Removes the contents of a <code>Node</code>.
@@ -1407,7 +1592,7 @@
* @param node the <code>Node</code> to clear.
*/
private static void removeContent(Node node) {
- while (node.hasChildNodes()) {
+ while (node.hasChildNodes()) {
node.removeChild(node.getFirstChild());
}
}
@@ -1419,196 +1604,191 @@
* @return the <code>Node</code> 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);
+ private Document decryptElement(Element element) throws XMLEncryptionException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Decrypting element...");
+ }
+
+ 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;
}
-
- /**
- *
- * @param element
- * @return
+ /**
+ *
+ * @param element
+ * @return the <code>Node</code> as a result of the decrypt operation.
* @throws XMLEncryptionException
- */
- private Document decryptElementContent(Element element) throws
- XMLEncryptionException {
- Element e = (Element) element.getElementsByTagNameNS(
+ */
+ private Document decryptElementContent(Element element) throws XMLEncryptionException {
+ Element e =
+ (Element) element.getElementsByTagNameNS(
EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);
+ EncryptionConstants._TAG_ENCRYPTEDDATA
+ ).item(0);
if (null == e) {
- throw new XMLEncryptionException("No EncryptedData child element.");
+ throw new XMLEncryptionException("No EncryptedData child element.");
}
- return (decryptElement(e));
+ return decryptElement(e);
}
- /**
- * Decrypt an EncryptedData element to a byte array
- *
- * When passed in an EncryptedData node, returns the decryption
- * as a byte array.
- *
- * Does not modify the source document
+ /**
+ * Decrypt an EncryptedData element to a byte array.
+ *
+ * When passed in an EncryptedData node, returns the decryption
+ * as a byte array.
+ *
+ * Does not modify the source document.
* @param element
- * @return
+ * @return the bytes resulting from the decryption
* @throws XMLEncryptionException
- */
-
- public byte[] decryptToByteArray(Element element)
- throws XMLEncryptionException {
-
- logger.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
-
- if(_cipherMode != DECRYPT_MODE)
- logger.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
-
- EncryptedData encryptedData = _factory.newEncryptedData(element);
-
- if (_key == null) {
-
- KeyInfo ki = encryptedData.getKeyInfo();
-
- 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");
+ */
+ public byte[] decryptToByteArray(Element element) throws XMLEncryptionException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Decrypting to ByteArray...");
+ }
+
+ if (cipherMode != DECRYPT_MODE) {
+ log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
+ }
+
+ EncryptedData encryptedData = factory.newEncryptedData(element);
+
+ if (key == null) {
+ KeyInfo ki = encryptedData.getKeyInfo();
+ if (ki != null) {
+ try {
+ // Add an EncryptedKey resolver
+ String encMethodAlgorithm = encryptedData.getEncryptionMethod().getAlgorithm();
+ EncryptedKeyResolver resolver = new EncryptedKeyResolver(encMethodAlgorithm, kek);
+ if (internalKeyResolvers != null) {
+ int size = internalKeyResolvers.size();
+ for (int i = 0; i < size; i++) {
+ resolver.registerInternalKeyResolver(internalKeyResolvers.get(i));
}
- }
-
- // 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;
- 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);
+ }
+ 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
-
- // For now, we only work with Block ciphers, so this will work.
- // This should probably be put into the JCE mapper.
-
- int ivLen = c.getBlockSize();
- byte[] ivBytes = new byte[ivLen];
-
- // You may be able to pass the entire piece in to IvParameterSpec
- // and it will only take the first x bytes, but no way to be certain
- // that this will work for every JCE provider, so lets copy the
- // necessary bytes into a dedicated array.
-
- System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen);
- IvParameterSpec iv = new IvParameterSpec(ivBytes);
-
- try {
- c.init(_cipherMode, _key, iv);
- } catch (InvalidKeyException ike) {
- throw new XMLEncryptionException("empty", ike);
- } catch (InvalidAlgorithmParameterException iape) {
- throw new XMLEncryptionException("empty", iape);
- }
-
- byte[] plainBytes;
+ }
+
+ 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");
+ }
+ }
+
+ // Obtain the encrypted octets
+ XMLCipherInput cipherInput = new XMLCipherInput(encryptedData);
+ cipherInput.setSecureValidation(secureValidation);
+ byte[] encryptedBytes = cipherInput.getBytes();
+
+ // Now create the working cipher
+ String jceAlgorithm =
+ JCEMapper.translateURItoJCEID(encryptedData.getEncryptionMethod().getAlgorithm());
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
+ }
+
+ Cipher c;
+ try {
+ if (requestedJCEProvider == null) {
+ c = Cipher.getInstance(jceAlgorithm);
+ } else {
+ c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
+ }
+ } catch (NoSuchAlgorithmException nsae) {
+ throw new XMLEncryptionException("empty", nsae);
+ } catch (NoSuchProviderException nspre) {
+ throw new XMLEncryptionException("empty", nspre);
+ } catch (NoSuchPaddingException nspae) {
+ throw new XMLEncryptionException("empty", nspae);
+ }
+
+ // Calculate the IV length and copy out
+
+ // For now, we only work with Block ciphers, so this will work.
+ // This should probably be put into the JCE mapper.
+
+ int ivLen = c.getBlockSize();
+ 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 <code>EncryptedData</code> <code>Element</code>.
*
- * 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.
- *<p>
- * 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.
+ *<p>
+ * 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
* <code>EncryptedData</code> or the URI to set in the CipherReference
- * (usage will depend on the <code>type</code>
+ * (usage will depend on the <code>type</code>
* @return the <code>EncryptedData</code> <code>Element</code>.
*
* <!--
@@ -1629,44 +1809,41 @@
* -->
* @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 <code>EncryptedKey</code> <code>Element</code>.
*
- * 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.
- *<p>
- * 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.
+ *<p>
+ * 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
* <code>EncryptedKey</code> or the URI to set in the CipherReference
- * (usage will depend on the <code>type</code>
+ * (usage will depend on the <code>type</code>
* @return the <code>EncryptedKey</code> <code>Element</code>.
*
* <!--
@@ -1687,331 +1864,128 @@
* -->
* @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);
- }
-
- 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));
+ 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);
}
- /**
- * 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
- * <p>
- * <b>Note</b>: A context document <i>must</i> 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 <b>requires</b> a
- * context document.
- *
- * @param doc Document that will own the created Transforms node
- * @return
- */
- public Transforms createTransforms(Document doc) {
- return (_factory.newTransforms(doc));
- }
+ return result;
+ }
+
+ /**
+ * Create an AgreementMethod object
+ *
+ * @param algorithm Algorithm of the agreement method
+ * @return a new <code>AgreementMethod</code>
+ */
+ 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 <code>CipherData</code>
+ */
+ 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 <code>CipherReference</code>
+ */
+ 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 <code>CipherValue</code>
+ */
+ public CipherValue createCipherValue(String value) {
+ return factory.newCipherValue(value);
+ }
/**
- * Converts <code>String</code>s into <code>Node</code>s and visa versa.
- * <p>
- * <b>NOTE:</b> For internal use only.
+ * Create an EncryptionMethod object
*
- * @author Axl Mattheus
+ * @param algorithm Algorithm for the encryption
+ * @return a new <code>EncryptionMethod</code>
+ */
+ public EncryptionMethod createEncryptionMethod(String algorithm) {
+ return factory.newEncryptionMethod(algorithm);
+ }
+
+ /**
+ * Create an EncryptionProperties element
+ * @return a new <code>EncryptionProperties</code>
+ */
+ public EncryptionProperties createEncryptionProperties() {
+ return factory.newEncryptionProperties();
+ }
+
+ /**
+ * Create a new EncryptionProperty element
+ * @return a new <code>EncryptionProperty</code>
+ */
+ public EncryptionProperty createEncryptionProperty() {
+ return factory.newEncryptionProperty();
+ }
+
+ /**
+ * Create a new ReferenceList object
+ * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE
+ * @return a new <code>ReferenceList</code>
*/
-
- private class Serializer {
- /**
- * Initialize the <code>XMLSerializer</code> with the specified context
- * <code>Document</code>.
- * <p/>
- * Setup OutputFormat in a way that the serialization does <b>not</b>
- * 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 <code>String</code> representation of the specified
- * <code>Document</code>.
- * <p/>
- * Refer also to comments about setup of format.
- *
- * @param document the <code>Document</code> to serialize.
- * @return the <code>String</code> representation of the serilaized
- * <code>Document</code>.
- * @throws Exception
- */
- String serialize(Document document) throws Exception {
- return canonSerialize(document);
- }
-
- /**
- * Returns a <code>String</code> representation of the specified
- * <code>Element</code>.
- * <p/>
- * Refer also to comments about setup of format.
- *
- * @param element the <code>Element</code> to serialize.
- * @return the <code>String</code> representation of the serilaized
- * <code>Element</code>.
- * @throws Exception
- */
- String serialize(Element element) throws Exception {
- return canonSerialize(element);
- }
-
- /**
- * Returns a <code>String</code> representation of the specified
- * <code>NodeList</code>.
- * <p/>
- * This is a special case because the NodeList may represent a
- * <code>DocumentFragment</code>. 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.
- * <p/>
- * 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.
- * <p/>
- * Refer also to comments about setup of format.
- *
- * @param content the <code>NodeList</code> to serialize.
- * @return the <code>String</code> representation of the serilaized
- * <code>NodeList</code>.
- * @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("<?xml version=\"1.0\" encoding=\"UTF-8\"?><"+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 + "</" + tagname + ">");
- 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 ReferenceList createReferenceList(int type) {
+ return factory.newReferenceList(type);
+ }
+
+ /**
+ * Create a new Transforms object
+ * <p>
+ * <b>Note</b>: A context document <i>must</i> have been set
+ * elsewhere (possibly via a call to doFinal). If not, use the
+ * createTransforms(Document) method.
+ * @return a new <code>Transforms</code>
+ */
+ 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 <b>requires</b> a
+ * context document.
+ *
+ * @param doc Document that will own the created Transforms node
+ * @return a new <code>Transforms</code>
+ */
+ public Transforms createTransforms(Document doc) {
+ return factory.newTransforms(doc);
+ }
/**
*
@@ -2020,201 +1994,110 @@
private class Factory {
/**
* @param algorithm
- * @return
- *
+ * @return a new AgreementMethod
*/
AgreementMethod newAgreementMethod(String algorithm) {
- return (new AgreementMethodImpl(algorithm));
- }
-
- /**
- * @param type
- * @return
- *
- */
- CipherData newCipherData(int type) {
- return (new CipherDataImpl(type));
- }
-
- /**
- * @param uri
- * @return
- *
- */
- CipherReference newCipherReference(String uri) {
- return (new CipherReferenceImpl(uri));
- }
-
- /**
- * @param value
- * @return
- *
- */
- CipherValue newCipherValue(String value) {
- return (new CipherValueImpl(value));
- }
-
- /**
- *
-
- CipherValue newCipherValue(byte[] value) {
- return (new CipherValueImpl(value));
- }
- */
- /**
- * @param data
- * @return
- *
- */
- EncryptedData newEncryptedData(CipherData data) {
- return (new EncryptedDataImpl(data));
- }
-
- /**
- * @param data
- * @return
- *
- */
- EncryptedKey newEncryptedKey(CipherData data) {
- return (new EncryptedKeyImpl(data));
- }
-
- /**
- * @param algorithm
- * @return
- *
- */
- EncryptionMethod newEncryptionMethod(String algorithm) {
- return (new EncryptionMethodImpl(algorithm));
- }
-
- /**
- * @return
- *
- */
- EncryptionProperties newEncryptionProperties() {
- return (new EncryptionPropertiesImpl());
- }
-
- /**
- * @return
- *
- */
- EncryptionProperty newEncryptionProperty() {
- return (new EncryptionPropertyImpl());
+ return new AgreementMethodImpl(algorithm);
}
/**
* @param type
- * @return
+ * @return a new CipherData
*
*/
- ReferenceList newReferenceList(int type) {
- return (new ReferenceListImpl(type));
+ CipherData newCipherData(int type) {
+ return new CipherDataImpl(type);
+ }
+
+ /**
+ * @param uri
+ * @return a new CipherReference
+ */
+ CipherReference newCipherReference(String uri) {
+ return new CipherReferenceImpl(uri);
+ }
+
+ /**
+ * @param value
+ * @return a new CipherValue
+ */
+ CipherValue newCipherValue(String value) {
+ return new CipherValueImpl(value);
+ }
+
+ /*
+ CipherValue newCipherValue(byte[] value) {
+ return new CipherValueImpl(value);
+ }
+ */
+
+ /**
+ * @param data
+ * @return a new EncryptedData
+ */
+ EncryptedData newEncryptedData(CipherData data) {
+ return new EncryptedDataImpl(data);
}
/**
- * @return
- *
+ * @param data
+ * @return a new EncryptedKey
+ */
+ EncryptedKey newEncryptedKey(CipherData data) {
+ return new EncryptedKeyImpl(data);
+ }
+
+ /**
+ * @param algorithm
+ * @return a new EncryptionMethod
+ */
+ EncryptionMethod newEncryptionMethod(String algorithm) {
+ return new EncryptionMethodImpl(algorithm);
+ }
+
+ /**
+ * @return a new EncryptionProperties
+ */
+ EncryptionProperties newEncryptionProperties() {
+ return new EncryptionPropertiesImpl();
+ }
+
+ /**
+ * @return a new EncryptionProperty
+ */
+ EncryptionProperty newEncryptionProperty() {
+ return new EncryptionPropertyImpl();
+ }
+
+ /**
+ * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE
+ * @return a new ReferenceList
+ */
+ ReferenceList newReferenceList(int type) {
+ return new ReferenceListImpl(type);
+ }
+
+ /**
+ * @return a new Transforms
*/
Transforms newTransforms() {
- return (new TransformsImpl());
+ return 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
- *
*/
- // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
- // <complexType name="AgreementMethodType" mixed="true">
- // <sequence>
- // <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
- // <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
- // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
- // <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- // <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- // </sequence>
- // <attribute name="Algorithm" type="anyURI" use="required"/>
- // </complexType>
- 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..
- // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
-
- // 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
- *
- */
- // <element name='CipherData' type='xenc:CipherDataType'/>
- // <complexType name='CipherDataType'>
- // <choice>
- // <element name='CipherValue' type='base64Binary'/>
- // <element ref='xenc:CipherReference'/>
- // </choice>
- // </complexType>
- 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 @@
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 @@
result.setCipherReference(newCipherReference(e));
}
- return (result);
+ return result;
}
/**
* @param element
- * @return
+ * @return a new CipherReference
* @throws XMLEncryptionException
*
*/
- // <element name='CipherReference' type='xenc:CipherReferenceType'/>
- // <complexType name='CipherReferenceType'>
- // <sequence>
- // <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
- // </sequence>
- // <attribute name='URI' type='anyURI' use='required'/>
- // </complexType>
- CipherReference newCipherReference(Element element) throws
- XMLEncryptionException {
-
- Attr URIAttr =
- element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI);
- CipherReference result = new CipherReferenceImpl(URIAttr);
-
- // Find any Transforms
-
- NodeList transformsElements = element.getElementsByTagNameNS(
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_TRANSFORMS);
- Element transformsElement =
- (Element) transformsElements.item(0);
-
- if (transformsElement != null) {
- logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
- try {
- result.setTransforms(new TransformsImpl(transformsElement));
- }
- catch (XMLSignatureException xse) {
- throw new XMLEncryptionException("empty", xse);
- } catch (InvalidTransformException ite) {
- throw new XMLEncryptionException("empty", ite);
- } catch (XMLSecurityException xse) {
- throw new XMLEncryptionException("empty", xse);
- }
-
- }
-
- return result;
+ CipherReference newCipherReference(Element element) throws XMLEncryptionException {
+
+ Attr uriAttr =
+ element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI);
+ CipherReference result = new CipherReferenceImpl(uriAttr);
+
+ // Find any Transforms
+ NodeList transformsElements =
+ element.getElementsByTagNameNS(
+ EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS);
+ Element transformsElement = (Element) transformsElements.item(0);
+
+ if (transformsElement != null) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element");
+ }
+ try {
+ result.setTransforms(new TransformsImpl(transformsElement));
+ } catch (XMLSignatureException xse) {
+ throw new XMLEncryptionException("empty", xse);
+ } catch (InvalidTransformException ite) {
+ throw new XMLEncryptionException("empty", ite);
+ } catch (XMLSecurityException xse) {
+ throw new XMLEncryptionException("empty", xse);
+ }
+ }
+
+ return result;
}
/**
* @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
*
*/
- // <complexType name='EncryptedType' abstract='true'>
- // <sequence>
- // <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- // minOccurs='0'/>
- // <element ref='ds:KeyInfo' minOccurs='0'/>
- // <element ref='xenc:CipherData'/>
- // <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // <attribute name='Type' type='anyURI' use='optional'/>
- // <attribute name='MimeType' type='string' use='optional'/>
- // <attribute name='Encoding' type='anyURI' use='optional'/>
- // </complexType>
- // <element name='EncryptedData' type='xenc:EncryptedDataType'/>
- // <complexType name='EncryptedDataType'>
- // <complexContent>
- // <extension base='xenc:EncryptedType'/>
- // </complexContent>
- // </complexType>
- EncryptedData newEncryptedData(Element element) throws
- XMLEncryptionException {
+ EncryptedData newEncryptedData(Element element) throws XMLEncryptionException {
EncryptedData result = null;
- NodeList dataElements = element.getElementsByTagNameNS(
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_CIPHERDATA);
+ NodeList dataElements =
+ element.getElementsByTagNameNS(
+ EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
// Need to get the last CipherData found, as earlier ones will
// be for elements in the KeyInfo lists
@@ -2349,22 +2200,17 @@
result = newEncryptedData(data);
- result.setId(element.getAttributeNS(
- null, EncryptionConstants._ATT_ID));
- result.setType(
- element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
- result.setMimeType(element.getAttributeNS(
- null, EncryptionConstants._ATT_MIMETYPE));
- result.setEncoding(
- element.getAttributeNS(null, Constants._ATT_ENCODING));
+ result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID));
+ result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE));
+ result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE));
+ result.setEncoding( element.getAttributeNS(null, Constants._ATT_ENCODING));
Element encryptionMethodElement =
(Element) element.getElementsByTagNameNS(
EncryptionConstants.EncryptionSpecNS,
EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0);
if (null != encryptionMethodElement) {
- result.setEncryptionMethod(newEncryptionMethod(
- encryptionMethodElement));
+ result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement));
}
// BFL 16/7/03 - simple implementation
@@ -2374,12 +2220,8 @@
(Element) element.getElementsByTagNameNS(
Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0);
if (null != keyInfoElement) {
- try {
- result.setKeyInfo(new KeyInfo(keyInfoElement, null));
- } catch (XMLSecurityException xse) {
- throw new XMLEncryptionException("Error loading Key Info",
- xse);
- }
+ KeyInfo ki = newKeyInfo(keyInfoElement);
+ result.setKeyInfo(ki);
}
// TODO: Implement
@@ -2389,85 +2231,49 @@
EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0);
if (null != encryptionPropertiesElement) {
result.setEncryptionProperties(
- newEncryptionProperties(encryptionPropertiesElement));
+ newEncryptionProperties(encryptionPropertiesElement)
+ );
}
- return (result);
+ return result;
}
/**
* @param element
- * @return
+ * @return a new EncryptedKey
* @throws XMLEncryptionException
- *
*/
- // <complexType name='EncryptedType' abstract='true'>
- // <sequence>
- // <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- // minOccurs='0'/>
- // <element ref='ds:KeyInfo' minOccurs='0'/>
- // <element ref='xenc:CipherData'/>
- // <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // <attribute name='Type' type='anyURI' use='optional'/>
- // <attribute name='MimeType' type='string' use='optional'/>
- // <attribute name='Encoding' type='anyURI' use='optional'/>
- // </complexType>
- // <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
- // <complexType name='EncryptedKeyType'>
- // <complexContent>
- // <extension base='xenc:EncryptedType'>
- // <sequence>
- // <element ref='xenc:ReferenceList' minOccurs='0'/>
- // <element name='CarriedKeyName' type='string' minOccurs='0'/>
- // </sequence>
- // <attribute name='Recipient' type='string' use='optional'/>
- // </extension>
- // </complexContent>
- // </complexType>
- 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 @@
EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0);
if (null != encryptionPropertiesElement) {
result.setEncryptionProperties(
- newEncryptionProperties(encryptionPropertiesElement));
+ newEncryptionProperties(encryptionPropertiesElement)
+ );
}
Element referenceListElement =
@@ -2493,30 +2300,40 @@
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
*/
- // <complexType name='EncryptionMethodType' mixed='true'>
- // <sequence>
- // <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
- // <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
- // <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
- // </sequence>
- // <attribute name='Algorithm' type='anyURI' use='required'/>
- // </complexType>
+ 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 @@
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
// <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
- return (result);
+ return result;
}
/**
* @param element
- * @return
- *
+ * @return a new EncryptionProperties
*/
- // <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
- // <complexType name='EncryptionPropertiesType'>
- // <sequence>
- // <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // </complexType>
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
*/
- // <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
- // <complexType name='EncryptionPropertyType' mixed='true'>
- // <choice maxOccurs='unbounded'>
- // <any namespace='##other' processContents='lax'/>
- // </choice>
- // <attribute name='Target' type='anyURI' use='optional'/>
- // <attribute name='Id' type='ID' use='optional'/>
- // <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
- // </complexType>
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...
// <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
// TODO: Make this work...
// <any namespace='##other' processContents='lax'/>
- return (result);
+ return result;
}
/**
* @param element
- * @return
- *
+ * @return a new ReferenceList
*/
- // <element name='ReferenceList'>
- // <complexType>
- // <choice minOccurs='1' maxOccurs='unbounded'>
- // <element name='DataReference' type='xenc:ReferenceType'/>
- // <element name='KeyReference' type='xenc:ReferenceType'/>
- // </choice>
- // </complexType>
- // </element>
ReferenceList newReferenceList(Element element) {
int type = 0;
if (null != element.getElementsByTagNameNS(
@@ -2629,84 +2437,38 @@
EncryptionConstants.EncryptionSpecNS,
EncryptionConstants._TAG_KEYREFERENCE).item(0)) {
type = ReferenceList.KEY_REFERENCE;
- } else {
- // complain
}
ReferenceList result = new ReferenceListImpl(type);
NodeList list = null;
switch (type) {
case ReferenceList.DATA_REFERENCE:
- list = element.getElementsByTagNameNS(
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_DATAREFERENCE);
+ list =
+ element.getElementsByTagNameNS(
+ EncryptionConstants.EncryptionSpecNS,
+ EncryptionConstants._TAG_DATAREFERENCE);
for (int i = 0; i < list.getLength() ; i++) {
String uri = ((Element) list.item(i)).getAttribute("URI");
result.add(result.newDataReference(uri));
}
break;
case ReferenceList.KEY_REFERENCE:
- list = element.getElementsByTagNameNS(
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_KEYREFERENCE);
+ list =
+ element.getElementsByTagNameNS(
+ EncryptionConstants.EncryptionSpecNS,
+ EncryptionConstants._TAG_KEYREFERENCE);
for (int i = 0; i < list.getLength() ; i++) {
String uri = ((Element) list.item(i)).getAttribute("URI");
result.add(result.newKeyReference(uri));
}
}
- return (result);
- }
-
- /**
- * @param element
- * @return
- *
- */
- Transforms newTransforms(Element element) {
- return (null);
- }
-
- /**
- * @param agreementMethod
- * @return
- *
- */
- Element toElement(AgreementMethod agreementMethod) {
- return ((AgreementMethodImpl) agreementMethod).toElement();
- }
-
- /**
- * @param cipherData
- * @return
- *
- */
- Element toElement(CipherData cipherData) {
- return ((CipherDataImpl) cipherData).toElement();
- }
-
- /**
- * @param cipherReference
- * @return
- *
- */
- Element toElement(CipherReference cipherReference) {
- return ((CipherReferenceImpl) cipherReference).toElement();
- }
-
- /**
- * @param cipherValue
- * @return
- *
- */
- Element toElement(CipherValue cipherValue) {
- return ((CipherValueImpl) cipherValue).toElement();
+ return result;
}
/**
* @param encryptedData
- * @return
- *
+ * @return the XML Element form of that EncryptedData
*/
Element toElement(EncryptedData encryptedData) {
return ((EncryptedDataImpl) encryptedData).toElement();
@@ -2714,64 +2476,20 @@
/**
* @param encryptedKey
- * @return
- *
+ * @return the XML Element form of that EncryptedKey
*/
Element toElement(EncryptedKey encryptedKey) {
return ((EncryptedKeyImpl) encryptedKey).toElement();
}
/**
- * @param encryptionMethod
- * @return
- *
- */
- Element toElement(EncryptionMethod encryptionMethod) {
- return ((EncryptionMethodImpl) encryptionMethod).toElement();
- }
-
- /**
- * @param encryptionProperties
- * @return
- *
+ * @param referenceList
+ * @return the XML Element form of that ReferenceList
*/
- 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();
- }
-
- // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
- // <complexType name="AgreementMethodType" mixed="true">
- // <sequence>
- // <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
- // <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
- // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
- // <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- // <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- // </sequence>
- // <attribute name="Algorithm" type="anyURI" use="required"/>
- // </complexType>
private class AgreementMethodImpl implements AgreementMethod {
private byte[] kaNonce = null;
private List<Element> agreementMethodInformation = null;
@@ -2787,15 +2505,16 @@
URI tmpAlgorithm = null;
try {
tmpAlgorithm = new URI(algorithm);
- } catch (URI.MalformedURIException fmue) {
- //complain?
+ } catch (URISyntaxException ex) {
+ throw (IllegalArgumentException)
+ new IllegalArgumentException().initCause(ex);
}
algorithmURI = tmpAlgorithm.toString();
}
/** @inheritDoc */
public byte[] getKANonce() {
- return (kaNonce);
+ return kaNonce;
}
/** @inheritDoc */
@@ -2805,7 +2524,7 @@
/** @inheritDoc */
public Iterator<Element> getAgreementMethodInformation() {
- return (agreementMethodInformation.iterator());
+ return agreementMethodInformation.iterator();
}
/** @inheritDoc */
@@ -2820,7 +2539,7 @@
/** @inheritDoc */
public KeyInfo getOriginatorKeyInfo() {
- return (originatorKeyInfo);
+ return originatorKeyInfo;
}
/** @inheritDoc */
@@ -2830,7 +2549,7 @@
/** @inheritDoc */
public KeyInfo getRecipientKeyInfo() {
- return (recipientKeyInfo);
+ return recipientKeyInfo;
}
/** @inheritDoc */
@@ -2840,70 +2559,10 @@
/** @inheritDoc */
public String getAlgorithm() {
- return (algorithmURI);
- }
-
- /** @param algorithm*/
- public void setAlgorithm(String algorithm) {
- URI tmpAlgorithm = null;
- try {
- tmpAlgorithm = new URI(algorithm);
- } catch (URI.MalformedURIException mfue) {
- //complain
- }
- algorithmURI = tmpAlgorithm.toString();
- }
-
- // <element name="AgreementMethod" type="xenc:AgreementMethodType"/>
- // <complexType name="AgreementMethodType" mixed="true">
- // <sequence>
- // <element name="KA-Nonce" minOccurs="0" type="base64Binary"/>
- // <!-- <element ref="ds:DigestMethod" minOccurs="0"/> -->
- // <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
- // <element name="OriginatorKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- // <element name="RecipientKeyInfo" minOccurs="0" type="ds:KeyInfoType"/>
- // </sequence>
- // <attribute name="Algorithm" type="anyURI" use="required"/>
- // </complexType>
- 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<Element> 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;
}
}
- // <element name='CipherData' type='xenc:CipherDataType'/>
- // <complexType name='CipherDataType'>
- // <choice>
- // <element name='CipherValue' type='base64Binary'/>
- // <element ref='xenc:CipherReference'/>
- // </choice>
- // </complexType>
private class CipherDataImpl implements CipherData {
private static final String valueMessage =
"Data type is reference type.";
@@ -2922,16 +2581,16 @@
/** @inheritDoc */
public CipherValue getCipherValue() {
- return (cipherValue);
+ return cipherValue;
}
/** @inheritDoc */
- public void setCipherValue(CipherValue value) throws
- XMLEncryptionException {
+ public void setCipherValue(CipherValue value) throws XMLEncryptionException {
if (cipherType == REFERENCE_TYPE) {
- throw new XMLEncryptionException("empty",
- new UnsupportedOperationException(valueMessage));
+ throw new XMLEncryptionException(
+ "empty", new UnsupportedOperationException(valueMessage)
+ );
}
cipherValue = value;
@@ -2939,15 +2598,16 @@
/** @inheritDoc */
public CipherReference getCipherReference() {
- return (cipherReference);
+ return cipherReference;
}
/** @inheritDoc */
public void setCipherReference(CipherReference reference) throws
- XMLEncryptionException {
+ XMLEncryptionException {
if (cipherType == VALUE_TYPE) {
- throw new XMLEncryptionException("empty",
- new UnsupportedOperationException(referenceMessage));
+ throw new XMLEncryptionException(
+ "empty", new UnsupportedOperationException(referenceMessage)
+ );
}
cipherReference = reference;
@@ -2955,77 +2615,59 @@
/** @inheritDoc */
public int getDataType() {
- return (cipherType);
+ return cipherType;
}
- // <element name='CipherData' type='xenc:CipherDataType'/>
- // <complexType name='CipherDataType'>
- // <choice>
- // <element name='CipherValue' type='base64Binary'/>
- // <element ref='xenc:CipherReference'/>
- // </choice>
- // </complexType>
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;
}
}
- // <element name='CipherReference' type='xenc:CipherReferenceType'/>
- // <complexType name='CipherReferenceType'>
- // <sequence>
- // <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
- // </sequence>
- // <attribute name='URI' type='anyURI' use='required'/>
- // </complexType>
private class CipherReferenceImpl implements CipherReference {
private String referenceURI = null;
private Transforms referenceTransforms = null;
- private Attr referenceNode = null;
+ private Attr referenceNode = null;
/**
* @param uri
*/
public CipherReferenceImpl(String uri) {
- /* Don't check validity of URI as may be "" */
+ /* Don't check validity of URI as may be "" */
referenceURI = uri;
- referenceNode = null;
+ referenceNode = null;
}
- /**
- * @param uri
- */
- public CipherReferenceImpl(Attr uri) {
- referenceURI = uri.getNodeValue();
- referenceNode = uri;
- }
+ /**
+ * @param uri
+ */
+ public CipherReferenceImpl(Attr uri) {
+ referenceURI = uri.getNodeValue();
+ referenceNode = uri;
+ }
/** @inheritDoc */
public String getURI() {
- return (referenceURI);
+ return referenceURI;
}
/** @inheritDoc */
- public Attr getURIAsAttr() {
- return (referenceNode);
- }
+ public Attr getURIAsAttr() {
+ return referenceNode;
+ }
/** @inheritDoc */
public Transforms getTransforms() {
- return (referenceTransforms);
+ return referenceTransforms;
}
/** @inheritDoc */
@@ -3033,91 +2675,53 @@
referenceTransforms = transforms;
}
- // <element name='CipherReference' type='xenc:CipherReferenceType'/>
- // <complexType name='CipherReferenceType'>
- // <sequence>
- // <element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>
- // </sequence>
- // <attribute name='URI' type='anyURI' use='required'/>
- // </complexType>
Element toElement() {
- Element result = ElementProxy.createElementForFamily(
- _contextDocument,
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_CIPHERREFERENCE);
- result.setAttributeNS(
- null, EncryptionConstants._ATT_URI, referenceURI);
+ Element result =
+ XMLUtils.createElementInEncryptionSpace(
+ contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE
+ );
+ result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI);
if (null != referenceTransforms) {
- result.appendChild(
- ((TransformsImpl) referenceTransforms).toElement());
+ result.appendChild(((TransformsImpl) referenceTransforms).toElement());
}
- return (result);
+ return result;
}
}
private class CipherValueImpl implements CipherValue {
- private String cipherValue = null;
-
- // public CipherValueImpl(byte[] value) {
- // cipherValue = value;
- // }
+ private String cipherValue = null;
/**
* @param value
*/
public CipherValueImpl(String value) {
- // cipherValue = value.getBytes();
- cipherValue = value;
+ cipherValue = value;
}
/** @inheritDoc */
- public String getValue() {
- return (cipherValue);
+ public String getValue() {
+ return cipherValue;
}
- // public void setValue(byte[] value) {
- // public void setValue(String value) {
- // cipherValue = value;
- // }
- /** @inheritDoc */
+ /** @inheritDoc */
public void setValue(String value) {
- // cipherValue = value.getBytes();
- cipherValue = value;
+ cipherValue = value;
}
Element toElement() {
- Element result = ElementProxy.createElementForFamily(
- _contextDocument, EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_CIPHERVALUE);
- result.appendChild(_contextDocument.createTextNode(
- cipherValue));
-
- return (result);
+ Element result =
+ XMLUtils.createElementInEncryptionSpace(
+ contextDocument, EncryptionConstants._TAG_CIPHERVALUE
+ );
+ result.appendChild(contextDocument.createTextNode(cipherValue));
+
+ return result;
}
}
- // <complexType name='EncryptedType' abstract='true'>
- // <sequence>
- // <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- // minOccurs='0'/>
- // <element ref='ds:KeyInfo' minOccurs='0'/>
- // <element ref='xenc:CipherData'/>
- // <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // <attribute name='Type' type='anyURI' use='optional'/>
- // <attribute name='MimeType' type='string' use='optional'/>
- // <attribute name='Encoding' type='anyURI' use='optional'/>
- // </complexType>
- // <element name='EncryptedData' type='xenc:EncryptedDataType'/>
- // <complexType name='EncryptedDataType'>
- // <complexContent>
- // <extension base='xenc:EncryptedType'/>
- // </complexContent>
- // </complexType>
- private class EncryptedDataImpl extends EncryptedTypeImpl implements
- EncryptedData {
+ private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData {
+
/**
* @param data
*/
@@ -3125,94 +2729,49 @@
super(data);
}
- // <complexType name='EncryptedType' abstract='true'>
- // <sequence>
- // <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- // minOccurs='0'/>
- // <element ref='ds:KeyInfo' minOccurs='0'/>
- // <element ref='xenc:CipherData'/>
- // <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // <attribute name='Type' type='anyURI' use='optional'/>
- // <attribute name='MimeType' type='string' use='optional'/>
- // <attribute name='Encoding' type='anyURI' use='optional'/>
- // </complexType>
- // <element name='EncryptedData' type='xenc:EncryptedDataType'/>
- // <complexType name='EncryptedDataType'>
- // <complexContent>
- // <extension base='xenc:EncryptedType'/>
- // </complexContent>
- // </complexType>
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;
}
}
- // <complexType name='EncryptedType' abstract='true'>
- // <sequence>
- // <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- // minOccurs='0'/>
- // <element ref='ds:KeyInfo' minOccurs='0'/>
- // <element ref='xenc:CipherData'/>
- // <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // <attribute name='Type' type='anyURI' use='optional'/>
- // <attribute name='MimeType' type='string' use='optional'/>
- // <attribute name='Encoding' type='anyURI' use='optional'/>
- // </complexType>
- // <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
- // <complexType name='EncryptedKeyType'>
- // <complexContent>
- // <extension base='xenc:EncryptedType'>
- // <sequence>
- // <element ref='xenc:ReferenceList' minOccurs='0'/>
- // <element name='CarriedKeyName' type='string' minOccurs='0'/>
- // </sequence>
- // <attribute name='Recipient' type='string' use='optional'/>
- // </extension>
- // </complexContent>
- // </complexType>
- private class EncryptedKeyImpl extends EncryptedTypeImpl implements
- EncryptedKey {
+ private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey {
private String keyRecipient = null;
private ReferenceList referenceList = null;
private String carriedName = null;
@@ -3226,7 +2785,7 @@
/** @inheritDoc */
public String getRecipient() {
- return (keyRecipient);
+ return keyRecipient;
}
/** @inheritDoc */
@@ -3236,7 +2795,7 @@
/** @inheritDoc */
public ReferenceList getReferenceList() {
- return (referenceList);
+ return referenceList;
}
/** @inheritDoc */
@@ -3246,7 +2805,7 @@
/** @inheritDoc */
public String getCarriedName() {
- return (carriedName);
+ return carriedName;
}
/** @inheritDoc */
@@ -3254,84 +2813,60 @@
carriedName = name;
}
- // <complexType name='EncryptedType' abstract='true'>
- // <sequence>
- // <element name='EncryptionMethod' type='xenc:EncryptionMethodType'
- // minOccurs='0'/>
- // <element ref='ds:KeyInfo' minOccurs='0'/>
- // <element ref='xenc:CipherData'/>
- // <element ref='xenc:EncryptionProperties' minOccurs='0'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // <attribute name='Type' type='anyURI' use='optional'/>
- // <attribute name='MimeType' type='string' use='optional'/>
- // <attribute name='Encoding' type='anyURI' use='optional'/>
- // </complexType>
- // <element name='EncryptedKey' type='xenc:EncryptedKeyType'/>
- // <complexType name='EncryptedKeyType'>
- // <complexContent>
- // <extension base='xenc:EncryptedType'>
- // <sequence>
- // <element ref='xenc:ReferenceList' minOccurs='0'/>
- // <element name='CarriedKeyName' type='string' minOccurs='0'/>
- // </sequence>
- // <attribute name='Recipient' type='string' use='optional'/>
- // </extension>
- // </complexContent>
- // </complexType>
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 @@
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 void setId(String id) {
this.id = id;
}
+
/**
*
- * @return
+ * @return the type
*/
public String getType() {
- return (type);
+ return type;
}
+
/**
*
* @param type
@@ -3380,18 +2923,20 @@
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 void setMimeType(String type) {
mimeType = type;
}
+
/**
*
- * @return
+ * @return the encoding
*/
public String getEncoding() {
- return (encoding);
+ return encoding;
}
+
/**
*
* @param encoding
@@ -3418,19 +2965,22 @@
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 void setEncryptionMethod(EncryptionMethod method) {
encryptionMethod = method;
}
+
/**
*
- * @return
+ * @return the KeyInfo
*/
public KeyInfo getKeyInfo() {
- return (keyInfo);
+ return keyInfo;
}
+
/**
*
* @param info
@@ -3452,217 +3004,235 @@
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;
}
}
- // <complexType name='EncryptionMethodType' mixed='true'>
- // <sequence>
- // <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
- // <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
- // <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
- // </sequence>
- // <attribute name='Algorithm' type='anyURI' use='required'/>
- // </complexType>
private class EncryptionMethodImpl implements EncryptionMethod {
private String algorithm = null;
private int keySize = Integer.MIN_VALUE;
private byte[] oaepParams = null;
private List<Element> 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<Element>();
}
+
/** @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<Element> 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);
}
- // <complexType name='EncryptionMethodType' mixed='true'>
- // <sequence>
- // <element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>
- // <element name='OAEPparams' minOccurs='0' type='base64Binary'/>
- // <any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>
- // </sequence>
- // <attribute name='Algorithm' type='anyURI' use='required'/>
- // </complexType>
Element toElement() {
- Element result = ElementProxy.createElementForFamily(
- _contextDocument, EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_ENCRYPTIONMETHOD);
- result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM,
- algorithm);
+ Element result =
+ XMLUtils.createElementInEncryptionSpace(
+ contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD
+ );
+ result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm);
if (keySize > 0) {
result.appendChild(
- ElementProxy.createElementForFamily(_contextDocument,
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_KEYSIZE).appendChild(
- _contextDocument.createTextNode(
- String.valueOf(keySize))));
+ XMLUtils.createElementInEncryptionSpace(
+ contextDocument, EncryptionConstants._TAG_KEYSIZE
+ ).appendChild(contextDocument.createTextNode(String.valueOf(keySize))));
}
if (null != oaepParams) {
- result.appendChild(
- ElementProxy.createElementForFamily(_contextDocument,
- EncryptionConstants.EncryptionSpecNS,
- EncryptionConstants._TAG_OAEPPARAMS).appendChild(
- _contextDocument.createTextNode(
- new String(oaepParams))));
+ Element oaepElement =
+ XMLUtils.createElementInEncryptionSpace(
+ contextDocument, EncryptionConstants._TAG_OAEPPARAMS
+ );
+ oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams)));
+ result.appendChild(oaepElement);
+ }
+ if (digestAlgorithm != null) {
+ Element digestElement =
+ XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD);
+ digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm);
+ result.appendChild(digestElement);
}
- if (!encryptionMethodInformation.isEmpty()) {
- Iterator<Element> itr = encryptionMethodInformation.iterator();
+ 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<Element> itr = encryptionMethodInformation.iterator();
+ while (itr.hasNext()) {
result.appendChild(itr.next());
}
- return (result);
+ return result;
}
}
- // <element name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
- // <complexType name='EncryptionPropertiesType'>
- // <sequence>
- // <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // </complexType>
private class EncryptionPropertiesImpl implements EncryptionProperties {
private String id = null;
private List<EncryptionProperty> encryptionProperties = null;
+
/**
- *
- *
+ * Constructor.
*/
public EncryptionPropertiesImpl() {
encryptionProperties = new LinkedList<EncryptionProperty>();
}
+
/** @inheritDoc */
public String getId() {
- return (id);
+ return id;
}
+
/** @inheritDoc */
public void setId(String id) {
this.id = id;
}
+
/** @inheritDoc */
public Iterator<EncryptionProperty> 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 name='EncryptionProperties' type='xenc:EncryptionPropertiesType'/>
- // <complexType name='EncryptionPropertiesType'>
- // <sequence>
- // <element ref='xenc:EncryptionProperty' maxOccurs='unbounded'/>
- // </sequence>
- // <attribute name='Id' type='ID' use='optional'/>
- // </complexType>
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<EncryptionProperty> itr = getEncryptionProperties();
while (itr.hasNext()) {
- result.appendChild(((EncryptionPropertyImpl)
- itr.next()).toElement());
+ result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement());
}
- return (result);
+ return result;
}
}
- // <element name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
- // <complexType name='EncryptionPropertyType' mixed='true'>
- // <choice maxOccurs='unbounded'>
- // <any namespace='##other' processContents='lax'/>
- // </choice>
- // <attribute name='Target' type='anyURI' use='optional'/>
- // <attribute name='Id' type='ID' use='optional'/>
- // <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
- // </complexType>
private class EncryptionPropertyImpl implements EncryptionProperty {
private String target = null;
private String id = null;
- private HashMap<String,String> attributeMap = new HashMap<String,String>();
+ private Map<String, String> attributeMap = new HashMap<String, String>();
private List<Element> encryptionInformation = null;
/**
- *
- *
+ * Constructor.
*/
public EncryptionPropertyImpl() {
encryptionInformation = new LinkedList<Element>();
}
+
/** @inheritDoc */
public String getTarget() {
- return (target);
+ return target;
}
+
/** @inheritDoc */
public void setTarget(String target) {
if (target == null || target.length() == 0) {
@@ -3670,163 +3240,144 @@
} else if (target.startsWith("#")) {
/*
* This is a same document URI reference. Do not parse,
- * because com.sun.org.apache.xml.internal.utils.URI considers this an
- * illegal URI because it has no scheme.
+ * because it has no scheme.
*/
this.target = target;
} else {
URI tmpTarget = null;
try {
tmpTarget = new URI(target);
- } catch (URI.MalformedURIException mfue) {
- // complain
+ } catch (URISyntaxException ex) {
+ throw (IllegalArgumentException)
+ new IllegalArgumentException().initCause(ex);
}
this.target = tmpTarget.toString();
}
}
+
/** @inheritDoc */
public String getId() {
- return (id);
+ return id;
}
+
/** @inheritDoc */
public void setId(String id) {
this.id = id;
}
+
/** @inheritDoc */
public String getAttribute(String attribute) {
return attributeMap.get(attribute);
}
+
/** @inheritDoc */
public void setAttribute(String attribute, String value) {
attributeMap.put(attribute, value);
}
+
/** @inheritDoc */
public Iterator<Element> 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 name='EncryptionProperty' type='xenc:EncryptionPropertyType'/>
- // <complexType name='EncryptionPropertyType' mixed='true'>
- // <choice maxOccurs='unbounded'>
- // <any namespace='##other' processContents='lax'/>
- // </choice>
- // <attribute name='Target' type='anyURI' use='optional'/>
- // <attribute name='Id' type='ID' use='optional'/>
- // <anyAttribute namespace="http://www.w3.org/XML/1998/namespace"/>
- // </complexType>
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;
}
}
- // <complexType name='TransformsType'>
- // <sequence>
- // <element ref='ds:Transform' maxOccurs='unbounded'/>
- // </sequence>
- // </complexType>
- private class TransformsImpl extends
- com.sun.org.apache.xml.internal.security.transforms.Transforms
- implements Transforms {
-
- /**
- * Construct Transforms
- */
-
- public TransformsImpl() {
- super(_contextDocument);
- }
- /**
+ 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, "");
-
- }
+ * @param doc
+ */
+ public TransformsImpl(Document doc) {
+ if (doc == null) {
+ throw new RuntimeException("Document is null");
+ }
+
+ this.doc = doc;
+ this.constructionElement =
+ createElementForFamilyLocal(
+ this.doc, this.getBaseNamespace(), this.getBaseLocalName()
+ );
+ }
/**
*
- * @return
+ * @param element
+ * @throws XMLSignatureException
+ * @throws InvalidTransformException
+ * @throws XMLSecurityException
+ * @throws TransformationException
*/
- public Element toElement() {
-
- if (_doc == null)
- _doc = _contextDocument;
-
- return getElement();
- }
+ 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);
- }
-
-
- // Over-ride the namespace
+ public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() {
+ return this;
+ }
+
+ // Over-ride the namespace
/** @inheritDoc */
- public String getBaseNamespace() {
- return EncryptionConstants.EncryptionSpecNS;
- }
-
+ public String getBaseNamespace() {
+ return EncryptionConstants.EncryptionSpecNS;
+ }
}
- //<element name='ReferenceList'>
- // <complexType>
- // <choice minOccurs='1' maxOccurs='unbounded'>
- // <element name='DataReference' type='xenc:ReferenceType'/>
- // <element name='KeyReference' type='xenc:ReferenceType'/>
- // </choice>
- // </complexType>
- //</element>
private class ReferenceListImpl implements ReferenceList {
private Class<?> sentry;
private List<Reference> references;
+
/**
- *
+ * Constructor.
* @param type
*/
public ReferenceListImpl(int type) {
@@ -3839,13 +3390,15 @@
}
references = new LinkedList<Reference>();
}
+
/** @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 @@
}
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<Reference> 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<Reference> eachReference = references.iterator();
while (eachReference.hasNext()) {
Reference reference = eachReference.next();
- result.appendChild(
- ((ReferenceImpl) reference).toElement());
+ result.appendChild(((ReferenceImpl) reference).toElement());
}
- return (result);
+ return result;
}
+
/** @inheritDoc */
public Reference newDataReference(String uri) {
- return (new DataReference(uri));
+ return new DataReference(uri);
}
+
/** @inheritDoc */
public Reference newKeyReference(String uri) {
- return (new KeyReference(uri));
+ return new KeyReference(uri);
}
/**
@@ -3898,68 +3457,81 @@
private String uri;
private List<Element> referenceInformation;
- ReferenceImpl(String _uri) {
- this.uri = _uri;
+ ReferenceImpl(String uri) {
+ this.uri = uri;
referenceInformation = new LinkedList<Element>();
}
+
+ /** @inheritDoc */
+ public abstract String getType();
+
/** @inheritDoc */
public String getURI() {
- return (uri);
+ return uri;
}
+
/** @inheritDoc */
public Iterator<Element> getElementRetrievalInformation() {
- return (referenceInformation.iterator());
+ return referenceInformation.iterator();
}
+
/** @inheritDoc */
- public void setURI(String _uri) {
- this.uri = _uri;
+ public void setURI(String uri) {
+ this.uri = uri;
}
+
/** @inheritDoc */
public void removeElementRetrievalInformation(Element node) {
referenceInformation.remove(node);
}
+
/** @inheritDoc */
public void addElementRetrievalInformation(Element node) {
referenceInformation.add(node);
}
+
/**
- *
- * @return
+ * @return the XML Element form of that Reference
*/
- public abstract Element toElement();
-
- Element toElement(String tagName) {
- Element result = ElementProxy.createElementForFamily(
- _contextDocument,
- EncryptionConstants.EncryptionSpecNS,
- tagName);
+ public Element toElement() {
+ String tagName = getType();
+ Element result =
+ ElementProxy.createElementForFamily(
+ contextDocument,
+ EncryptionConstants.EncryptionSpecNS,
+ tagName
+ );
result.setAttribute(EncryptionConstants._ATT_URI, uri);
// TODO: Need to martial referenceInformation
// Figure out how to make this work..
// <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
- 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;
}
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,23 +2,24 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
-
package com.sun.org.apache.xml.internal.security.encryption;
import java.io.IOException;
@@ -32,7 +33,6 @@
import org.w3c.dom.Attr;
import com.sun.org.apache.xml.internal.security.utils.Base64;
-
/**
* <code>XMLCipherInput</code> is used to wrap input passed into the
* XMLCipher encryption operations.
@@ -50,77 +50,79 @@
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;
+ private boolean secureValidation;
- /**
- * Constructor for processing encrypted octets
- *
- * @param data The <code>CipherData</code> 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 data The <code>CipherData</code> 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 <code>EncryptedType</code> 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 <code>EncryptedType</code> object to read
+ * the bytes from.
+ * @throws XMLEncryptionException {@link XMLEncryptionException}
+ */
+ public XMLCipherInput(EncryptedType input) throws XMLEncryptionException {
+ cipherData = ((input == null) ? null : input.getCipherData());
+ mode = XMLCipher.DECRYPT_MODE;
+ if (cipherData == null) {
+ throw new XMLEncryptionException("CipherData is null");
+ }
+ }
- }
+ /**
+ * Set whether secure validation is enabled or not. The default is false.
+ */
+ public void setSecureValidation(boolean secureValidation) {
+ this.secureValidation = secureValidation;
+ }
- /**
- * Dereferences the input and returns it as a single byte array.
- *
- * @throws XMLEncryptionException
+ /**
+ * Dereferences the input and returns it as a single byte array.
+ *
+ * @throws XMLEncryptionException
* @return The decripted bytes.
- */
-
- public byte[] getBytes() throws XMLEncryptionException {
-
- if (_mode == XMLCipher.DECRYPT_MODE) {
- return getDecryptBytes();
- }
- return null;
+ */
+ public byte[] getBytes() throws XMLEncryptionException {
+ if (mode == XMLCipher.DECRYPT_MODE) {
+ return getDecryptBytes();
}
+ return null;
+ }
/**
* Internal method to get bytes in decryption mode
- * @return the decripted bytes
+ * @return the decrypted bytes
* @throws XMLEncryptionException
*/
private byte[] getDecryptBytes() throws XMLEncryptionException {
-
String base64EncodedEncryptedOctets = null;
- if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
+ if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
// Fun time!
- logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
- CipherReference cr = _cipherData.getCipherReference();
+ if (logger.isLoggable(java.util.logging.Level.FINE)) {
+ logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
+ }
+ CipherReference cr = cipherData.getCipherReference();
// Need to wrap the uri in an Attribute node so that we can
// Pass to the resource resolvers
@@ -130,25 +132,32 @@
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 @@
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);
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,104 +2,85 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
-
package com.sun.org.apache.xml.internal.security.encryption;
-
/**
* Constants
*/
public interface XMLCipherParameters {
- /** */
- public static final String AES_128 =
+ String AES_128 =
"http://www.w3.org/2001/04/xmlenc#aes128-cbc";
- /** */
- public static final String AES_256 =
+ String AES_256 =
"http://www.w3.org/2001/04/xmlenc#aes256-cbc";
- /** */
- public static final String AES_192 =
+ String AES_192 =
"http://www.w3.org/2001/04/xmlenc#aes192-cbc";
- /** */
- public static final String RSA_1_5 =
+ String RSA_1_5 =
"http://www.w3.org/2001/04/xmlenc#rsa-1_5";
- /** */
- public static final String RSA_OAEP =
+ String RSA_OAEP =
"http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
- /** */
- public static final String DIFFIE_HELLMAN =
+ String DIFFIE_HELLMAN =
"http://www.w3.org/2001/04/xmlenc#dh";
- /** */
- public static final String TRIPLEDES_KEYWRAP =
+ String TRIPLEDES_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-tripledes";
- /** */
- public static final String AES_128_KEYWRAP =
+ String AES_128_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-aes128";
- /** */
- public static final String AES_256_KEYWRAP =
+ String AES_256_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-aes256";
- /** */
- public static final String AES_192_KEYWRAP =
+ String AES_192_KEYWRAP =
"http://www.w3.org/2001/04/xmlenc#kw-aes192";
- /** */
- public static final String SHA1 =
+ String SHA1 =
"http://www.w3.org/2000/09/xmldsig#sha1";
- /** */
- public static final String SHA256 =
+ String SHA256 =
"http://www.w3.org/2001/04/xmlenc#sha256";
- /** */
- public static final String SHA512 =
+ String SHA512 =
"http://www.w3.org/2001/04/xmlenc#sha512";
- /** */
- public static final String RIPEMD_160 =
+ String RIPEMD_160 =
"http://www.w3.org/2001/04/xmlenc#ripemd160";
- /** */
- public static final String XML_DSIG =
+ String XML_DSIG =
"http://www.w3.org/2000/09/xmldsig#";
- /** */
- public static final String N14C_XML =
+ String N14C_XML =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
- /** */
- public static final String N14C_XML_CMMNTS =
+ String N14C_XML_CMMNTS =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
- /** */
- public static final String EXCL_XML_N14C =
+ String EXCL_XML_N14C =
"http://www.w3.org/2001/10/xml-exc-c14n#";
- /** */
- public static final String EXCL_XML_N14C_CMMNTS =
+ String EXCL_XML_N14C_CMMNTS =
"http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2003-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.encryption;
@@ -26,49 +28,53 @@
*
*/
public class XMLEncryptionException extends XMLSecurityException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- /**
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ /**
+ *
+ *
+ */
+ public XMLEncryptionException() {
+ super();
+ }
+
+ /**
+ *
+ * @param msgID
+ */
+ public XMLEncryptionException(String msgID) {
+ super(msgID);
+ }
+
+ /**
*
- *
- */
- 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);
- }
+ * @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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,88 +2,80 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.exceptions;
-
-
/**
* This Exception is thrown if decoding of Base64 data fails.
*
@@ -29,58 +29,54 @@
*/
public class Base64DecodingException extends XMLSecurityException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ 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);
+ }
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.exceptions;
-
-
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.MessageFormat;
@@ -29,7 +29,6 @@
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
-
/**
* The mother of all Exceptions in this bundle. It allows exceptions to have
* their messages translated to the different locales.
@@ -64,186 +63,154 @@
*/
public class XMLSecurityException extends Exception {
-
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- /** Field originalException */
- protected Exception originalException = null;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
- /** Field msgID */
- protected String msgID;
-
- /**
- * Constructor XMLSecurityException
- *
- */
- public XMLSecurityException() {
-
- super("Missing message string");
+ /** Field msgID */
+ protected String msgID;
- this.msgID = null;
- this.originalException = null;
- }
+ /**
+ * Constructor XMLSecurityException
+ *
+ */
+ public XMLSecurityException() {
+ super("Missing message string");
- /**
- * Constructor XMLSecurityException
- *
- * @param _msgID
- */
- public XMLSecurityException(String _msgID) {
+ this.msgID = null;
+ }
- super(I18n.getExceptionMessage(_msgID));
-
- this.msgID = _msgID;
- this.originalException = null;
- }
+ /**
+ * Constructor XMLSecurityException
+ *
+ * @param msgID
+ */
+ public XMLSecurityException(String msgID) {
+ super(I18n.getExceptionMessage(msgID));
- /**
- * Constructor XMLSecurityException
- *
- * @param _msgID
- * @param exArgs
- */
- public XMLSecurityException(String _msgID, Object exArgs[]) {
+ this.msgID = msgID;
+ }
- super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
-
- this.msgID = _msgID;
- this.originalException = null;
- }
+ /**
+ * Constructor XMLSecurityException
+ *
+ * @param msgID
+ * @param exArgs
+ */
+ public XMLSecurityException(String msgID, Object exArgs[]) {
- /**
- * Constructor XMLSecurityException
- *
- * @param _originalException
- */
- public XMLSecurityException(Exception _originalException) {
+ super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
- super("Missing message ID to locate message string in resource bundle \""
- + Constants.exceptionMessagesResourceBundleBase
- + "\". Original Exception was a "
- + _originalException.getClass().getName() + " and message "
- + _originalException.getMessage());
-
- this.originalException = _originalException;
- }
+ this.msgID = msgID;
+ }
- /**
- * Constructor XMLSecurityException
- *
- * @param _msgID
- * @param _originalException
- */
- public XMLSecurityException(String _msgID, Exception _originalException) {
-
- super(I18n.getExceptionMessage(_msgID, _originalException));
+ /**
+ * Constructor XMLSecurityException
+ *
+ * @param originalException
+ */
+ public XMLSecurityException(Exception originalException) {
- this.msgID = _msgID;
- this.originalException = _originalException;
- }
+ super("Missing message ID to locate message string in resource bundle \""
+ + Constants.exceptionMessagesResourceBundleBase
+ + "\". Original Exception was a "
+ + originalException.getClass().getName() + " and message "
+ + originalException.getMessage(), originalException);
+ }
- /**
- * Constructor XMLSecurityException
- *
- * @param _msgID
- * @param exArgs
- * @param _originalException
- */
- public XMLSecurityException(String _msgID, Object exArgs[],
- Exception _originalException) {
+ /**
+ * Constructor XMLSecurityException
+ *
+ * @param msgID
+ * @param originalException
+ */
+ public XMLSecurityException(String msgID, Exception originalException) {
+ super(I18n.getExceptionMessage(msgID, originalException), originalException);
+
+ this.msgID = msgID;
+ }
- super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
-
- this.msgID = _msgID;
- this.originalException = _originalException;
- }
+ /**
+ * Constructor XMLSecurityException
+ *
+ * @param msgID
+ * @param exArgs
+ * @param originalException
+ */
+ public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) {
+ super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException);
- /**
- * Method getMsgID
- *
- * @return the messageId
- */
- public String getMsgID() {
-
- if (msgID == null) {
- return "Missing message ID";
- }
- return msgID;
- }
-
- /** @inheritDoc */
- public String toString() {
+ this.msgID = msgID;
+ }
- String s = this.getClass().getName();
- String message = super.getLocalizedMessage();
-
- if (message != null) {
- message = s + ": " + message;
- } else {
- message = s;
- }
+ /**
+ * Method getMsgID
+ *
+ * @return the messageId
+ */
+ public String getMsgID() {
+ if (msgID == null) {
+ return "Missing message ID";
+ }
+ return msgID;
+ }
- if (originalException != null) {
- message = message + "\nOriginal Exception was "
- + originalException.toString();
- }
+ /** @inheritDoc */
+ public String toString() {
+ String s = this.getClass().getName();
+ String message = super.getLocalizedMessage();
- return message;
- }
+ if (message != null) {
+ message = s + ": " + message;
+ } else {
+ message = s;
+ }
- /**
- * Method printStackTrace
- *
- */
- public void printStackTrace() {
+ if (super.getCause() != null) {
+ message = message + "\nOriginal Exception was " + super.getCause().toString();
+ }
- synchronized (System.err) {
- super.printStackTrace(System.err);
-
- if (this.originalException != null) {
- this.originalException.printStackTrace(System.err);
- }
- }
- }
+ return message;
+ }
- /**
- * Method printStackTrace
- *
- * @param printwriter
- */
- public void printStackTrace(PrintWriter printwriter) {
+ /**
+ * Method printStackTrace
+ *
+ */
+ public void printStackTrace() {
+ synchronized (System.err) {
+ super.printStackTrace(System.err);
+ }
+ }
- super.printStackTrace(printwriter);
-
- if (this.originalException != null) {
- this.originalException.printStackTrace(printwriter);
- }
- }
+ /**
+ * Method printStackTrace
+ *
+ * @param printwriter
+ */
+ public void printStackTrace(PrintWriter printwriter) {
+ super.printStackTrace(printwriter);
+ }
- /**
- * Method printStackTrace
- *
- * @param printstream
- */
- public void printStackTrace(PrintStream printstream) {
-
- super.printStackTrace(printstream);
+ /**
+ * Method 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java Fri Jul 05 14:37:41 2013 -0700
@@ -1,3 +1,25 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
package com.sun.org.apache.xml.internal.security.exceptions;
import java.io.PrintStream;
@@ -39,186 +61,152 @@
*
* @author Christian Geuer-Pollmann
*/
-public class XMLSecurityRuntimeException
- extends RuntimeException {
- /**
- *
- */
+public class XMLSecurityRuntimeException extends RuntimeException {
+
private static final long serialVersionUID = 1L;
- /** Field originalException */
- protected Exception originalException = null;
-
- /** Field msgID */
- protected String msgID;
+ /** Field msgID */
+ protected String msgID;
- /**
- * Constructor XMLSecurityRuntimeException
- *
- */
- public XMLSecurityRuntimeException() {
+ /**
+ * Constructor XMLSecurityRuntimeException
+ *
+ */
+ public XMLSecurityRuntimeException() {
+ super("Missing message string");
- super("Missing message string");
-
- this.msgID = null;
- this.originalException = null;
- }
+ this.msgID = null;
+ }
- /**
- * Constructor XMLSecurityRuntimeException
- *
- * @param _msgID
- */
- public XMLSecurityRuntimeException(String _msgID) {
-
- super(I18n.getExceptionMessage(_msgID));
+ /**
+ * Constructor XMLSecurityRuntimeException
+ *
+ * @param msgID
+ */
+ public XMLSecurityRuntimeException(String msgID) {
+ super(I18n.getExceptionMessage(msgID));
- this.msgID = _msgID;
- this.originalException = null;
- }
+ this.msgID = msgID;
+ }
- /**
- * Constructor XMLSecurityRuntimeException
- *
- * @param _msgID
- * @param exArgs
- */
- public XMLSecurityRuntimeException(String _msgID, Object exArgs[]) {
-
- super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
+ /**
+ * Constructor XMLSecurityRuntimeException
+ *
+ * @param msgID
+ * @param exArgs
+ */
+ public XMLSecurityRuntimeException(String msgID, Object exArgs[]) {
+ super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
- this.msgID = _msgID;
- this.originalException = null;
- }
+ this.msgID = msgID;
+ }
- /**
- * Constructor XMLSecurityRuntimeException
- *
- * @param _originalException
- */
- public XMLSecurityRuntimeException(Exception _originalException) {
-
- super("Missing message ID to locate message string in resource bundle \""
- + Constants.exceptionMessagesResourceBundleBase
- + "\". Original Exception was a "
- + _originalException.getClass().getName() + " and message "
- + _originalException.getMessage());
-
- this.originalException = _originalException;
- }
+ /**
+ * Constructor XMLSecurityRuntimeException
+ *
+ * @param originalException
+ */
+ public XMLSecurityRuntimeException(Exception originalException) {
+ super("Missing message ID to locate message string in resource bundle \""
+ + Constants.exceptionMessagesResourceBundleBase
+ + "\". Original Exception was a "
+ + originalException.getClass().getName() + " and message "
+ + originalException.getMessage(), originalException);
+ }
- /**
- * Constructor XMLSecurityRuntimeException
- *
- * @param _msgID
- * @param _originalException
- */
- public XMLSecurityRuntimeException(String _msgID, Exception _originalException) {
-
- super(I18n.getExceptionMessage(_msgID, _originalException));
+ /**
+ * Constructor XMLSecurityRuntimeException
+ *
+ * @param msgID
+ * @param originalException
+ */
+ public XMLSecurityRuntimeException(String msgID, Exception originalException) {
+ super(I18n.getExceptionMessage(msgID, originalException), originalException);
- this.msgID = _msgID;
- this.originalException = _originalException;
- }
+ this.msgID = msgID;
+ }
- /**
- * Constructor XMLSecurityRuntimeException
- *
- * @param _msgID
- * @param exArgs
- * @param _originalException
- */
- public XMLSecurityRuntimeException(String _msgID, Object exArgs[],
- Exception _originalException) {
-
- super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs));
+ /**
+ * Constructor XMLSecurityRuntimeException
+ *
+ * @param msgID
+ * @param exArgs
+ * @param originalException
+ */
+ public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) {
+ super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs));
- this.msgID = _msgID;
- this.originalException = _originalException;
- }
+ this.msgID = msgID;
+ }
- /**
- * Method getMsgID
- *
- * @return the messageId
- */
- public String getMsgID() {
-
- if (msgID == null) {
- return "Missing message ID";
- }
- return msgID;
- }
-
- /** @inheritDoc */
- public String toString() {
+ /**
+ * Method getMsgID
+ *
+ * @return the messageId
+ */
+ public String getMsgID() {
+ if (msgID == null) {
+ return "Missing message ID";
+ }
+ return msgID;
+ }
- String s = this.getClass().getName();
- String message = super.getLocalizedMessage();
-
- if (message != null) {
- message = s + ": " + message;
- } else {
- message = s;
- }
+ /** @inheritDoc */
+ public String toString() {
+ String s = this.getClass().getName();
+ String message = super.getLocalizedMessage();
- if (originalException != null) {
- message = message + "\nOriginal Exception was "
- + originalException.toString();
- }
+ if (message != null) {
+ message = s + ": " + message;
+ } else {
+ message = s;
+ }
- return message;
- }
+ if (this.getCause() != null) {
+ message = message + "\nOriginal Exception was " + this.getCause().toString();
+ }
- /**
- * Method printStackTrace
- *
- */
- public void printStackTrace() {
+ return message;
+ }
- synchronized (System.err) {
- super.printStackTrace(System.err);
-
- if (this.originalException != null) {
- this.originalException.printStackTrace(System.err);
- }
- }
- }
+ /**
+ * Method printStackTrace
+ *
+ */
+ public void printStackTrace() {
+ synchronized (System.err) {
+ super.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 printwriter
+ */
+ public void printStackTrace(PrintWriter printwriter) {
+ super.printStackTrace(printwriter);
+ }
- /**
- * Method printStackTrace
- *
- * @param printstream
- */
- public void printStackTrace(PrintStream printstream) {
-
- super.printStackTrace(printstream);
+ /**
+ * 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() {
+ if (this.getCause() instanceof Exception) {
+ return (Exception)this.getCause();
+ }
+ return null;
+ }
- /**
- * Method getOriginalException
- *
- * @return the original exception
- */
- public Exception getOriginalException() {
- return originalException;
- }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,89 +2,83 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys;
-
-
+import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.Iterator;
import java.util.List;
@@ -35,6 +35,8 @@
import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue;
+import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference;
import com.sun.org.apache.xml.internal.security.keys.content.KeyName;
import com.sun.org.apache.xml.internal.security.keys.content.KeyValue;
import com.sun.org.apache.xml.internal.security.keys.content.MgmtData;
@@ -49,9 +51,8 @@
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
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.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr;
@@ -60,7 +61,6 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-
/**
* This class stand for KeyInfo Element that may contain keys, names,
* certificates and other public key management information,
@@ -91,639 +91,769 @@
* The <CODE>containsXXX()</CODE> methods return <I>whether</I> 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<X509Data> x509Datas=null;
- List<EncryptedKey> encryptedKeys=null;
+
+ // We need at least one StorageResolver otherwise
+ // the KeyResolvers would not be called.
+ // The default StorageResolver is null.
- static final List<StorageResolver> nullList;
+ private List<X509Data> x509Datas = null;
+ private List<EncryptedKey> encryptedKeys = null;
+
+ private static final List<StorageResolver> nullList;
static {
List<StorageResolver> list = new ArrayList<StorageResolver>(1);
list.add(null);
- nullList = Collections.unmodifiableList(list);
+ nullList = java.util.Collections.unmodifiableList(list);
+ }
+
+ /** Field storageResolvers */
+ private List<StorageResolver> storageResolvers = nullList;
+
+ /**
+ * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s
+ */
+ private List<KeyResolverSpi> internalKeyResolvers = new ArrayList<KeyResolverSpi>();
+
+ 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 <code>Id</code> 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 <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> 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);
}
- /**
- * 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);
+ /**
+ * Method add
+ *
+ * @param spkidata
+ */
+ public void add(SPKIData spkidata) {
+ this.constructionElement.appendChild(spkidata.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- Attr attr = element.getAttributeNodeNS(null, "Id");
- if (attr != null) {
- element.setIdAttributeNode(attr, true);
- }
- }
-
- /**
- * Sets the <code>Id</code> attribute
- *
- * @param Id ID
- */
- public void setId(String Id) {
+ /**
+ * Method addX509Data
+ *
+ * @param x509data
+ */
+ public void add(X509Data x509data) {
+ if (x509Datas == null) {
+ x509Datas = new ArrayList<X509Data>();
+ }
+ x509Datas.add(x509data);
+ this.constructionElement.appendChild(x509data.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- if (Id != null) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
+ /**
+ * Method addEncryptedKey
+ *
+ * @param encryptedKey
+ * @throws XMLEncryptionException
+ */
- /**
- * Returns the <code>Id</code> attribute
- *
- * @return the <code>Id</code> attribute
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
+ public void add(EncryptedKey encryptedKey) throws XMLEncryptionException {
+ if (encryptedKeys == null) {
+ encryptedKeys = new ArrayList<EncryptedKey>();
+ }
+ encryptedKeys.add(encryptedKey);
+ XMLCipher cipher = XMLCipher.getInstance();
+ this.constructionElement.appendChild(cipher.martial(encryptedKey));
+ }
- /**
- * Method addKeyName
- *
- * @param keynameString
- */
- public void addKeyName(String keynameString) {
- this.add(new KeyName(this._doc, keynameString));
- }
+ /**
+ * Method addDEREncodedKeyValue
+ *
+ * @param pk
+ * @throws XMLSecurityException
+ */
+ public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException {
+ this.add(new DEREncodedKeyValue(this.doc, pk));
+ }
- /**
- * Method add
- *
- * @param keyname
- */
- public void add(KeyName keyname) {
-
- this._constructionElement.appendChild(keyname.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method add
+ *
+ * @param derEncodedKeyValue
+ */
+ public void add(DEREncodedKeyValue derEncodedKeyValue) {
+ this.constructionElement.appendChild(derEncodedKeyValue.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 addKeyInfoReference
+ *
+ * @param URI
+ * @throws XMLSecurityException
+ */
+ public void addKeyInfoReference(String URI) throws XMLSecurityException {
+ this.add(new KeyInfoReference(this.doc, URI));
+ }
- /**
- * Method add
- *
- * @param dsakeyvalue
- */
- public void add(DSAKeyValue dsakeyvalue) {
- this.add(new KeyValue(this._doc, dsakeyvalue));
- }
+ /**
+ * Method add
+ *
+ * @param keyInfoReference
+ */
+ public void add(KeyInfoReference keyInfoReference) {
+ this.constructionElement.appendChild(keyInfoReference.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method add
- *
- * @param rsakeyvalue
- */
- public void add(RSAKeyValue rsakeyvalue) {
- this.add(new KeyValue(this._doc, rsakeyvalue));
- }
+ /**
+ * Method addUnknownElement
+ *
+ * @param element
+ */
+ public void addUnknownElement(Element element) {
+ this.constructionElement.appendChild(element);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method add
- *
- * @param pk
- */
- public void add(PublicKey pk) {
- this.add(new KeyValue(this._doc, pk));
- }
+ /**
+ * Method lengthKeyName
+ *
+ * @return the number of the KeyName tags
+ */
+ public int lengthKeyName() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME);
+ }
- /**
- * Method add
- *
- * @param keyvalue
- */
- public void add(KeyValue keyvalue) {
- this._constructionElement.appendChild(keyvalue.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method lengthKeyValue
+ *
+ *@return the number of the KeyValue tags
+ */
+ public int lengthKeyValue() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE);
+ }
- /**
- * Method addMgmtData
- *
- * @param mgmtdata
- */
- public void addMgmtData(String mgmtdata) {
- this.add(new MgmtData(this._doc, mgmtdata));
- }
+ /**
+ * Method lengthMgmtData
+ *
+ *@return the number of the MgmtData tags
+ */
+ public int lengthMgmtData() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA);
+ }
- /**
- * Method add
- *
- * @param mgmtdata
- */
- public void add(MgmtData mgmtdata) {
- this._constructionElement.appendChild(mgmtdata.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method lengthPGPData
+ *
+ *@return the number of the PGPDat. tags
+ */
+ public int lengthPGPData() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA);
+ }
- /**
- * Method addPGPData
- *
- * @param pgpdata
- */
- public void add(PGPData pgpdata) {
- this._constructionElement.appendChild(pgpdata.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method lengthRetrievalMethod
+ *
+ *@return the number of the RetrievalMethod tags
+ */
+ public int lengthRetrievalMethod() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_RETRIEVALMETHOD);
+ }
- /**
- * 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 lengthSPKIData
+ *
+ *@return the number of the SPKIData tags
+ */
+ public int lengthSPKIData() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA);
+ }
- /**
- * Method add
- *
- * @param retrievalmethod
- */
- public void add(RetrievalMethod retrievalmethod) {
- this._constructionElement.appendChild(retrievalmethod.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * 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 add
- *
- * @param spkidata
- */
- public void add(SPKIData spkidata) {
- this._constructionElement.appendChild(spkidata.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method lengthKeyInfoReference
+ *
+ *@return the number of the KeyInfoReference tags
+ */
+ public int lengthKeyInfoReference() {
+ return this.length(Constants.SignatureSpec11NS, Constants._TAG_KEYINFOREFERENCE);
+ }
- /**
- * Method addX509Data
- *
- * @param x509data
- */
- public void add(X509Data x509data) {
- if (x509Datas==null)
- x509Datas=new ArrayList<X509Data>();
- x509Datas.add(x509data);
- this._constructionElement.appendChild(x509data.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method lengthUnknownElement
+ * NOTE possibly buggy.
+ * @return the number of the UnknownElement tags
+ */
+ public int lengthUnknownElement() {
+ int res = 0;
+ NodeList nl = this.constructionElement.getChildNodes();
- /**
- * Method addEncryptedKey
- *
- * @param encryptedKey
- * @throws XMLEncryptionException
- */
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node current = nl.item(i);
- public void add(EncryptedKey encryptedKey)
- throws XMLEncryptionException {
- if (encryptedKeys==null)
- encryptedKeys=new ArrayList<EncryptedKey>();
- encryptedKeys.add(encryptedKey);
- XMLCipher cipher = XMLCipher.getInstance();
- this._constructionElement.appendChild(cipher.martial(encryptedKey));
+ /**
+ * $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++;
+ }
}
- /**
- * Method addUnknownElement
- *
- * @param element
- */
- public void addUnknownElement(Element element) {
- this._constructionElement.appendChild(element);
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ return res;
+ }
- /**
- * 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 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);
- /**
- * 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);
- }
+ if (e != null) {
+ return new KeyName(e, this.baseURI);
+ }
+ return null;
+ }
- /**
- * 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);
+ /**
+ * 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);
- /**
- * $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 {
+ if (e != null) {
+ return new KeyValue(e, this.baseURI);
+ }
+ return null;
+ }
- 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);
- /**
- * 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 {
+ if (e != null) {
+ return new MgmtData(e, this.baseURI);
+ }
+ return null;
+ }
- Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- Constants._TAG_PGPDATA,i);
-
- if (e != null) {
- return new PGPData(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);
- /**
- * 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;
- }
+ if (e != null) {
+ return new PGPData(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 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);
- /**
- * 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
- */
+ if (e != null) {
+ return new RetrievalMethod(e, this.baseURI);
+ }
+ return null;
+ }
- 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) {
+ /**
+ * 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);
- 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;
- }
+ if (e != null) {
+ return new SPKIData(e, this.baseURI);
+ }
+ 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 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);
- /**
- * 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;
- }
+ if (e != null) {
+ return new X509Data(e, this.baseURI);
+ }
+ return null;
+ }
- /**
- * 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 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);
- /**
- * 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");
+ if (e != null) {
+ XMLCipher cipher = XMLCipher.getInstance();
+ cipher.init(XMLCipher.UNWRAP_MODE, null);
+ return cipher.loadEncryptedKey(e);
+ }
+ return null;
+ }
- return pk;
- }
- log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers");
-
- pk = this.getPublicKeyFromStaticResolvers();
+ /**
+ * 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 (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;
- }
+ if (e != null) {
+ return new DEREncodedKeyValue(e, this.baseURI);
+ }
+ return null;
+ }
/**
- * Searches the library wide keyresolvers for public keys
+ * 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 @@
Iterator<KeyResolverSpi> 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 @@
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());
+ }
+ 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
+ );
- 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();
+ }
+ }
- if (pk != null) {
- return pk;
- }
- }
- }
- currentChild=currentChild.getNextSibling();
- }
- }
-
- return null;
- }
+ return null;
+ }
- /**
- * Method getX509Certificate
- *
- * @return The certificate contined in this KeyInfo
- * @throws KeyResolverException
- */
- public X509Certificate getX509Certificate() throws KeyResolverException {
+ /**
+ * 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();
- // 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) {
- log.log(java.util.logging.Level.FINE,
- "I could find a X509Certificate using the system-wide 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 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 cert;
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers");
+ }
-
- return null;
- }
+ return null;
+ }
/**
* This method uses each System-wide {@link KeyResolver} to search the
@@ -846,6 +976,7 @@
Iterator<KeyResolverSpi> 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 @@
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 @@
/**
* Method getX509CertificateFromInternalResolvers
*
- * @return The certificate contined in this KeyInfo
+ * @return The certificate contained in this KeyInfo
* @throws KeyResolverException
*/
X509Certificate getX509CertificateFromInternalResolvers()
@@ -891,10 +1022,11 @@
);
}
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 @@
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) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers");
+ }
+
+ return sk;
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
+ }
+
+ sk = this.getSecretKeyFromStaticResolvers();
+
+ if (sk != null) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers");
+ }
+
+ return sk;
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers");
+ }
+
+ return null;
+ }
+
+ /**
+ * Searches the library wide KeyResolvers for Secret keys
+ *
+ * @return the secret key contained in this KeyInfo
+ * @throws KeyResolverException
+ */
+ SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException {
+ Iterator<KeyResolverSpi> 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) {
- log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers");
+ if (sk != null) {
+ return sk;
+ }
+ }
+ }
+ currentChild = currentChild.getNextSibling();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Searches the per-KeyInfo KeyResolvers for secret keys
+ *
+ * @return the secret key contained in this KeyInfo
+ * @throws KeyResolverException
+ */
+
+ SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
+ for (KeyResolverSpi keyResolver : internalKeyResolvers) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
+ }
+ keyResolver.setSecureValidation(secureValidation);
+ Node currentChild = this.constructionElement.getFirstChild();
+ String uri = this.getBaseURI();
+ while (currentChild != null) {
+ if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+ for (StorageResolver storage : storageResolvers) {
+ SecretKey sk =
+ keyResolver.engineLookupAndResolveSecretKey(
+ (Element) currentChild, uri, storage
+ );
+
+ if (sk != null) {
+ return sk;
+ }
+ }
+ }
+ currentChild = currentChild.getNextSibling();
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * This method returns a private key. This is for Key Transport in XML Encryption.
+ * @return the private key contained in this KeyInfo
+ * @throws KeyResolverException
+ */
+ public PrivateKey getPrivateKey() throws KeyResolverException {
+ PrivateKey pk = this.getPrivateKeyFromInternalResolvers();
+
+ if (pk != null) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I could find a private key using the per-KeyInfo key resolvers");
+ }
+ return pk;
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
+ }
- return sk;
- }
- log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers");
+ pk = this.getPrivateKeyFromStaticResolvers();
+ if (pk != null) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I could find a private key using the system-wide key resolvers");
+ }
+ return pk;
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I couldn't find a private key using the system-wide key resolvers");
+ }
+
+ return null;
+ }
+ /**
+ * Searches the library wide KeyResolvers for Private keys
+ *
+ * @return the private key contained in this KeyInfo
+ * @throws KeyResolverException
+ */
+ PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException {
+ Iterator<KeyResolverSpi> it = KeyResolver.iterator();
+ while (it.hasNext()) {
+ KeyResolverSpi keyResolver = it.next();
+ keyResolver.setSecureValidation(secureValidation);
- sk = this.getSecretKeyFromStaticResolvers();
+ Node currentChild = this.constructionElement.getFirstChild();
+ String uri = this.getBaseURI();
+ while (currentChild != null) {
+ if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+ // not using StorageResolvers at the moment
+ // since they cannot return private keys
+ PrivateKey pk =
+ keyResolver.engineLookupAndResolvePrivateKey(
+ (Element) currentChild, uri, null
+ );
+
+ if (pk != null) {
+ return pk;
+ }
+ }
+ currentChild = currentChild.getNextSibling();
+ }
+ }
+ return null;
+ }
- if (sk != null) {
- log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers");
+ /**
+ * Searches the per-KeyInfo KeyResolvers for private keys
+ *
+ * @return the private key contained in this KeyInfo
+ * @throws KeyResolverException
+ */
+ PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException {
+ for (KeyResolverSpi keyResolver : internalKeyResolvers) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
+ }
+ keyResolver.setSecureValidation(secureValidation);
+ Node currentChild = this.constructionElement.getFirstChild();
+ String uri = this.getBaseURI();
+ while (currentChild != null) {
+ if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
+ // not using StorageResolvers at the moment
+ // since they cannot return private keys
+ PrivateKey pk =
+ keyResolver.engineLookupAndResolvePrivateKey(
+ (Element) currentChild, uri, null
+ );
+
+ if (pk != null) {
+ return pk;
+ }
+ }
+ currentChild = currentChild.getNextSibling();
+ }
+ }
+
+ return null;
+ }
- return sk;
- }
- log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers");
+ /**
+ * 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<StorageResolver>();
+ }
+ this.storageResolvers.add(storageResolver);
+ }
- 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<KeyResolverSpi> it = KeyResolver.iterator();
- for (int i = 0; i < length; i++) {
- KeyResolverSpi keyResolver = it.next();
-
- Node currentChild=this._constructionElement.getFirstChild();
- String uri=this.getBaseURI();
- while (currentChild!=null) {
- if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
- for (int k = 0; k < storageLength; k++) {
- StorageResolver storage =
- this._storageResolvers.get(k);
-
- SecretKey sk =
- keyResolver.engineLookupAndResolveSecretKey((Element) currentChild,
- uri,
- storage);
-
- if (sk != null) {
- return sk;
- }
- }
- }
- currentChild=currentChild.getNextSibling();
- }
- }
- return null;
- }
-
- /**
- * Searches the per-KeyInfo keyresolvers for secret keys
- *
- * @return the secret key contained in this KeyInfo
- * @throws KeyResolverException
- */
-
- SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException {
- int storageLength=this._storageResolvers.size();
- for (int i = 0; i < this.lengthInternalKeyResolver(); i++) {
- KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i);
- if (log.isLoggable(java.util.logging.Level.FINE))
- log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName());
-
- Node currentChild=this._constructionElement.getFirstChild();
- String uri=this.getBaseURI();
- while (currentChild!=null) {
- if (currentChild.getNodeType() == Node.ELEMENT_NODE) {
- for (int k = 0; k < storageLength; k++) {
- StorageResolver storage =
- this._storageResolvers.get(k);
-
- SecretKey sk = keyResolver
- .engineLookupAndResolveSecretKey((Element) currentChild, uri, storage);
-
- if (sk != null) {
- return sk;
- }
- }
- }
- currentChild=currentChild.getNextSibling();
- }
- }
-
- return null;
- }
-
- /**
- * Stores the individual (per-KeyInfo) {@link KeyResolver}s
- */
- List<KeyResolverSpi> _internalKeyResolvers = new ArrayList<KeyResolverSpi>();
-
- /**
- * 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<KeyResolverSpi>();
- }
- this._internalKeyResolvers.add(realKeyResolver);
- }
-
- /**
- * Method lengthInternalKeyResolver
- * @return the length of the key
- */
- int lengthInternalKeyResolver() {
- if (_internalKeyResolvers==null)
- return 0;
- return this._internalKeyResolvers.size();
- }
-
- /**
- * Method itemInternalKeyResolver
- *
- * @param i the index
- * @return the KeyResolverSpi for the index.
- */
- KeyResolverSpi itemInternalKeyResolver(int i) {
- return this._internalKeyResolvers.get(i);
- }
-
- /** Field _storageResolvers */
- private List<StorageResolver> _storageResolvers = nullList;
-
- /**
- * Method addStorageResolver
- *
- * @param storageResolver
- */
- public void addStorageResolver(StorageResolver storageResolver) {
- if (_storageResolvers == nullList ){
- _storageResolvers=new ArrayList<StorageResolver>();
- }
- this._storageResolvers.add(storageResolver);
-
- }
-
- //J-
- static boolean _alreadyInitialized = false;
- /** init the keyinfo (Still needed?)*/
- public static void init() {
-
- if (!KeyInfo._alreadyInitialized) {
- if (KeyInfo.log == null) {
-
- /**
- * $todo$ why the hell does the static initialization from the
- * start not work ?
- */
- KeyInfo.log =
- java.util.logging.Logger.getLogger(KeyInfo.class.getName());
-
- log.log(java.util.logging.Level.SEVERE, "Had to assign log in the init() function");
- }
-
- // KeyInfo._contentHandlerHash = new HashMap(10);
- KeyInfo._alreadyInitialized = true;
- }
- }
-
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_KEYINFO;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_KEYINFO;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys;
-
-
import java.io.PrintStream;
import java.security.PublicKey;
@@ -31,57 +31,53 @@
import com.sun.org.apache.xml.internal.security.keys.content.MgmtData;
import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
-
/**
* Utility class for for <CODE>com.sun.org.apache.xml.internal.security.keys</CODE> 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 " : "") + "\"");
+ }
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>dsig11:DEREncodedKeyvalue</code> 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 <code>Id</code> 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 <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> 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);
+ }
+ }
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,32 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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 {
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>dsig11:KeyInfoReference</code> 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 <code>Id</code> 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 <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> attribute
+ */
+ public String getId() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ }
+
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_KEYINFOREFERENCE;
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content;
@@ -27,46 +29,44 @@
import org.w3c.dom.Element;
/**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
*/
public class KeyName extends SignatureElementProxy implements KeyInfoContent {
- /**
- * Constructor KeyName
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public KeyName(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
- }
-
- /**
- * Constructor KeyName
- *
- * @param doc
- * @param keyName
- */
- public KeyName(Document doc, String keyName) {
+ /**
+ * Constructor KeyName
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public KeyName(Element element, String BaseURI) throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- super(doc);
+ /**
+ * Constructor KeyName
+ *
+ * @param doc
+ * @param keyName
+ */
+ public KeyName(Document doc, String keyName) {
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content;
@@ -39,7 +41,7 @@
* keys values represented as PCDATA or element types from an external
* namespace.
*
- * @author $Author: mullan $
+ * @author $Author: coheigea $
*/
public class KeyValue extends SignatureElementProxy implements KeyInfoContent {
@@ -50,12 +52,11 @@
* @param dsaKeyValue
*/
public KeyValue(Document doc, DSAKeyValue dsaKeyValue) {
-
super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
- this._constructionElement.appendChild(dsaKeyValue.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ this.constructionElement.appendChild(dsaKeyValue.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -65,12 +66,11 @@
* @param rsaKeyValue
*/
public KeyValue(Document doc, RSAKeyValue rsaKeyValue) {
-
super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
- this._constructionElement.appendChild(rsaKeyValue.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ this.constructionElement.appendChild(rsaKeyValue.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -80,12 +80,11 @@
* @param unknownKeyValue
*/
public KeyValue(Document doc, Element unknownKeyValue) {
-
super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
- this._constructionElement.appendChild(unknownKeyValue);
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ this.constructionElement.appendChild(unknownKeyValue);
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -95,21 +94,20 @@
* @param pk
*/
public KeyValue(Document doc, PublicKey pk) {
-
super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
if (pk instanceof java.security.interfaces.DSAPublicKey) {
- DSAKeyValue dsa = new DSAKeyValue(this._doc, pk);
+ DSAKeyValue dsa = new DSAKeyValue(this.doc, pk);
- this._constructionElement.appendChild(dsa.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
+ this.constructionElement.appendChild(dsa.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
} else if (pk instanceof java.security.interfaces.RSAPublicKey) {
- RSAKeyValue rsa = new RSAKeyValue(this._doc, pk);
+ RSAKeyValue rsa = new RSAKeyValue(this.doc, pk);
- this._constructionElement.appendChild(rsa.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
+ this.constructionElement.appendChild(rsa.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
}
}
@@ -120,8 +118,7 @@
* @param BaseURI
* @throws XMLSecurityException
*/
- public KeyValue(Element element, String BaseURI)
- throws XMLSecurityException {
+ public KeyValue(Element element, String BaseURI) throws XMLSecurityException {
super(element, BaseURI);
}
@@ -132,22 +129,21 @@
* @throws XMLSecurityException
*/
public PublicKey getPublicKey() throws XMLSecurityException {
-
- Element rsa = XMLUtils.selectDsNode
- (this._constructionElement.getFirstChild(),
- Constants._TAG_RSAKEYVALUE,0);
+ Element rsa =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
if (rsa != null) {
- RSAKeyValue kv = new RSAKeyValue(rsa, this._baseURI);
+ RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI);
return kv.getPublicKey();
}
- Element dsa = XMLUtils.selectDsNode
- (this._constructionElement.getFirstChild(),
- Constants._TAG_DSAKEYVALUE,0);
+ Element dsa =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
if (dsa != null) {
- DSAKeyValue kv = new DSAKeyValue(dsa, this._baseURI);
+ DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI);
return kv.getPublicKey();
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content;
@@ -27,47 +29,45 @@
import org.w3c.dom.Element;
/**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
*/
public class MgmtData extends SignatureElementProxy implements KeyInfoContent {
- /**
- * Constructor MgmtData
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public MgmtData(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
-
- /**
- * Constructor MgmtData
- *
- * @param doc
- * @param mgmtData
- */
- public MgmtData(Document doc, String mgmtData) {
+ /**
+ * Constructor MgmtData
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public MgmtData(Element element, String BaseURI)
+ throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- super(doc);
+ /**
+ * Constructor MgmtData
+ *
+ * @param doc
+ * @param mgmtData
+ */
+ public MgmtData(Document doc, String mgmtData) {
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content;
@@ -26,25 +28,24 @@
import org.w3c.dom.Element;
/**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
* $todo$ Implement
*/
public class PGPData extends SignatureElementProxy implements KeyInfoContent {
- /**
- * Constructor PGPData
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public PGPData(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Constructor PGPData
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public PGPData(Element element, String BaseURI) throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_PGPDATA;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_PGPDATA;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content;
@@ -30,118 +32,104 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- *
- * @author $Author: mullan $
- */
-public class RetrievalMethod extends SignatureElementProxy
- implements KeyInfoContent {
+public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent {
- //J-
/** DSA retrieval */
- public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue";
- /** RSA retrieval */
- public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue";
- /** PGP retrieval */
- public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData";
- /** SPKI retrieval */
- public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData";
- /** MGMT retrieval */
- public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData";
- /** X509 retrieval */
- public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data";
- /** RAWX509 retrieval */
- public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate";
- //J+
+ 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 transforamitons
- */
- public Transforms getTransforms() throws XMLSecurityException {
-
- try {
- Element transformsElem =
- XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- Constants
- ._TAG_TRANSFORMS, 0);
+ /**
+ * Method getTransforms
+ *
+ * @throws XMLSecurityException
+ * @return the transformations
+ */
+ public Transforms getTransforms() throws XMLSecurityException {
+ try {
+ Element transformsElem =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0);
- if (transformsElem != null) {
- return new Transforms(transformsElem, this._baseURI);
- }
+ if (transformsElem != null) {
+ return new Transforms(transformsElem, this.baseURI);
+ }
- return null;
- } catch (XMLSignatureException ex) {
- throw new XMLSecurityException("empty", ex);
- }
- }
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content;
@@ -26,26 +28,25 @@
import org.w3c.dom.Element;
/**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
* $todo$ implement
*/
public class SPKIData extends SignatureElementProxy implements KeyInfoContent {
- /**
- * Constructor SPKIData
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public SPKIData(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Constructor SPKIData
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public SPKIData(Element element, String BaseURI)
+ throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_SPKIDATA;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_SPKIDATA;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,32 +2,33 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content;
-
-
import java.math.BigInteger;
import java.security.cert.X509Certificate;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509CRL;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
+import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName;
@@ -38,447 +39,501 @@
import org.w3c.dom.Element;
import org.w3c.dom.Node;
-
-/**
- *
- * @author $Author: mullan $
- */
public class X509Data extends SignatureElementProxy implements KeyInfoContent {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(X509Data.class.getName());
- /**
- * Constructor X509Data
- *
- * @param doc
- */
- public X509Data(Document doc) {
-
- super(doc);
+ /**
+ * Constructor X509Data
+ *
+ * @param doc
+ */
+ public X509Data(Document 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 {
+ /**
+ * Constructor X509Data
+ *
+ * @param element
+ * @param baseURI
+ * @throws XMLSecurityException
+ */
+ public X509Data(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
- 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);
- }
+ 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) {
+
+ 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 add
- *
- * @param xmlX509IssuerSerial
- */
- public void add(XMLX509IssuerSerial xmlX509IssuerSerial) {
-
- this._constructionElement
- .appendChild(xmlX509IssuerSerial.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method addSKI
+ *
+ * @param x509certificate
+ * @throws XMLSecurityException
+ */
+ public void addSKI(X509Certificate x509certificate)
+ throws XMLSecurityException {
+ this.add(new XMLX509SKI(this.doc, x509certificate));
+ }
- /**
- * Method addSKI
- *
- * @param skiBytes
- */
- public void addSKI(byte[] skiBytes) {
- this.add(new XMLX509SKI(this._doc, skiBytes));
- }
+ /**
+ * Method add
+ *
+ * @param xmlX509SKI
+ */
+ public void add(XMLX509SKI xmlX509SKI) {
+ this.constructionElement.appendChild(xmlX509SKI.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method addSKI
- *
- * @param x509certificate
- * @throws XMLSecurityException
- */
- public void addSKI(X509Certificate x509certificate)
- throws XMLSecurityException {
- this.add(new XMLX509SKI(this._doc, x509certificate));
- }
+ /**
+ * Method addSubjectName
+ *
+ * @param subjectName
+ */
+ public void addSubjectName(String subjectName) {
+ this.add(new XMLX509SubjectName(this.doc, subjectName));
+ }
- /**
- * Method add
- *
- * @param xmlX509SKI
- */
- public void add(XMLX509SKI xmlX509SKI) {
- this._constructionElement.appendChild(xmlX509SKI.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method addSubjectName
+ *
+ * @param x509certificate
+ */
+ public void addSubjectName(X509Certificate x509certificate) {
+ this.add(new XMLX509SubjectName(this.doc, x509certificate));
+ }
- /**
- * Method addSubjectName
- *
- * @param subjectName
- */
- public void addSubjectName(String subjectName) {
- this.add(new XMLX509SubjectName(this._doc, subjectName));
- }
+ /**
+ * Method add
+ *
+ * @param xmlX509SubjectName
+ */
+ public void add(XMLX509SubjectName xmlX509SubjectName) {
+ this.constructionElement.appendChild(xmlX509SubjectName.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method addSubjectName
- *
- * @param x509certificate
- */
- public void addSubjectName(X509Certificate x509certificate) {
- this.add(new XMLX509SubjectName(this._doc, x509certificate));
- }
+ /**
+ * Method addCertificate
+ *
+ * @param x509certificate
+ * @throws XMLSecurityException
+ */
+ public void addCertificate(X509Certificate x509certificate)
+ throws XMLSecurityException {
+ this.add(new XMLX509Certificate(this.doc, x509certificate));
+ }
- /**
- * Method add
- *
- * @param xmlX509SubjectName
- */
- public void add(XMLX509SubjectName xmlX509SubjectName) {
- this._constructionElement.appendChild(xmlX509SubjectName.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method addCertificate
+ *
+ * @param x509certificateBytes
+ */
+ public void addCertificate(byte[] x509certificateBytes) {
+ this.add(new XMLX509Certificate(this.doc, x509certificateBytes));
+ }
- /**
- * Method addCertificate
- *
- * @param x509certificate
- * @throws XMLSecurityException
- */
- public void addCertificate(X509Certificate x509certificate)
- throws XMLSecurityException {
- this.add(new XMLX509Certificate(this._doc, x509certificate));
- }
+ /**
+ * 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 addCertificate
- *
- * @param x509certificateBytes
- */
- public void addCertificate(byte[] x509certificateBytes) {
- this.add(new XMLX509Certificate(this._doc, x509certificateBytes));
- }
+ /**
+ * Method add
+ *
+ * @param xmlX509CRL
+ */
+ public void add(XMLX509CRL xmlX509CRL) {
+ this.constructionElement.appendChild(xmlX509CRL.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method add
- *
- * @param xmlX509Certificate
- */
- public void add(XMLX509Certificate xmlX509Certificate) {
- this._constructionElement.appendChild(xmlX509Certificate.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 addCRL
- *
- * @param crlBytes
- */
- public void addCRL(byte[] crlBytes) {
- this.add(new XMLX509CRL(this._doc, crlBytes));
- }
+ /**
+ * Method addDigest
+ *
+ * @param x509CertificateDigestByes
+ * @param algorithmURI
+ */
+ public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) {
+ this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI));
+ }
- /**
- * Method add
- *
- * @param xmlX509CRL
- */
- public void add(XMLX509CRL xmlX509CRL) {
- this._constructionElement.appendChild(xmlX509CRL.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method add
+ *
+ * @param XMLX509Digest
+ */
+ public void add(XMLX509Digest xmlX509Digest) {
+ this.constructionElement.appendChild(xmlX509Digest.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method addUnknownElement
- *
- * @param element
- */
- public void addUnknownElement(Element element) {
- this._constructionElement.appendChild(element);
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * Method addUnknownElement
+ *
+ * @param element
+ */
+ public void addUnknownElement(Element element) {
+ this.constructionElement.appendChild(element);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Method lengthIssuerSerial
- *
- * @return the number of IssuerSerial elements in this X509Data
- */
- public int lengthIssuerSerial() {
- return this.length(Constants.SignatureSpecNS,
- Constants._TAG_X509ISSUERSERIAL);
- }
+ /**
+ * Method lengthIssuerSerial
+ *
+ * @return the number of IssuerSerial elements in this X509Data
+ */
+ public int lengthIssuerSerial() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL);
+ }
+
+ /**
+ * Method lengthSKI
+ *
+ * @return the number of SKI elements in this X509Data
+ */
+ public int lengthSKI() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI);
+ }
- /**
- * Method lengthSKI
- *
- * @return the number of SKI elements in this X509Data
- */
- public int lengthSKI() {
- return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI);
- }
+ /**
+ * Method lengthSubjectName
+ *
+ * @return the number of SubjectName elements in this X509Data
+ */
+ public int lengthSubjectName() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME);
+ }
- /**
- * Method lengthSubjectName
- *
- * @return the number of SubjectName elements in this X509Data
- */
- public int lengthSubjectName() {
- return this.length(Constants.SignatureSpecNS,
- Constants._TAG_X509SUBJECTNAME);
- }
+ /**
+ * Method lengthCertificate
+ *
+ * @return the number of Certificate elements in this X509Data
+ */
+ public int lengthCertificate() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE);
+ }
+
+ /**
+ * Method lengthCRL
+ *
+ * @return the number of CRL elements in this X509Data
+ */
+ public int lengthCRL() {
+ return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL);
+ }
- /**
- * Method lengthCertificate
- *
- * @return the number of Certificate elements in this X509Data
- */
- public int lengthCertificate() {
- return this.length(Constants.SignatureSpecNS,
- Constants._TAG_X509CERTIFICATE);
- }
+ /**
+ * Method lengthDigest
+ *
+ * @return the number of X509Digest elements in this X509Data
+ */
+ public int lengthDigest() {
+ return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST);
+ }
- /**
- * Method lengthCRL
- *
- * @return the number of CRL elements in this X509Data
- */
- public int lengthCRL() {
- return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL);
- }
+ /**
+ * Method lengthUnknownElement
+ *
+ * @return the number of UnknownElement elements in this X509Data
+ */
+ public int lengthUnknownElement() {
+ int result = 0;
+ Node n = this.constructionElement.getFirstChild();
+ while (n != null){
+ if ((n.getNodeType() == Node.ELEMENT_NODE)
+ && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
+ result++;
+ }
+ n = n.getNextSibling();
+ }
- /**
- * 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){
+ return result;
+ }
- if ((n.getNodeType() == Node.ELEMENT_NODE)
- &&!n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
- result += 1;
- }
- n=n.getNextSibling();
- }
-
- return result;
- }
+ /**
+ * Method itemIssuerSerial
+ *
+ * @param i
+ * @return the X509IssuerSerial, null if not present
+ * @throws XMLSecurityException
+ */
+ public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException {
+ Element e =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
- /**
- * Method itemIssuerSerial
- *
- * @param i
- * @return the X509IssuerSerial, null if not present
- * @throws XMLSecurityException
- */
- public XMLX509IssuerSerial itemIssuerSerial(int i)
- throws XMLSecurityException {
+ if (e != null) {
+ return new XMLX509IssuerSerial(e, this.baseURI);
+ }
+ return null;
+ }
- Element e =
- XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- Constants._TAG_X509ISSUERSERIAL,i);
+ /**
+ * Method itemSKI
+ *
+ * @param i
+ * @return the X509SKI, null if not present
+ * @throws XMLSecurityException
+ */
+ public XMLX509SKI itemSKI(int i) throws XMLSecurityException {
- if (e != null) {
- return new XMLX509IssuerSerial(e, this._baseURI);
- }
- return null;
- }
+ Element e =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i);
- /**
- * Method itemSKI
- *
- * @param i
- * @return the X509SKI, null if not present
- * @throws XMLSecurityException
- */
- public XMLX509SKI itemSKI(int i) throws XMLSecurityException {
+ if (e != null) {
+ return new XMLX509SKI(e, this.baseURI);
+ }
+ return null;
+ }
- Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- Constants._TAG_X509SKI,i);
+ /**
+ * Method itemSubjectName
+ *
+ * @param i
+ * @return the X509SubjectName, null if not present
+ * @throws XMLSecurityException
+ */
+ public XMLX509SubjectName itemSubjectName(int i) throws XMLSecurityException {
+
+ Element e =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
- if (e != null) {
- return new XMLX509SKI(e, this._baseURI);
- }
- return null;
- }
+ if (e != null) {
+ return new XMLX509SubjectName(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 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_X509SUBJECTNAME,i);
+ Element e =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
- if (e != null) {
- return new XMLX509SubjectName(e, this._baseURI);
- }
- return null;
- }
+ if (e != null) {
+ return new XMLX509Certificate(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 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_X509CERTIFICATE,i);
+ Element e =
+ XMLUtils.selectDsNode(
+ this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i);
- if (e != null) {
- return new XMLX509Certificate(e, this._baseURI);
- }
- return null;
- }
+ if (e != null) {
+ return new XMLX509CRL(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 itemDigest
+ *
+ * @param i
+ * @return the X509Digest, null if not present
+ * @throws XMLSecurityException
+ */
+ public XMLX509Digest itemDigest(int i) throws XMLSecurityException {
- Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- Constants._TAG_X509CRL,i);
+ Element e =
+ XMLUtils.selectDs11Node(
+ this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i);
- if (e != null) {
- return new XMLX509CRL(e, this._baseURI);
- }
- return null;
- }
+ if (e != null) {
+ return new XMLX509Digest(e, this.baseURI);
+ }
+ return null;
+ }
- /**
- * Method itemUnknownElement
- *
- * @param i
- * @return the Unknown Element at i
- * TODO implement
- **/
- public Element itemUnknownElement(int i) {
- log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i);
- return null;
- }
+ /**
+ * Method itemUnknownElement
+ *
+ * @param i
+ * @return the Unknown Element at i
+ * TODO implement
+ **/
+ public Element itemUnknownElement(int i) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:" + i);
+ }
+ return null;
+ }
- /**
- * Method containsIssuerSerial
- *
- * @return true if this X509Data contains a IssuerSerial
- */
- public boolean containsIssuerSerial() {
- return this.lengthIssuerSerial() > 0;
- }
+ /**
+ * Method containsIssuerSerial
+ *
+ * @return true if this X509Data contains a IssuerSerial
+ */
+ public boolean containsIssuerSerial() {
+ return this.lengthIssuerSerial() > 0;
+ }
- /**
- * Method containsSKI
- *
- * @return true if this X509Data contains a SKI
- */
- public boolean containsSKI() {
- return this.lengthSKI() > 0;
- }
+ /**
+ * Method containsSKI
+ *
+ * @return true if this X509Data contains a SKI
+ */
+ public boolean containsSKI() {
+ return this.lengthSKI() > 0;
+ }
- /**
- * Method containsSubjectName
- *
- * @return true if this X509Data contains a SubjectName
- */
- public boolean containsSubjectName() {
- return this.lengthSubjectName() > 0;
- }
+ /**
+ * Method containsSubjectName
+ *
+ * @return true if this X509Data contains a SubjectName
+ */
+ public boolean containsSubjectName() {
+ return this.lengthSubjectName() > 0;
+ }
- /**
- * Method containsCertificate
- *
- * @return true if this X509Data contains a Certificate
- */
- public boolean containsCertificate() {
- return this.lengthCertificate() > 0;
- }
+ /**
+ * Method 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 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;
- }
+ /**
+ * 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;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_X509DATA;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content.keyvalues;
@@ -37,104 +39,93 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- *
- * @author $Author: mullan $
- */
-public class DSAKeyValue extends SignatureElementProxy
- implements KeyValueContent {
+public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent {
- /**
- * Constructor DSAKeyValue
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public DSAKeyValue(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Constructor DSAKeyValue
+ *
+ * @param element
+ * @param baseURI
+ * @throws XMLSecurityException
+ */
+ public DSAKeyValue(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
+ }
- /**
- * Constructor DSAKeyValue
- *
- * @param doc
- * @param P
- * @param Q
- * @param G
- * @param Y
- */
- public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G,
- BigInteger Y) {
-
- super(doc);
+ /**
+ * Constructor DSAKeyValue
+ *
+ * @param doc
+ * @param P
+ * @param Q
+ * @param G
+ * @param Y
+ */
+ public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) {
+ super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
- this.addBigIntegerElement(P, Constants._TAG_P);
- this.addBigIntegerElement(Q, Constants._TAG_Q);
- this.addBigIntegerElement(G, Constants._TAG_G);
- this.addBigIntegerElement(Y, Constants._TAG_Y);
- }
+ 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 {
+ /**
+ * Constructor DSAKeyValue
+ *
+ * @param doc
+ * @param key
+ * @throws IllegalArgumentException
+ */
+ public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
+ super(doc);
- super(doc);
+ XMLUtils.addReturnToElement(this.constructionElement);
- XMLUtils.addReturnToElement(this._constructionElement);
+ if (key instanceof java.security.interfaces.DSAPublicKey) {
+ this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), Constants._TAG_P);
+ this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), Constants._TAG_Q);
+ this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), Constants._TAG_G);
+ this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y);
+ } else {
+ Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
- if (key instanceof java.security.interfaces.DSAPublicKey) {
- this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(),
- Constants._TAG_P);
- this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(),
- Constants._TAG_Q);
- this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(),
- Constants._TAG_G);
- this.addBigIntegerElement(((DSAPublicKey) key).getY(),
- Constants._TAG_Y);
- } else {
- Object exArgs[] = { Constants._TAG_DSAKEYVALUE,
- key.getClass().getName() };
-
- throw new IllegalArgumentException(I18n
- .translate("KeyValue.IllegalArgument", exArgs));
- }
- }
-
- /** @inheritDoc */
- public PublicKey getPublicKey() throws XMLSecurityException {
+ throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
+ }
+ }
- 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);
+ /** @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);
- }
- }
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,46 +2,38 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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;
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content.keyvalues;
@@ -37,93 +39,86 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- *
- * @author $Author: mullan $
- */
-public class RSAKeyValue extends SignatureElementProxy
- implements KeyValueContent {
+public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent {
- /**
- * Constructor RSAKeyValue
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public RSAKeyValue(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Constructor RSAKeyValue
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- /**
- * Constructor RSAKeyValue
- *
- * @param doc
- * @param modulus
- * @param exponent
- */
- public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
-
- super(doc);
+ /**
+ * Constructor RSAKeyValue
+ *
+ * @param doc
+ * @param modulus
+ * @param exponent
+ */
+ public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
+ super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
- this.addBigIntegerElement(modulus, Constants._TAG_MODULUS);
- this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT);
- }
+ 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 {
+ /**
+ * Constructor RSAKeyValue
+ *
+ * @param doc
+ * @param key
+ * @throws IllegalArgumentException
+ */
+ public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
+ super(doc);
+
+ XMLUtils.addReturnToElement(this.constructionElement);
- super(doc);
-
- XMLUtils.addReturnToElement(this._constructionElement);
+ if (key instanceof java.security.interfaces.RSAPublicKey ) {
+ this.addBigIntegerElement(
+ ((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS
+ );
+ this.addBigIntegerElement(
+ ((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT
+ );
+ } else {
+ Object exArgs[] = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() };
- if (key instanceof java.security.interfaces.RSAPublicKey ) {
- this.addBigIntegerElement(((RSAPublicKey) key).getModulus(),
- Constants._TAG_MODULUS);
- this.addBigIntegerElement(((RSAPublicKey) key).getPublicExponent(),
- Constants._TAG_EXPONENT);
- } else {
- Object exArgs[] = { Constants._TAG_RSAKEYVALUE,
- key.getClass().getName() };
+ throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs));
+ }
+ }
- throw new IllegalArgumentException(I18n
- .translate("KeyValue.IllegalArgument", exArgs));
- }
- }
-
- /** @inheritDoc */
- public PublicKey getPublicKey() throws XMLSecurityException {
+ /** @inheritDoc */
+ public PublicKey getPublicKey() throws XMLSecurityException {
+ try {
+ KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
- 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);
+ 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);
- }
- }
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content.x509;
@@ -26,51 +28,43 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- *
- * @author $Author: mullan $
- *
- */
-public class XMLX509CRL extends SignatureElementProxy
- implements XMLX509DataContent {
+public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent {
- /**
- * Constructor XMLX509CRL
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public XMLX509CRL(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Constructor 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content.x509;
@@ -25,6 +27,7 @@
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
+import java.util.Arrays;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
@@ -32,135 +35,134 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- *
- * @author $Author: mullan $
- */
-public class XMLX509Certificate extends SignatureElementProxy
- implements XMLX509DataContent {
+public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent {
- /** Field JCA_CERT_ID */
- public static final String JCA_CERT_ID = "X.509";
+ /** Field JCA_CERT_ID */
+ public static final String JCA_CERT_ID = "X.509";
- /**
- * Constructor X509Certificate
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public XMLX509Certificate(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Constructor X509Certificate
+ *
+ * @param 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 {
-
- super(doc);
+ try {
+ this.addBase64Text(x509certificate.getEncoded());
+ } catch (java.security.cert.CertificateEncodingException ex) {
+ throw new XMLSecurityException("empty", ex);
+ }
+ }
- try {
- this.addBase64Text(x509certificate.getEncoded());
- } catch (java.security.cert.CertificateEncodingException ex) {
- throw new XMLSecurityException("empty", ex);
- }
- }
+ /**
+ * Method getCertificateBytes
+ *
+ * @return the certificate bytes
+ * @throws XMLSecurityException
+ */
+ public byte[] getCertificateBytes() throws XMLSecurityException {
+ return this.getBytesFromTextChild();
+ }
- /**
- * Method getCertificateBytes
- *
- * @return the certificate bytes
- * @throws XMLSecurityException
- */
- public byte[] getCertificateBytes() throws XMLSecurityException {
- return this.getBytesFromTextChild();
- }
-
- /**
- * Method getX509Certificate
- *
- * @return the x509 certificate
- * @throws XMLSecurityException
- */
- public X509Certificate getX509Certificate() throws XMLSecurityException {
+ /**
+ * 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)
+ );
- try {
- byte certbytes[] = this.getCertificateBytes();
- CertificateFactory certFact =
- CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
- X509Certificate cert =
- (X509Certificate) certFact
- .generateCertificate(new ByteArrayInputStream(certbytes));
+ if (cert != null) {
+ return cert;
+ }
- if (cert != null) {
- return cert;
- }
+ return null;
+ } catch (CertificateException ex) {
+ throw new XMLSecurityException("empty", ex);
+ }
+ }
- return null;
- } catch (CertificateException ex) {
- throw new XMLSecurityException("empty", ex);
- }
- }
+ /**
+ * Method getPublicKey
+ *
+ * @return the publickey
+ * @throws XMLSecurityException
+ */
+ public PublicKey getPublicKey() throws XMLSecurityException {
+ X509Certificate cert = this.getX509Certificate();
- /**
- * Method getPublicKey
- *
- * @return teh publickey
- * @throws XMLSecurityException
- */
- public PublicKey getPublicKey() throws XMLSecurityException {
+ if (cert != null) {
+ return cert.getPublicKey();
+ }
- 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,32 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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 {
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,139 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.keys.content.x509;
+
+import java.security.MessageDigest;
+import java.security.cert.X509Certificate;
+
+import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
+import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Provides content model support for the <code>dsig11:X509Digest</code> 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;
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content.x509;
@@ -31,17 +33,11 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-/**
- *
- * @author $Author: mullan $
- */
-public class XMLX509IssuerSerial extends SignatureElementProxy
- implements XMLX509DataContent {
+public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- XMLX509IssuerSerial.class.getName());
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName());
/**
* Constructor XMLX509IssuerSerial
@@ -50,8 +46,7 @@
* @param baseURI
* @throws XMLSecurityException
*/
- public XMLX509IssuerSerial(Element element, String baseURI)
- throws XMLSecurityException {
+ public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
}
@@ -62,11 +57,9 @@
* @param x509IssuerName
* @param x509SerialNumber
*/
- public XMLX509IssuerSerial(Document doc, String x509IssuerName,
- BigInteger x509SerialNumber) {
-
+ public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) {
super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME);
addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER);
}
@@ -78,8 +71,7 @@
* @param x509IssuerName
* @param x509SerialNumber
*/
- public XMLX509IssuerSerial(Document doc, String x509IssuerName,
- String x509SerialNumber) {
+ public XMLX509IssuerSerial(Document doc, String x509IssuerName, String x509SerialNumber) {
this(doc, x509IssuerName, new BigInteger(x509SerialNumber));
}
@@ -90,10 +82,8 @@
* @param x509IssuerName
* @param x509SerialNumber
*/
- public XMLX509IssuerSerial(Document doc, String x509IssuerName,
- int x509SerialNumber) {
- this(doc, x509IssuerName,
- new BigInteger(Integer.toString(x509SerialNumber)));
+ public XMLX509IssuerSerial(Document doc, String x509IssuerName, int x509SerialNumber) {
+ this(doc, x509IssuerName, new BigInteger(Integer.toString(x509SerialNumber)));
}
/**
@@ -103,10 +93,11 @@
* @param x509certificate
*/
public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) {
-
- this(doc,
- RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()),
- x509certificate.getSerialNumber());
+ this(
+ doc,
+ x509certificate.getIssuerX500Principal().getName(),
+ x509certificate.getSerialNumber()
+ );
}
/**
@@ -115,11 +106,11 @@
* @return the serial number
*/
public BigInteger getSerialNumber() {
-
- String text = this.getTextFromChildElement
- (Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS);
- if (log.isLoggable(java.util.logging.Level.FINE))
+ String text =
+ this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text);
+ }
return new BigInteger(text);
}
@@ -139,27 +130,28 @@
* @return the issuer name
*/
public String getIssuerName() {
-
- return RFC2253Parser
- .normalize(this
- .getTextFromChildElement(Constants._TAG_X509ISSUERNAME,
- Constants.SignatureSpecNS));
+ return RFC2253Parser.normalize(
+ this.getTextFromChildElement(Constants._TAG_X509ISSUERNAME, Constants.SignatureSpecNS)
+ );
}
/** @inheritDoc */
public boolean equals(Object obj) {
-
- if (obj == null) {
- return false;
- }
- if (!this.getClass().getName().equals(obj.getClass().getName())) {
+ if (!(obj instanceof XMLX509IssuerSerial)) {
return false;
}
XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj;
return this.getSerialNumber().equals(other.getSerialNumber())
- && this.getIssuerName().equals(other.getIssuerName());
+ && this.getIssuerName().equals(other.getIssuerName());
+ }
+
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + getSerialNumber().hashCode();
+ result = 31 * result + getIssuerName().hashCode();
+ return result;
}
/** @inheritDoc */
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.content.x509;
-import java.io.IOException;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
import java.security.cert.X509Certificate;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
+import java.util.Arrays;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
@@ -37,14 +35,13 @@
/**
* Handles SubjectKeyIdentifier (SKI) for X.509v3.
*
- * @author $Author: mullan $
- * @see <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Extension.html">Interface X509Extension</A>
+ * @see <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Extension.html">
+ * Interface X509Extension</A>
*/
-public class XMLX509SKI extends SignatureElementProxy
- implements XMLX509DataContent {
+public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(XMLX509SKI.class.getName());
/**
@@ -53,7 +50,7 @@
* distinct keys used by the same subject to be differentiated
* (e.g., as key updating occurs).
* <BR />
- * A key identifer shall be unique with respect to all key identifiers
+ * A key identifier shall be unique with respect to all key identifiers
* for the subject with which it is used. This extension is always non-critical.
*/
public static final String SKI_OID = "2.5.29.14";
@@ -77,7 +74,7 @@
* @throws XMLSecurityException
*/
public XMLX509SKI(Document doc, X509Certificate x509certificate)
- throws XMLSecurityException {
+ throws XMLSecurityException {
super(doc);
this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate));
}
@@ -89,8 +86,7 @@
* @param BaseURI
* @throws XMLSecurityException
*/
- public XMLX509SKI(Element element, String BaseURI)
- throws XMLSecurityException {
+ public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException {
super(element, BaseURI);
}
@@ -117,9 +113,8 @@
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 @@
* Strip away first four bytes from the extensionValue
* The first two bytes are the tag and length of the extensionValue
* OCTET STRING, and the next two bytes are the tag and length of
- * the skid OCTET STRING.
+ * the ski OCTET STRING.
*/
byte skidValue[] = new byte[extensionValue.length - 4];
@@ -152,23 +147,35 @@
/** @inheritDoc */
public boolean equals(Object obj) {
- if (obj == null) {
- return false;
- }
- if (!this.getClass().getName().equals(obj.getClass().getName())) {
+ if (!(obj instanceof XMLX509SKI)) {
return false;
}
XMLX509SKI other = (XMLX509SKI) obj;
try {
- return java.security.MessageDigest.isEqual(other.getSKIBytes(),
- this.getSKIBytes());
+ return Arrays.equals(other.getSKIBytes(), this.getSKIBytes());
} catch (XMLSecurityException ex) {
return false;
}
}
+ public int hashCode() {
+ int result = 17;
+ try {
+ byte[] bytes = getSKIBytes();
+ for (int i = 0; i < bytes.length; i++) {
+ result = 31 * result + bytes[i];
+ }
+ } catch (XMLSecurityException e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+ }
+ }
+ return result;
+
+ }
+
/** @inheritDoc */
public String getBaseLocalName() {
return Constants._TAG_X509SKI;
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.content.x509;
@@ -30,65 +32,57 @@
import org.w3c.dom.Element;
/**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
*/
-public class XMLX509SubjectName extends SignatureElementProxy
- implements XMLX509DataContent {
+public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent {
- /**
- * Constructor X509SubjectName
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public XMLX509SubjectName(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
-
- /**
- * Constructor X509SubjectName
- *
- * @param doc
- * @param X509SubjectNameString
- */
- public XMLX509SubjectName(Document doc, String X509SubjectNameString) {
+ /**
+ * Constructor X509SubjectName
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public XMLX509SubjectName(Element element, String BaseURI)
+ throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- super(doc);
+ /**
+ * Constructor X509SubjectName
+ *
+ * @param doc
+ * @param X509SubjectNameString
+ */
+ public XMLX509SubjectName(Document doc, String X509SubjectNameString) {
+ super(doc);
- this.addText(X509SubjectNameString);
- }
+ this.addText(X509SubjectNameString);
+ }
- /**
- * Constructor XMLX509SubjectName
- *
- * @param doc
- * @param x509certificate
- */
- public XMLX509SubjectName(Document doc, X509Certificate x509certificate) {
- this(doc,
- RFC2253Parser.normalize(x509certificate.getSubjectDN().getName()));
- }
+ /**
+ * Constructor XMLX509SubjectName
+ *
+ * @param doc
+ * @param x509certificate
+ */
+ public XMLX509SubjectName(Document doc, X509Certificate x509certificate) {
+ this(doc, x509certificate.getSubjectX500Principal().getName());
+ }
- /**
- * Method getSubjectName
- *
- *
- * @return the subject name
- */
- public String getSubjectName() {
- return RFC2253Parser.normalize(this.getTextFromTextChild());
- }
+ /**
+ * Method getSubjectName
+ *
+ *
+ * @return the subject name
+ */
+ public String getSubjectName() {
+ return RFC2253Parser.normalize(this.getTextFromTextChild());
+ }
/** @inheritDoc */
public boolean equals(Object obj) {
- if (obj == null) {
- return false;
- }
-
- if (!this.getClass().getName().equals(obj.getClass().getName())) {
+ if (!(obj instanceof XMLX509SubjectName)) {
return false;
}
@@ -97,10 +91,16 @@
String thisSubject = this.getSubjectName();
return thisSubject.equals(otherSubject);
- }
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_X509SUBJECTNAME;
- }
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + this.getSubjectName().hashCode();
+ return result;
+ }
+
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_X509SUBJECTNAME;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,88 +2,80 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -31,10 +31,13 @@
import javax.crypto.SecretKey;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.KeyInfoReferenceResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509DigestResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver;
@@ -277,6 +280,9 @@
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);
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,90 +2,80 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,24 +2,27 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver;
+import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.HashMap;
@@ -30,78 +33,89 @@
import org.w3c.dom.Element;
/**
- * This class is abstract class for a child KeyInfo Elemnet.
+ * This class is an abstract class for a child KeyInfo Element.
*
- * If you want your KeyResolver, at first you must extend this class, and register
+ * If you want the your KeyResolver, at firstly you must extend this class, and register
* as following in config.xml
* <PRE>
* <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
* JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
* </PRE>
- *
- * @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();
- }
+
+ /** Field properties */
+ protected java.util.Map<String, String> 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;
+ }
- /**
- * 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();
+ /**
+ * This method returns whether the KeyResolverSpi is able to perform the requested action.
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return whether the KeyResolverSpi is able to perform the requested action.
+ */
+ public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Method engineResolvePublicKey
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return resolved public key from the registered from the element.
+ *
+ * @throws KeyResolverException
+ */
+ public PublicKey engineResolvePublicKey(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ throw new UnsupportedOperationException();
};
- /**
- * Method engineResolvePublicKey
- *
- * @param element
- * @param BaseURI
- * @param storage
- * @return resolved public key from the registered from the element.
- *
- * @throws KeyResolverException
- */
+ /**
+ * Method engineLookupAndResolvePublicKey
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return resolved public key from the registered from the element.
+ *
+ * @throws KeyResolverException
+ */
public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage)
- throws KeyResolverException {
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
KeyResolverSpi tmp = cloneIfNeeded();
- if (!tmp.engineCanResolve(element, BaseURI, storage))
- return null;
- return tmp.engineResolvePublicKey(element, BaseURI, storage);
+ if (!tmp.engineCanResolve(element, baseURI, storage)) {
+ return null;
+ }
+ return tmp.engineResolvePublicKey(element, baseURI, storage);
}
private KeyResolverSpi cloneIfNeeded() throws KeyResolverException {
- KeyResolverSpi tmp=this;
+ KeyResolverSpi tmp = this;
if (globalResolver) {
- try {
- tmp = (KeyResolverSpi) getClass().newInstance();
- } catch (InstantiationException e) {
- throw new KeyResolverException("",e);
- } catch (IllegalAccessException e) {
- throw new KeyResolverException("",e);
- }
+ try {
+ tmp = getClass().newInstance();
+ } catch (InstantiationException e) {
+ throw new KeyResolverException("", e);
+ } catch (IllegalAccessException e) {
+ throw new KeyResolverException("", e);
+ }
}
return tmp;
}
@@ -110,116 +124,138 @@
* Method engineResolveCertificate
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @return resolved X509Certificate key from the registered from the elements
*
* @throws KeyResolverException
*/
public X509Certificate engineResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage)
- throws KeyResolverException{
- throw new UnsupportedOperationException();
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException{
+ throw new UnsupportedOperationException();
};
- /**
- * Method engineResolveCertificate
- *
- * @param element
- * @param BaseURI
- * @param storage
- * @return resolved X509Certificate key from the registered from the elements
- *
- * @throws KeyResolverException
- */
+ /**
+ * Method engineLookupResolveX509Certificate
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return resolved X509Certificate key from the registered from the elements
+ *
+ * @throws KeyResolverException
+ */
public X509Certificate engineLookupResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage)
- throws KeyResolverException {
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
KeyResolverSpi tmp = cloneIfNeeded();
- if (!tmp.engineCanResolve(element, BaseURI, storage))
- return null;
- return tmp.engineResolveX509Certificate(element, BaseURI, storage);
+ if (!tmp.engineCanResolve(element, baseURI, storage)) {
+ return null;
+ }
+ return tmp.engineResolveX509Certificate(element, baseURI, storage);
}
/**
* Method engineResolveSecretKey
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @return resolved SecretKey key from the registered from the elements
*
* @throws KeyResolverException
*/
public SecretKey engineResolveSecretKey(
- Element element, String BaseURI, StorageResolver storage)
- throws KeyResolverException{
- throw new UnsupportedOperationException();
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException{
+ throw new UnsupportedOperationException();
};
- /**
- * Method 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<String,String> _properties = null;
-
- protected boolean globalResolver=false;
+ /**
+ * Method engineLookupAndResolvePrivateKey
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return resolved PrivateKey key from the registered from the elements
+ *
+ * @throws KeyResolverException
+ */
+ public PrivateKey engineLookupAndResolvePrivateKey(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ // This method was added later, it has no equivalent
+ // engineResolvePrivateKey() in the old API.
+ // We cannot throw UnsupportedOperationException because
+ // KeyResolverSpi implementations who don't know about
+ // this method would stop the search too early.
+ return null;
+ }
- /**
- * Method engineSetProperty
- *
- * @param key
- * @param value
- */
- public void engineSetProperty(String key, String value) {
- if (_properties==null)
- _properties=new HashMap<String,String>();
- this._properties.put(key, value);
- }
+ /**
+ * Method engineSetProperty
+ *
+ * @param key
+ * @param value
+ */
+ public void engineSetProperty(String key, String value) {
+ if (properties == null) {
+ properties = new HashMap<String, String>();
+ }
+ 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 this._properties.get(key);
- }
+ return 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 this._properties.get(propertyToTest)!=null;
- }
- public void setGlobalResolver(boolean globalResolver) {
+ return properties.get(propertyToTest) != null;
+ }
+
+ public void setGlobalResolver(boolean globalResolver) {
this.globalResolver = globalResolver;
- }
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * <code>dsig11:DEREncodedKeyValue</code> 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;
+ }
+
+
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.security.PublicKey;
import java.security.cert.X509Certificate;
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
@@ -34,66 +33,70 @@
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
-
-/**
- *
- * @author $Author: mullan $
- */
public class DSAKeyValueResolver extends KeyResolverSpi {
- /**
- * Method engineResolvePublicKey
- *
- * @param element
- * @param BaseURI
- * @param storage
- * @return null if no {@link PublicKey} could be obtained
- */
- public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage) {
- if (element == null) {
- return null;
- }
- Element dsaKeyElement=null;
- boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element,
- Constants._TAG_KEYVALUE);
- if (isKeyValue) {
- dsaKeyElement =
- XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0);
- } else if (XMLUtils.elementIsInSignatureSpace(element,
- Constants._TAG_DSAKEYVALUE)) {
- // this trick is needed to allow the RetrievalMethodResolver to eat a
- // ds:DSAKeyValue directly (without KeyValue)
- dsaKeyElement = element;
- }
-
- 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;
- }
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName());
- /** @inheritDoc */
- public X509Certificate engineLookupResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage) {
- return null;
- }
+ /**
+ * 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;
+ }
- /** @inheritDoc */
- public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
- Element element, String BaseURI, StorageResolver storage){
- return null;
- }
+ try {
+ DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI);
+ PublicKey pk = dsaKeyValue.getPublicKey();
+
+ return pk;
+ } catch (XMLSecurityException ex) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+ }
+ //do nothing
+ }
+
+ return null;
+ }
+
+
+ /** @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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,39 +2,43 @@
* 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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.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 <code>EncryptedKeyResolver</code> is not a generic resolver. It can
* only be for specific instantiations, as the key being unwrapped will
@@ -47,78 +51,100 @@
*
* @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<KeyResolverSpi> 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;
+ this.algorithm = 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) {
+ this.algorithm = algorithm;
+ this.kek = kek;
+ }
- /**
- * Constructor used for when a KEK has been set
- * @param algorithm
- * @param kek
- */
-
- public EncryptedKeyResolver(String algorithm, Key kek) {
- _algorithm = algorithm;
- _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<KeyResolverSpi>();
}
+ internalKeyResolvers.add(realKeyResolver);
+ }
/** @inheritDoc */
- public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage) {
-
- return null;
- }
+ public PublicKey engineLookupAndResolvePublicKey(
+ Element element, String BaseURI, StorageResolver storage
+ ) {
+ return null;
+ }
- /** @inheritDoc */
- public X509Certificate engineLookupResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage) {
- return null;
- }
+ /** @inheritDoc */
+ public X509Certificate engineLookupResolveX509Certificate(
+ Element element, String BaseURI, StorageResolver storage
+ ) {
+ return null;
+ }
- /** @inheritDoc */
- public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
- Element element, String BaseURI, StorageResolver storage) {
- SecretKey key=null;
- if (log.isLoggable(java.util.logging.Level.FINE))
- log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName());
+ /** @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());
+ }
+
+ if (element == null) {
+ return null;
+ }
- if (element == null) {
- return null;
- }
-
- boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element,
- EncryptionConstants._TAG_ENCRYPTEDKEY);
+ 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);
+ }
+ }
+ }
- 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;
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * <code>dsig11:KeyInfoReference</code> element.
+ *
+ * @author Brent Putman (putmanb@georgetown.edu)
+ */
+public class KeyInfoReferenceResolver extends KeyResolverSpi {
+
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName());
+
+ /** {@inheritDoc}. */
+ public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+ return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE);
+ }
+
+ /** {@inheritDoc}. */
+ public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
+ throws KeyResolverException {
+
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+ }
+
+ if (!engineCanResolve(element, baseURI, storage)) {
+ return null;
+ }
+
+ try {
+ KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+ if (referent != null) {
+ return referent.getPublicKey();
+ }
+ } catch (XMLSecurityException e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+ }
+ }
+
+ return null;
+ }
+
+ /** {@inheritDoc}. */
+ public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
+ throws KeyResolverException {
+
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+ }
+
+ if (!engineCanResolve(element, baseURI, storage)) {
+ return null;
+ }
+
+ try {
+ KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+ if (referent != null) {
+ return referent.getX509Certificate();
+ }
+ } catch (XMLSecurityException e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+ }
+ }
+
+ return null;
+ }
+
+ /** {@inheritDoc}. */
+ public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
+ throws KeyResolverException {
+
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+ }
+
+ if (!engineCanResolve(element, baseURI, storage)) {
+ return null;
+ }
+
+ try {
+ KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+ if (referent != null) {
+ return referent.getSecretKey();
+ }
+ } catch (XMLSecurityException e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+ }
+ }
+
+ return null;
+ }
+
+ /** {@inheritDoc}. */
+ public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage)
+ throws KeyResolverException {
+
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
+ }
+
+ if (!engineCanResolve(element, baseURI, storage)) {
+ return null;
+ }
+
+ try {
+ KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
+ if (referent != null) {
+ return referent.getPrivateKey();
+ }
+ } catch (XMLSecurityException e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance.
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved
+ * @throws XMLSecurityException
+ */
+ private KeyInfo resolveReferentKeyInfo(Element element, String baseURI, StorageResolver storage) throws XMLSecurityException {
+ KeyInfoReference reference = new KeyInfoReference(element, baseURI);
+ Attr uriAttr = reference.getURIAttr();
+
+ XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation);
+
+ Element referentElement = null;
+ try {
+ referentElement = obtainReferenceElement(resource);
+ } catch (Exception e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+ }
+ return null;
+ }
+
+ if (referentElement == null) {
+ log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue());
+ return null;
+ }
+
+ validateReference(referentElement);
+
+ KeyInfo referent = new KeyInfo(referentElement, baseURI);
+ referent.addStorageResolver(storage);
+ return referent;
+ }
+
+ /**
+ * Validate the Element referred to by the KeyInfoReference.
+ *
+ * @param referentElement
+ *
+ * @throws XMLSecurityException
+ */
+ private void validateReference(Element referentElement) throws XMLSecurityException {
+ if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) {
+ Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) };
+ throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs);
+ }
+
+ KeyInfo referent = new KeyInfo(referentElement, "");
+ if (referent.containsKeyInfoReference()) {
+ if (secureValidation) {
+ throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure");
+ } else {
+ // Don't support chains of references at this time. If do support in the future, this is where the code
+ // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic
+ // to implement, and/or very expensive given remote URI references.
+ throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure");
+ }
+ }
+
+ }
+
+ /**
+ * Resolve the XML signature input represented by the specified URI.
+ *
+ * @param uri
+ * @param baseURI
+ * @param secureValidation
+ * @return
+ * @throws XMLSecurityException
+ */
+ private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation)
+ throws XMLSecurityException {
+ ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
+ XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
+ return resource;
+ }
+
+ /**
+ * Resolve the Element effectively represented by the XML signature input source.
+ *
+ * @param resource
+ * @return
+ * @throws CanonicalizationException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ * @throws KeyResolverException
+ */
+ private Element obtainReferenceElement(XMLSignatureInput resource)
+ throws CanonicalizationException, ParserConfigurationException,
+ IOException, SAXException, KeyResolverException {
+
+ Element e;
+ if (resource.isElement()){
+ e = (Element) resource.getSubNode();
+ } else if (resource.isNodeSet()) {
+ log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet");
+ return null;
+ } else {
+ // Retrieved resource is a byte stream
+ byte inputBytes[] = resource.getBytes();
+ e = getDocFromBytes(inputBytes);
+ }
+ return e;
+ }
+
+ /**
+ * Parses a byte array and returns the parsed Element.
+ *
+ * @param bytes
+ * @return the Document Element after parsing bytes
+ * @throws KeyResolverException if something goes wrong
+ */
+ private Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ Document doc = db.parse(new ByteArrayInputStream(bytes));
+ return doc.getDocumentElement();
+ } catch (SAXException ex) {
+ throw new KeyResolverException("empty", ex);
+ } catch (IOException ex) {
+ throw new KeyResolverException("empty", ex);
+ } catch (ParserConfigurationException ex) {
+ throw new KeyResolverException("empty", ex);
+ }
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -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<String> aliases = keyStore.aliases();
+ while (aliases.hasMoreElements()) {
+ String alias = aliases.nextElement();
+ if (keyStore.isKeyEntry(alias)) {
+
+ Certificate cert = keyStore.getCertificate(alias);
+ if (cert instanceof X509Certificate) {
+ XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert);
+
+ if (certSKI.equals(x509SKI)) {
+ log.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<String> aliases = keyStore.aliases();
+ while (aliases.hasMoreElements()) {
+ String alias = aliases.nextElement();
+ if (keyStore.isKeyEntry(alias)) {
+
+ Certificate cert = keyStore.getCertificate(alias);
+ if (cert instanceof X509Certificate) {
+ XMLX509IssuerSerial certSerial =
+ new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert);
+
+ if (certSerial.equals(x509Serial)) {
+ log.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<String> aliases = keyStore.aliases();
+ while (aliases.hasMoreElements()) {
+ String alias = aliases.nextElement();
+ if (keyStore.isKeyEntry(alias)) {
+
+ Certificate cert = keyStore.getCertificate(alias);
+ if (cert instanceof X509Certificate) {
+ XMLX509SubjectName certSN =
+ new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert);
+
+ if (certSN.equals(x509SubjectName)) {
+ log.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<String> aliases = keyStore.aliases();
+ while (aliases.hasMoreElements()) {
+ String alias = aliases.nextElement();
+ if (keyStore.isKeyEntry(alias)) {
+
+ Certificate cert = keyStore.getCertificate(alias);
+ if (cert instanceof X509Certificate) {
+ byte[] certBytes = null;
+
+ try {
+ certBytes = cert.getEncoded();
+ } catch (CertificateEncodingException e1) {
+ }
+
+ 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;
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.security.PublicKey;
import java.security.cert.X509Certificate;
@@ -34,69 +34,63 @@
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
-
-/**
- *
- * @author $Author: mullan $
- */
public class RSAKeyValueResolver extends KeyResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- RSAKeyValueResolver.class.getName());
-
- /** Field _rsaKeyElement */
+ /** {@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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.PublicKey;
@@ -35,6 +35,8 @@
import java.util.Set;
import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -51,11 +53,11 @@
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
-
/**
* The RetrievalMethodResolver can retrieve public keys and certificates from
* other locations. The location is specified using the ds:RetrievalMethod
@@ -65,252 +67,325 @@
* RetrievalMethodResolver cannot handle itself, resolving of the extracted
* element is delegated back to the KeyResolver mechanism.
*
- * @author $Author: mullan $ modified by Dave Garcia
+ * @author $Author: raul $ modified by Dave Garcia
*/
public class RetrievalMethodResolver extends KeyResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- RetrievalMethodResolver.class.getName());
+ /** {@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;
- }
+ /**
+ * 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;
- }
+ 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;
+ }
+ }
- 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;
- }
+ 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);
+ }
- /**
- * 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;
- }
+ 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;
+ }
+ }
- 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;
- }
+ 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
- */
- 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
+ */
+ 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 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;
- }
+ /**
+ * 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;
+ }
- 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;
- }
+ 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;
+ }
- /**
- * 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);
- }
- }
+ /**
+ * 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;
- }
-
- static Element getDocumentElement(Set<Node> set) {
- Iterator<Node> 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;
- }
+ /**
+ * Method engineResolveSecretKey
+ * @inheritDoc
+ * @param element
+ * @param baseURI
+ * @param storage
+ */
+ public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
+ Element element, String baseURI, StorageResolver storage
+ ) {
+ return null;
+ }
- }
- List<Element> parents=new ArrayList<Element>(10);
+ private static Element getDocumentElement(Set<Node> set) {
+ Iterator<Node> 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<Node> parents = new ArrayList<Node>();
- //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<Element> it2=parents.listIterator(parents.size()-1);
- Element ele=null;
- while (it2.hasPrevious()) {
- ele=it2.previous();
- if (set.contains(ele)) {
- return ele;
- }
+ // 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;
}
- return null;
- }
+ // Visit them in reverse order.
+ ListIterator<Node> it2 = parents.listIterator(parents.size()-1);
+ Element ele = null;
+ while (it2.hasPrevious()) {
+ ele = (Element) it2.previous();
+ if (set.contains(ele)) {
+ return ele;
+ }
+ }
+ return null;
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,129 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
+
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import javax.crypto.SecretKey;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
+import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
+import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
+import com.sun.org.apache.xml.internal.security.utils.Constants;
+import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import org.w3c.dom.Element;
+
+/**
+ * Resolves a SecretKey within a KeyStore based on the KeyName.
+ * The KeyName is the key entry alias within the KeyStore.
+ */
+public class SecretKeyResolver extends KeyResolverSpi
+{
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName());
+
+ private KeyStore keyStore;
+ private char[] password;
+
+ /**
+ * Constructor.
+ */
+ public SecretKeyResolver(KeyStore keyStore, char[] password) {
+ this.keyStore = keyStore;
+ this.password = password;
+ }
+
+ /**
+ * This method returns whether the KeyResolverSpi is able to perform the requested action.
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return whether the KeyResolverSpi is able to perform the requested action.
+ */
+ public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
+ return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME);
+ }
+
+ /**
+ * Method engineLookupAndResolvePublicKey
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return null if no {@link PublicKey} could be obtained
+ * @throws KeyResolverException
+ */
+ public PublicKey engineLookupAndResolvePublicKey(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ return null;
+ }
+
+ /**
+ * Method engineResolveX509Certificate
+ * @inheritDoc
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @throws KeyResolverException
+ */
+ public X509Certificate engineLookupResolveX509Certificate(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ return null;
+ }
+
+ /**
+ * Method engineResolveSecretKey
+ *
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained
+ *
+ * @throws KeyResolverException
+ */
+ public SecretKey engineResolveSecretKey(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+ }
+
+ if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
+ String keyName = element.getFirstChild().getNodeValue();
+ try {
+ Key key = keyStore.getKey(keyName, password);
+ if (key instanceof SecretKey) {
+ return (SecretKey) key;
+ }
+ } catch (Exception e) {
+ log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+ }
+ }
+
+ log.log(java.util.logging.Level.FINE, "I can't");
+ return null;
+ }
+
+ /**
+ * Method engineResolvePrivateKey
+ * @inheritDoc
+ * @param element
+ * @param baseURI
+ * @param storage
+ * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained
+ * @throws KeyResolverException
+ */
+ public PrivateKey engineLookupAndResolvePrivateKey(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ return null;
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -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;
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.security.PublicKey;
import java.security.cert.X509Certificate;
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate;
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException;
@@ -35,96 +34,93 @@
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
-
/**
* Resolves Certificates which are directly contained inside a
* <CODE>ds:X509Certificate</CODE> 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 {
- /**
- * 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);
+ 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 {
+ /**
+ * 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;
- }
+ try {
+ Element[] els =
+ XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE);
+ if ((els == null) || (els.length == 0)) {
+ Element el =
+ XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0);
+ if (el != null) {
+ return engineLookupResolveX509Certificate(el, BaseURI, storage);
+ }
+ return null;
+ }
- // populate Object array
- for (int i = 0; i < els.length; i++) {
- XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI);
- X509Certificate cert = xmlCert.getX509Certificate();
- if (cert!=null) {
- return cert;
+ // populate Object array
+ for (int i = 0; i < els.length; i++) {
+ XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI);
+ X509Certificate cert = xmlCert.getX509Certificate();
+ if (cert != null) {
+ return cert;
+ }
}
- }
- return null;
- } catch (XMLSecurityException ex) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
-
- throw new KeyResolverException("generic.EmptyMessage", 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);
+ }
+ }
- /**
- * 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;
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * <code>dsig11:X509Digest</code> 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<Certificate> 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;
+ }
+ }
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.security.PublicKey;
+import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
+import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.keys.content.X509Data;
@@ -35,114 +37,114 @@
import com.sun.org.apache.xml.internal.security.utils.Constants;
import org.w3c.dom.Element;
-
-/**
- *
- * @author $Author: mullan $
- */
public class X509IssuerSerialResolver extends KeyResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- X509IssuerSerialResolver.class.getName());
+ /** {@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() + "?");
+ /** @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;
- }
+ X509Data x509data = null;
+ try {
+ x509data = new X509Data(element, baseURI);
+ } catch (XMLSignatureException ex) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I can't");
+ }
+ return null;
+ } catch (XMLSecurityException ex) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "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 (!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);
-
- 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());
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "", ex);
+ }
+ throw ex;
}
- for (int i=0; i<noOfISS; i++) {
- XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i);
+ int noOfISS = x509data.lengthIssuerSerial();
+
+ Iterator<Certificate> storageIterator = storage.getIterator();
+ while (storageIterator.hasNext()) {
+ X509Certificate cert = (X509Certificate)storageIterator.next();
+ XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert);
+
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName());
+ log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString());
+ }
+
+ for (int i = 0; i < noOfISS; i++) {
+ XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i);
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Found Element Issuer: "
- + xmliss.getIssuerName());
- log.log(java.util.logging.Level.FINE, "Found Element Serial: "
- + xmliss.getSerialNumber().toString());
- }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Found Element Issuer: "
+ + xmliss.getIssuerName());
+ log.log(java.util.logging.Level.FINE, "Found Element Serial: "
+ + xmliss.getSerialNumber().toString());
+ }
- if (certSerial.equals(xmliss)) {
- log.log(java.util.logging.Level.FINE, "match !!! ");
-
- return cert;
- }
- log.log(java.util.logging.Level.FINE, "no match...");
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.security.PublicKey;
+import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
+import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
@@ -35,124 +37,121 @@
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
-
-/**
- *
- *
- * @author $Author: mullan $
- */
public class X509SKIResolver extends KeyResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(X509SKIResolver.class.getName());
- /**
- * Method engineResolvePublicKey
- *
- * @param element
- * @param BaseURI
- * @param storage
- * @return null if no {@link PublicKey} could be obtained
- * @throws KeyResolverException
- */
- public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage)
- throws KeyResolverException {
+ /**
+ * 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;
+ /**
+ * Method engineResolveX509Certificate
+ * @inheritDoc
+ * @param element
+ * @param baseURI
+ * @param storage
+ *
+ * @throws KeyResolverException
+ */
+ public X509Certificate engineLookupResolveX509Certificate(
+ Element element, String baseURI, StorageResolver storage
+ ) throws KeyResolverException {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
+ }
+ if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I can't");
+ }
+ return null;
+ }
+ /** Field _x509childObject[] */
+ XMLX509SKI x509childObject[] = null;
- Element x509childNodes[] = null;
- x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(),
- Constants._TAG_X509SKI);
+ 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);
+ 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);
- throw ex;
- }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "", ex);
+ }
- x509childObject = new XMLX509SKI[x509childNodes.length];
+ throw ex;
+ }
+
+ x509childObject = new XMLX509SKI[x509childNodes.length];
- for (int i = 0; i < x509childNodes.length; i++) {
- x509childObject[i] =
- new XMLX509SKI(x509childNodes[i], BaseURI);
- }
+ 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);
+ Iterator<Certificate> 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])) {
- log.log(java.util.logging.Level.FINE, "Return PublicKey from "
- + cert.getSubjectDN().getName());
+ 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;
- }
+ return cert;
+ }
+ }
}
- }
- } catch (XMLSecurityException ex) {
- throw new KeyResolverException("empty", ex);
- }
+ } catch (XMLSecurityException ex) {
+ throw new KeyResolverException("empty", ex);
+ }
- return null;
- }
+ return null;
+ }
- /**
- * 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-
import java.security.PublicKey;
+import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
+import java.util.Iterator;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
@@ -35,133 +37,140 @@
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Element;
-
-/**
- *
- * @author $Author: mullan $
- */
public class X509SubjectNameResolver extends KeyResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- X509SubjectNameResolver.class.getName());
+ /** {@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;
+ }
+
+ x509childObject = new XMLX509SubjectName[x509childNodes.length];
+
+ for (int i = 0; i < x509childNodes.length; i++) {
+ x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI);
}
- try {
- if (storage == null) {
- Object exArgs[] = { Constants._TAG_X509SUBJECTNAME };
- KeyResolverException ex =
- new KeyResolverException("KeyResolver.needStorageResolver",
- exArgs);
+ Iterator<Certificate> storageIterator = storage.getIterator();
+ while (storageIterator.hasNext()) {
+ X509Certificate cert = (X509Certificate)storageIterator.next();
+ XMLX509SubjectName certSN =
+ new XMLX509SubjectName(element.getOwnerDocument(), cert);
- log.log(java.util.logging.Level.INFO, "", ex);
-
- throw ex;
- }
-
- x509childObject =
- new XMLX509SubjectName[x509childNodes.length];
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName());
+ }
- for (int i = 0; i < x509childNodes.length; i++) {
- x509childObject[i] =
- new XMLX509SubjectName(x509childNodes[i],
- BaseURI);
- }
+ 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());
+ }
- 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])) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "match !!! ");
+ }
- if (certSN.equals(x509childObject[i])) {
- 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 cert;
- }
- log.log(java.util.logging.Level.FINE, "no match...");
+ return null;
+ } catch (XMLSecurityException ex) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
}
- }
-
- return null;
- } catch (XMLSecurityException ex) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
- throw new KeyResolverException("generic.EmptyMessage", ex);
- }
- }
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,197 +2,187 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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<Object> _storageResolvers = null;
-
- /** Field _iterator */
- Iterator<Object> _iterator = null;
+ /** Field storageResolvers */
+ private List<StorageResolverSpi> storageResolvers = 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<Object>();
- this._storageResolvers.add(resolver);
-
- this._iterator = null;
- }
+ /**
+ * Method addResolver
+ *
+ * @param resolver
+ */
+ public void add(StorageResolverSpi resolver) {
+ if (storageResolvers == null) {
+ storageResolvers = new ArrayList<StorageResolverSpi>();
+ }
+ this.storageResolvers.add(resolver);
+ }
- /**
- * Constructor StorageResolver
- *
- * @param keyStore
- */
- public StorageResolver(KeyStore keyStore) {
- this.add(keyStore);
- }
-
- /**
- * Method addKeyStore
- *
- * @param keyStore
- */
- public void add(KeyStore keyStore) {
+ /**
+ * Constructor StorageResolver
+ *
+ * @param keyStore
+ */
+ public StorageResolver(KeyStore keyStore) {
+ this.add(keyStore);
+ }
- try {
- this.add(new KeyStoreResolver(keyStore));
- } catch (StorageResolverException ex) {
- log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex);
- }
- }
+ /**
+ * Method addKeyStore
+ *
+ * @param keyStore
+ */
+ public void add(KeyStore keyStore) {
+ try {
+ this.add(new KeyStoreResolver(keyStore));
+ } catch (StorageResolverException ex) {
+ log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex);
+ }
+ }
- /**
- * Constructor StorageResolver
- *
- * @param x509certificate
- */
- public StorageResolver(X509Certificate x509certificate) {
- this.add(x509certificate);
- }
+ /**
+ * Constructor StorageResolver
+ *
+ * @param x509certificate
+ */
+ public StorageResolver(X509Certificate x509certificate) {
+ this.add(x509certificate);
+ }
- /**
- * Method addCertificate
- *
- * @param x509certificate
- */
- public void add(X509Certificate x509certificate) {
- this.add(new SingleCertificateResolver(x509certificate));
- }
+ /**
+ * Method addCertificate
+ *
+ * @param x509certificate
+ */
+ public void add(X509Certificate x509certificate) {
+ this.add(new SingleCertificateResolver(x509certificate));
+ }
- /**
- * Method getIterator
- * @return the iterator for the resolvers.
- *
- */
- public Iterator<Object> getIterator() {
+ /**
+ * Method getIterator
+ * @return the iterator for the resolvers.
+ */
+ public Iterator<Certificate> getIterator() {
+ return new StorageResolverIterator(this.storageResolvers.iterator());
+ }
- if (this._iterator == null) {
- if (_storageResolvers==null)
- _storageResolvers=new ArrayList<Object>();
- this._iterator = new StorageResolverIterator(this._storageResolvers.iterator());
- }
+ /**
+ * Class StorageResolverIterator
+ * This iterates over all the Certificates found in all the resolvers.
+ */
+ static class StorageResolverIterator implements Iterator<Certificate> {
- return this._iterator;
- }
+ /** Field resolvers */
+ Iterator<StorageResolverSpi> resolvers = null;
- /**
- * Method hasNext
- *
- * @return true if there is more elements.
- */
- public boolean hasNext() {
+ /** Field currentResolver */
+ Iterator<Certificate> currentResolver = null;
- if (this._iterator == null) {
- if (_storageResolvers==null)
- _storageResolvers=new ArrayList<Object>();
- this._iterator = new StorageResolverIterator(this._storageResolvers.iterator());
- }
+ /**
+ * Constructor StorageResolverIterator
+ *
+ * @param resolvers
+ */
+ public StorageResolverIterator(Iterator<StorageResolverSpi> resolvers) {
+ this.resolvers = resolvers;
+ currentResolver = findNextResolver();
+ }
- return this._iterator.hasNext();
- }
+ /** @inheritDoc */
+ public boolean hasNext() {
+ if (currentResolver == null) {
+ return false;
+ }
- /**
- * Method next
- *
- * @return the next element
- */
- public X509Certificate next() {
- return (X509Certificate) this._iterator.next();
- }
+ if (currentResolver.hasNext()) {
+ return true;
+ }
+
+ currentResolver = findNextResolver();
+ return (currentResolver != null);
+ }
- /**
- * Class StorageResolverIterator
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- static class StorageResolverIterator implements Iterator<Object> {
+ /** @inheritDoc */
+ public Certificate next() {
+ if (hasNext()) {
+ return currentResolver.next();
+ }
- /** Field _resolvers */
- Iterator<Object> _resolvers = null;
+ throw new NoSuchElementException();
+ }
- /**
- * Constructor FilesystemIterator
- *
- * @param resolvers
- */
- public StorageResolverIterator(Iterator<Object> resolvers) {
- this._resolvers = resolvers;
- }
-
- /** @inheritDoc */
- public boolean hasNext() {
- return _resolvers.hasNext();
- }
+ /**
+ * Method remove
+ */
+ public void remove() {
+ throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+ }
- /** @inheritDoc */
- public Object next() {
- return _resolvers.next();
- }
+ // Find the next storage with at least one element and return its Iterator
+ private Iterator<Certificate> findNextResolver() {
+ while (resolvers.hasNext()) {
+ StorageResolverSpi resolverSpi = resolvers.next();
+ Iterator<Certificate> iter = resolverSpi.getIterator();
+ if (iter.hasNext()) {
+ return iter;
+ }
+ }
- /**
- * Method remove
- */
- public void remove() {
- throw new UnsupportedOperationException(
- "Can't remove keys from KeyStore");
- }
- }
+ return null;
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,86 +2,82 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,39 +2,35 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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<Certificate> getIterator();
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.keys.storage.implementations;
@@ -24,6 +26,7 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
@@ -39,188 +42,188 @@
/**
* This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s
- * which reside as files in a single directory available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
- *
- * @author $Author: mullan $
+ * which reside as files in a single directory available to the
+ * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
*/
public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(
- CertsInFilesystemDirectoryResolver.class.getName());
+ CertsInFilesystemDirectoryResolver.class.getName()
+ );
- /** Field _merlinsCertificatesDir */
- String _merlinsCertificatesDir = null;
+ /** Field merlinsCertificatesDir */
+ private String merlinsCertificatesDir = null;
- /** Field _certs */
- private List<X509Certificate> _certs = new ArrayList<X509Certificate>();
-
- /** Field _iterator */
- Iterator<X509Certificate> _iterator = null;
+ /** Field certs */
+ private List<X509Certificate> certs = new ArrayList<X509Certificate>();
- /**
- *
- *
- * @param directoryName
- * @throws StorageResolverException
- */
- public CertsInFilesystemDirectoryResolver(String directoryName)
- throws StorageResolverException {
+ /**
+ * @param directoryName
+ * @throws StorageResolverException
+ */
+ public CertsInFilesystemDirectoryResolver(String directoryName)
+ throws StorageResolverException {
+ this.merlinsCertificatesDir = directoryName;
- this._merlinsCertificatesDir = directoryName;
+ this.readCertsFromHarddrive();
+ }
- this.readCertsFromHarddrive();
-
- this._iterator = new FilesystemIterator(this._certs);
- }
+ /**
+ * Method readCertsFromHarddrive
+ *
+ * @throws StorageResolverException
+ */
+ private void readCertsFromHarddrive() throws StorageResolverException {
- /**
- * Method readCertsFromHarddrive
- *
- * @throws StorageResolverException
- */
- private void readCertsFromHarddrive() throws StorageResolverException {
+ File certDir = new File(this.merlinsCertificatesDir);
+ List<String> al = new ArrayList<String>();
+ String[] names = certDir.list();
- File certDir = new File(this._merlinsCertificatesDir);
- ArrayList<String> al = new ArrayList<String>();
- String[] names = certDir.list();
+ for (int i = 0; i < names.length; i++) {
+ String currentFileName = names[i];
- for (int i = 0; i < names.length; i++) {
- String currentFileName = names[i];
+ if (currentFileName.endsWith(".crt")) {
+ al.add(names[i]);
+ }
+ }
- if (currentFileName.endsWith(".crt")) {
- al.add(names[i]);
- }
- }
+ CertificateFactory cf = null;
- CertificateFactory cf = null;
-
- try {
- cf = CertificateFactory.getInstance("X.509");
- } catch (CertificateException ex) {
- throw new StorageResolverException("empty", ex);
- }
+ try {
+ cf = CertificateFactory.getInstance("X.509");
+ } catch (CertificateException ex) {
+ throw new StorageResolverException("empty", ex);
+ }
- if (cf == null) {
- throw new StorageResolverException("empty");
- }
+ if (cf == null) {
+ throw new StorageResolverException("empty");
+ }
- for (int i = 0; i < al.size(); i++) {
- String filename = certDir.getAbsolutePath() + File.separator
- + al.get(i);
- File file = new File(filename);
- boolean added = false;
- String dn = null;
+ for (int i = 0; i < al.size(); i++) {
+ String filename = certDir.getAbsolutePath() + File.separator + al.get(i);
+ File file = new File(filename);
+ boolean added = false;
+ String dn = null;
- try {
- FileInputStream fis = new FileInputStream(file);
- X509Certificate cert =
- (X509Certificate) cf.generateCertificate(fis);
+ FileInputStream fis = null;
+ try {
+ fis = new FileInputStream(file);
+ X509Certificate cert =
+ (X509Certificate) cf.generateCertificate(fis);
- fis.close();
-
- //add to ArrayList
- cert.checkValidity();
- this._certs.add(cert);
+ //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))
- log.log(java.util.logging.Level.FINE, "Added certificate: " + dn);
- }
- }
- }
+ 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);
+ }
+ }
+ }
- /** @inheritDoc */
- public Iterator<X509Certificate> getIterator() {
- return this._iterator;
- }
+ if (added && log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Added certificate: " + dn);
+ }
+ }
+ }
- /**
- * Class FilesystemIterator
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- private static class FilesystemIterator implements Iterator<X509Certificate> {
+ /** @inheritDoc */
+ public Iterator<Certificate> getIterator() {
+ return new FilesystemIterator(this.certs);
+ }
- /** Field _certs */
- List<X509Certificate> _certs = null;
-
- /** Field _i */
- int _i;
+ /**
+ * Class FilesystemIterator
+ */
+ private static class FilesystemIterator implements Iterator<Certificate> {
- /**
- * Constructor FilesystemIterator
- *
- * @param certs
- */
- public FilesystemIterator(List<X509Certificate> certs) {
- this._certs = certs;
- this._i = 0;
- }
+ /** Field certs */
+ List<X509Certificate> certs = null;
+
+ /** Field i */
+ int i;
- /** @inheritDoc */
- public boolean hasNext() {
- return (this._i < this._certs.size());
- }
-
- /** @inheritDoc */
- public X509Certificate next() {
- return this._certs.get(this._i++);
- }
+ /**
+ * Constructor FilesystemIterator
+ *
+ * @param certs
+ */
+ public FilesystemIterator(List<X509Certificate> certs) {
+ this.certs = certs;
+ this.i = 0;
+ }
- /**
- * Method remove
- *
- */
- public void remove() {
- throw new UnsupportedOperationException(
- "Can't remove keys from KeyStore");
- }
- }
+ /** @inheritDoc */
+ public boolean hasNext() {
+ return (this.i < this.certs.size());
+ }
+
+ /** @inheritDoc */
+ public Certificate next() {
+ return this.certs.get(this.i++);
+ }
+
+ /**
+ * Method remove
+ *
+ */
+ public void remove() {
+ throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+ }
+ }
- /**
- * Method main
- *
- * @param unused
- * @throws Exception
- */
- public static void main(String unused[]) throws Exception {
+ /**
+ * 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<X509Certificate> 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<Certificate> 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() + "\"");
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,147 +2,152 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
import java.security.KeyStore;
import java.security.KeyStoreException;
-import java.security.cert.X509Certificate;
+import java.security.cert.Certificate;
import java.util.Enumeration;
import java.util.Iterator;
+import java.util.NoSuchElementException;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
-
/**
* Makes the Certificates from a JAVA {@link KeyStore} object available to the
* {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
- *
- * @author $Author: mullan $
*/
public class KeyStoreResolver extends StorageResolverSpi {
- /** Field _keyStore */
- KeyStore _keyStore = null;
-
- /** Field _iterator */
- Iterator<X509Certificate> _iterator = null;
+ /** Field keyStore */
+ private KeyStore keyStore = null;
- /**
- * Constructor KeyStoreResolver
- *
- * @param keyStore is the keystore which contains the Certificates
- * @throws StorageResolverException
- */
- public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException {
- this._keyStore = keyStore;
- this._iterator = new KeyStoreIterator(this._keyStore);
- }
-
- /** @inheritDoc */
- public Iterator<X509Certificate> getIterator() {
- return this._iterator;
- }
+ /**
+ * 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);
+ }
+ }
- /**
- * Class KeyStoreIterator
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- static class KeyStoreIterator implements Iterator<X509Certificate> {
-
- /** Field _keyStore */
- KeyStore _keyStore = null;
-
- /** Field _aliases */
- Enumeration<String> _aliases = null;
+ /** @inheritDoc */
+ public Iterator<Certificate> getIterator() {
+ return new KeyStoreIterator(this.keyStore);
+ }
- /**
- * Constructor KeyStoreIterator
- *
- * @param keyStore
- * @throws StorageResolverException
- */
- public KeyStoreIterator(KeyStore keyStore)
- throws StorageResolverException {
+ /**
+ * Class KeyStoreIterator
+ */
+ static class KeyStoreIterator implements Iterator<Certificate> {
- try {
- this._keyStore = keyStore;
- this._aliases = this._keyStore.aliases();
- } catch (KeyStoreException ex) {
- throw new StorageResolverException("generic.EmptyMessage", ex);
- }
- }
+ /** Field keyStore */
+ KeyStore keyStore = null;
+
+ /** Field aliases */
+ Enumeration<String> aliases = null;
+
+ /** Field nextCert */
+ Certificate nextCert = null;
- /** @inheritDoc */
- public boolean hasNext() {
- return this._aliases.hasMoreElements();
- }
-
- /** @inheritDoc */
- @SuppressWarnings("unchecked")
- public X509Certificate next() {
-
- String alias = this._aliases.nextElement();
+ /**
+ * 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<String>() {
+ public boolean hasMoreElements() {
+ return false;
+ }
+ public String nextElement() {
+ return null;
+ }
+ };
+ }
+ }
- try {
- return (X509Certificate)this._keyStore.getCertificate(alias);
- } catch (KeyStoreException ex) {
- return null;
- }
- }
+ /** @inheritDoc */
+ public boolean hasNext() {
+ if (nextCert == null) {
+ nextCert = findNextCert();
+ }
- /**
- * Method remove
- *
- */
- public void remove() {
- throw new UnsupportedOperationException(
- "Can't remove keys from KeyStore");
- }
- }
+ return (nextCert != null);
+ }
+
+ /** @inheritDoc */
+ public Certificate next() {
+ if (nextCert == null) {
+ // maybe caller did not call hasNext()
+ nextCert = findNextCert();
- /**
- * Method main
- *
- * @param unused
- * @throws Exception
- */
- public static void main(String unused[]) throws Exception {
+ if (nextCert == null) {
+ throw new NoSuchElementException();
+ }
+ }
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ Certificate ret = nextCert;
+ nextCert = null;
+ return ret;
+ }
+
+ /**
+ * Method remove
+ */
+ public void remove() {
+ throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+ }
- 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);
+ // 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;
+ }
+ }
- for (Iterator<X509Certificate> i = krs.getIterator(); i.hasNext(); ) {
- X509Certificate cert = i.next();
- byte[] ski =
- com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI
- .getSKIBytesFromCert(cert);
+ return null;
+ }
- System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski));
- }
- }
+ }
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,102 +2,93 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.keys.storage.implementations;
+import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Iterator;
+import java.util.NoSuchElementException;
import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi;
-
/**
* This {@link StorageResolverSpi} makes a single {@link X509Certificate}
* available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}.
- *
- * @author $Author: mullan $
*/
public class SingleCertificateResolver extends StorageResolverSpi {
- /** Field _certificate */
- X509Certificate _certificate = null;
-
- /** Field _iterator */
- Iterator<X509Certificate> _iterator = null;
+ /** Field certificate */
+ private X509Certificate certificate = null;
- /**
- *
- *
- * @param x509cert the single {@link X509Certificate}
- */
- public SingleCertificateResolver(X509Certificate x509cert) {
- this._certificate = x509cert;
- this._iterator = new InternalIterator(this._certificate);
- }
+ /**
+ * @param x509cert the single {@link X509Certificate}
+ */
+ public SingleCertificateResolver(X509Certificate x509cert) {
+ this.certificate = x509cert;
+ }
- /** @inheritDoc */
- public Iterator<X509Certificate> getIterator() {
- return this._iterator;
- }
+ /** @inheritDoc */
+ public Iterator<Certificate> getIterator() {
+ return new InternalIterator(this.certificate);
+ }
- /**
- * Class InternalIterator
- *
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
- */
- static class InternalIterator implements Iterator<X509Certificate> {
+ /**
+ * Class InternalIterator
+ */
+ static class InternalIterator implements Iterator<Certificate> {
- /** 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 X509Certificate next() {
-
- this._alreadyReturned = true;
-
- return this._certificate;
- }
+ /** @inheritDoc */
+ public Certificate next() {
+ if (this.alreadyReturned) {
+ throw new NoSuchElementException();
+ }
+ this.alreadyReturned = true;
+ return this.certificate;
+ }
- /**
- * Method remove
- *
- */
- public void remove() {
- throw new UnsupportedOperationException(
- "Can't remove keys from KeyStore");
- }
- }
+ /**
+ * Method remove
+ */
+ public void remove() {
+ throw new UnsupportedOperationException("Can't remove keys from KeyStore");
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml Fri Jul 05 14:37:41 2013 -0700
@@ -52,9 +52,6 @@
<TransformAlgorithm URI="http://www.w3.org/TR/1999/REC-xslt-19991116"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXSLT" />
<!-- XPath version 2 -->
- <TransformAlgorithm URI="http://www.w3.org/2002/04/xmldsig-filter2"
- JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter" />
- <!-- XPath version 2b -->
<TransformAlgorithm URI="http://www.w3.org/2002/06/xmldsig-filter2"
JAVACLASS="com.sun.org.apache.xml.internal.security.transforms.implementations.TransformXPath2Filter" />
</TransformAlgorithms>
@@ -78,6 +75,12 @@
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA1" />
+ <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
+ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA256" />
+ <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
+ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA384" />
+ <SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
+ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA$SignatureECDSASHA512" />
<SignatureAlgorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac$IntegrityHmacMD5" />
@@ -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"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#ripemd160"
@@ -122,7 +125,7 @@
Description="SHA message digest with 384 bit"
AlgorithmClass="MessageDigest"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="SHA-384"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#sha512"
@@ -142,14 +145,14 @@
Description="RSA Signature with MD5 message digest"
AlgorithmClass="Signature"
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="MD5withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-ripemd160"
Description="RSA Signature with RIPEMD-160 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="RIPEMD160withRSA"/>
<Algorithm URI="http://www.w3.org/2000/09/xmldsig#rsa-sha1"
@@ -162,43 +165,64 @@
Description="RSA Signature with SHA-256 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="SHA256withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha384"
Description="RSA Signature with SHA-384 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="SHA384withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
Description="RSA Signature with SHA-512 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="SHA512withRSA"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"
Description="ECDSA Signature with SHA-1 message digest"
AlgorithmClass="Signature"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
- JCEName="ECDSAwithSHA1"/>
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+ JCEName="SHA1withECDSA"/>
+
+ <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"
+ Description="ECDSA Signature with SHA-256 message digest"
+ AlgorithmClass="Signature"
+ RequirementLevel="OPTIONAL"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+ JCEName="SHA256withECDSA"/>
+
+ <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"
+ Description="ECDSA Signature with SHA-384 message digest"
+ AlgorithmClass="Signature"
+ RequirementLevel="OPTIONAL"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+ JCEName="SHA384withECDSA"/>
+
+ <Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"
+ Description="ECDSA Signature with SHA-512 message digest"
+ AlgorithmClass="Signature"
+ RequirementLevel="OPTIONAL"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
+ JCEName="SHA512withECDSA"/>
<!-- MAC Algorithms -->
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-md5"
Description="Message Authentication code using MD5"
AlgorithmClass="Mac"
RequirementLevel="NOT RECOMMENDED"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="HmacMD5"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"
Description="Message Authentication code using RIPEMD-160"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="HMACRIPEMD160"/>
<Algorithm URI="http://www.w3.org/2000/09/xmldsig#hmac-sha1"
@@ -211,21 +235,21 @@
Description="Message Authentication code using SHA-256"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="HmacSHA256"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"
Description="Message Authentication code using SHA-384"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="HmacSHA384"/>
<Algorithm URI="http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"
Description="Message Authentication code using SHA-512"
AlgorithmClass="Mac"
RequirementLevel="OPTIONAL"
- SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt"
+ SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt"
JCEName="HmacSHA512"/>
<!-- Block encryption Algorithms -->
@@ -260,7 +284,31 @@
KeyLength="256"
RequiredKey="AES"
JCEName="AES/CBC/ISO10126Padding"/>
+
+ <Algorithm URI="http://www.w3.org/2009/xmlenc11#aes128-gcm"
+ Description="Block encryption using AES with a key length of 128 bit in GCM"
+ AlgorithmClass="BlockEncryption"
+ RequirementLevel="OPTIONAL"
+ KeyLength="128"
+ RequiredKey="AES"
+ JCEName="AES/GCM/NoPadding"/>
+
+ <Algorithm URI="http://www.w3.org/2009/xmlenc11#aes192-gcm"
+ Description="Block encryption using AES with a key length of 192 bit in GCM"
+ AlgorithmClass="BlockEncryption"
+ RequirementLevel="OPTIONAL"
+ KeyLength="192"
+ RequiredKey="AES"
+ JCEName="AES/GCM/NoPadding"/>
+ <Algorithm URI="http://www.w3.org/2009/xmlenc11#aes256-gcm"
+ Description="Block encryption using AES with a key length of 256 bit in GCM"
+ AlgorithmClass="BlockEncryption"
+ RequirementLevel="OPTIONAL"
+ KeyLength="256"
+ RequiredKey="AES"
+ JCEName="AES/GCM/NoPadding"/>
+
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#rsa-1_5"
Description="Key Transport RSA-v1.5"
AlgorithmClass="KeyTransport"
@@ -273,7 +321,14 @@
AlgorithmClass="KeyTransport"
RequirementLevel="REQUIRED"
RequiredKey="RSA"
- JCEName="RSA/ECB/OAEPWithSHA1AndMGF1Padding"/>
+ JCEName="RSA/ECB/OAEPPadding"/>
+
+ <Algorithm URI="http://www.w3.org/2009/xmlenc11#rsa-oaep"
+ Description="Key Transport RSA-OAEP"
+ AlgorithmClass="KeyTransport"
+ RequirementLevel="OPTIONAL"
+ RequiredKey="RSA"
+ JCEName="RSA/ECB/OAEPPadding"/>
<Algorithm URI="http://www.w3.org/2001/04/xmlenc#dh"
Description="Key Agreement Diffie-Hellman"
@@ -314,14 +369,7 @@
</Algorithms>
</JCEAlgorithmMappings>
- <ResourceBundles defaultLanguageCode="en" defaultCountryCode="US">
- <ResourceBundle LanguageCode="en"
- CountryCode="US"
- LOCATION="com.sun.org.apache.xml.internal.security/resource/xmlsecurity_en.properties" />
- <ResourceBundle LanguageCode="de"
- CountryCode="DE"
- LOCATION="com.sun.org.apache.xml.internal.security/resource/xmlsecurity_de.properties" />
- </ResourceBundles>
+ <ResourceBundles defaultLanguageCode="en" defaultCountryCode="US"/>
<ResourceResolvers>
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverDirectHTTP"
DESCRIPTION="A simple resolver for requests to HTTP space" />
@@ -330,32 +378,8 @@
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment"
DESCRIPTION="A simple resolver for requests of same-document URIs" />
<Resolver JAVACLASS="com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverXPointer"
- DESCRIPTION="A simple resolver for requests of XPointer fragents" />
+ DESCRIPTION="A simple resolver for requests of XPointer fragments" />
</ResourceResolvers>
- <!-- <defaultLocale languageCode="en" countryCode="US" /> -->
- <KeyInfo>
- <ContentHandler LOCALNAME="KeyName"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.KeyName" />
- <ContentHandler LOCALNAME="KeyValue"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.KeyValue" />
- <ContentHandler LOCALNAME="RetrievalMethod"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.RetrievalMethod" />
- <ContentHandler LOCALNAME="X509Data"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.X509Data" />
- <ContentHandler LOCALNAME="PGPData"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.PGPData" />
- <ContentHandler LOCALNAME="SPKIData"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.SPKIData" />
- <ContentHandler LOCALNAME="MgmtData"
- NAMESPACE="http://www.w3.org/2000/09/xmldsig#"
- JAVACLASS="com.sun.org.apache.xml.internal.security.keys.content.MgmtData" />
- </KeyInfo>
<KeyResolver>
<!-- This section contains a list of KeyResolvers that are available in
every KeyInfo object -->
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties Fri Jul 05 13:28:17 2013 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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
-
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties Fri Jul 05 14:37:41 2013 -0700
@@ -5,6 +5,7 @@
algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures.
algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures.
algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs.
+algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0}
algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms
algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1}
algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm
@@ -88,8 +89,13 @@
signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0}
signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature
signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first
+signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled
+signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled
signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein
+signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation
+signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation
signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf.
+signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled
signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert
signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler?
signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0}
@@ -103,6 +109,7 @@
signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen
signature.Verification.MissingID = Cannot resolve element with ID {0}
signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen
+signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected
signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1}
signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten.
signature.Verification.SignatureError = Signatur Fehler
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties Fri Jul 05 14:37:41 2013 -0700
@@ -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 <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
-errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
-errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
-errorMessages.IOException = Other file I/O and similar exceptions.
-errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
-errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
-errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
-errorMessages.NotYetImplementedException = Functionality not yet there.
-errorMessages.XMLSignatureException = Verification failed for some other reason.
-decoding.divisible.four = It should be divisible by four
-decoding.general = Error while decoding
-FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
-FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
-FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
-FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
-generic.dontHaveConstructionElement = I do not have a construction Element
-generic.EmptyMessage = {0}
-generic.NotYetImplemented = {0} Not YET implemented ;-((
-java.security.InvalidKeyException = Invalid key
-java.security.NoSuchProviderException = Unknown or unsupported provider
-java.security.UnknownKeyType = Unknown or unsupported key type {0}
-KeyInfo.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 <http://xml.apache.org/security/Java/installation.html> how to solve this problem.
+errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution.
+errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed.
+errorMessages.IOException = Other file I/O and similar exceptions.
+errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again.
+errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again.
+errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0}
+errorMessages.NotYetImplementedException = Functionality not yet there.
+errorMessages.XMLSignatureException = Verification failed for some other reason.
+decoding.divisible.four = It should be divisible by four
+decoding.general = Error while decoding
+FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented.
+FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0}
+FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1}
+FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0}
+generic.dontHaveConstructionElement = I do not have a construction Element
+generic.EmptyMessage = {0}
+generic.NotYetImplemented = {0} Not YET implemented ;-((
+java.security.InvalidKeyException = Invalid key
+java.security.NoSuchProviderException = Unknown or unsupported provider
+java.security.UnknownKeyType = Unknown or unsupported key type {0}
+KeyInfo.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}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,85 +2,85 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
/**
- * Raised when the computed hash value doesn't match the given <i>DigestValue</i>. Additional human readable info is passed to the constructor -- this being the benefit of raising an exception or returning a value.
+ * Raised when the computed hash value doesn't match the given <i>DigestValue</i>.
+ * Additional human readable info is passed to the constructor -- this being the benefit
+ * of raising an exception or returning a value.
*
* @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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
/**
* Raised if testing the signature value over <i>DigestValue</i> fails because of invalid signature.
*
@@ -30,58 +30,56 @@
*/
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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,33 +2,33 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Set;
-import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
@@ -38,7 +38,6 @@
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
@@ -50,523 +49,561 @@
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
-
-
/**
* Handles <code><ds:Manifest></code> elements.
* <p> This element holds the <code>Reference</code> elements</p>
- * @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<Reference> _references;
- Element[] _referencesEl;
+ /** Field references */
+ private List<Reference> references;
+ private Element[] referencesEl;
- /** Field verificationResults[] */
- private boolean verificationResults[] = null;
+ /** Field verificationResults[] */
+ private boolean verificationResults[] = null;
- /** Field _resolverProperties */
- Map<String,String> _resolverProperties = null;
+ /** Field resolverProperties */
+ private Map<String, String> resolverProperties = null;
- /** Field _perManifestResolvers */
- List<ResourceResolver> _perManifestResolvers = null;
+ /** Field perManifestResolvers */
+ private List<ResourceResolver> perManifestResolvers = null;
- /**
- * Consturts {@link Manifest}
- *
- * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
- */
- public Manifest(Document doc) {
+ private boolean secureValidation;
- super(doc);
+ /**
+ * Constructs {@link Manifest}
+ *
+ * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+ */
+ public Manifest(Document doc) {
+ super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
- this._references = new ArrayList<Reference>();
- }
+ this.references = new ArrayList<Reference>();
+ }
- /**
- * Constructor Manifest
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public Manifest(Element element, String BaseURI)
- throws XMLSecurityException {
-
- super(element, BaseURI);
+ /**
+ * Constructor Manifest
+ *
+ * @param element
+ * @param baseURI
+ * @throws XMLSecurityException
+ */
+ public Manifest(Element element, String baseURI) throws XMLSecurityException {
+ this(element, baseURI, false);
- Attr attr = element.getAttributeNodeNS(null, "Id");
- if (attr != null) {
- element.setIdAttributeNode(attr, true);
- }
+ }
+ /**
+ * Constructor Manifest
+ *
+ * @param element
+ * @param baseURI
+ * @param secureValidation
+ * @throws XMLSecurityException
+ */
+ public Manifest(
+ Element element, String baseURI, boolean secureValidation
+ ) throws XMLSecurityException {
+ super(element, baseURI);
- // 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<Reference>(le);
+ if (secureValidation && le > MAXIMUM_REFERENCE_COUNT) {
+ Object exArgs[] = { le, MAXIMUM_REFERENCE_COUNT };
+
+ throw new XMLSecurityException("signature.tooManyReferences", exArgs);
+ }
- 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);
- }
- }
+ // create List
+ this.references = new ArrayList<Reference>(le);
+
+ for (int i = 0; i < le; i++) {
+ Element refElem = referencesEl[i];
+ Attr refAttr = refElem.getAttributeNodeNS(null, "Id");
+ if (refAttr != null) {
+ refElem.setIdAttributeNode(refAttr, true);
+ }
+ this.references.add(null);
+ }
+ }
- /**
- * This <code>addDocument</code> method is used to add a new resource to the
- * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
- * from the supplied values.
- *
- * @param BaseURI the URI of the resource where the XML instance was stored
- * @param referenceURI <code>URI</code> attribute in <code>Reference</code> 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 {
+ /**
+ * This <code>addDocument</code> method is used to add a new resource to the
+ * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
+ * from the supplied values.
+ *
+ * @param baseURI the URI of the resource where the XML instance was stored
+ * @param referenceURI <code>URI</code> attribute in <code>Reference</code> 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);
- // the this._doc is handed implicitly by the this.getOwnerDocument()
- Reference ref = new Reference(this._doc, BaseURI, referenceURI, this,
- transforms, digestURI);
+ if (referenceId != null) {
+ ref.setId(referenceId);
+ }
- if (ReferenceId != null) {
- ref.setId(ReferenceId);
- }
-
- if (ReferenceType != null) {
- ref.setType(ReferenceType);
- }
-
- // 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);
+
+ // add the Element of the Reference object to the Manifest/SignedInfo
+ this.constructionElement.appendChild(ref.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * The calculation of the DigestValues in the References must be after the
- * References are already added to the document and during the signing
- * process. This ensures that all neccesary data is in place.
- *
- * @throws ReferenceNotInitializedException
- * @throws XMLSignatureException
- */
- public void generateDigestValues()
- throws XMLSignatureException, ReferenceNotInitializedException {
-
- for (int i = 0; i < this.getLength(); i++) {
-
+ /**
+ * 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 nonnegative number of added references.
+ *
+ * @return the number of references
+ */
+ public int getLength() {
+ return this.references.size();
+ }
- /**
- * Return the <it>i</it><sup>th</sup> reference. Valid <code>i</code>
- * values are 0 to <code>{link@ getSize}-1</code>.
- *
- * @param i Index of the requested {@link Reference}
- * @return the <it>i</it><sup>th</sup> reference
- * @throws XMLSecurityException
- */
- public Reference item(int i) throws XMLSecurityException {
+ /**
+ * Return the <it>i</it><sup>th</sup> reference. Valid <code>i</code>
+ * values are 0 to <code>{link@ getSize}-1</code>.
+ *
+ * @param i Index of the requested {@link Reference}
+ * @return the <it>i</it><sup>th</sup> reference
+ * @throws XMLSecurityException
+ */
+ public Reference item(int i) throws XMLSecurityException {
+ if (this.references.get(i) == null) {
+ // not yet constructed, so _we_ have to
+ Reference ref =
+ new Reference(referencesEl[i], this.baseURI, this, secureValidation);
- if (this._references.get(i) == null) {
-
- // not yet constructed, so _we_ have to
- Reference ref = new Reference(_referencesEl[i], this._baseURI, this);
+ this.references.set(i, ref);
+ }
- this._references.set(i, ref);
- }
-
- return this._references.get(i);
-
- }
+ return this.references.get(i);
+ }
- /**
- * Sets the <code>Id</code> attribute
- *
- * @param Id the <code>Id</code> attribute in <code>ds:Manifest</code>
- */
- public void setId(String Id) {
+ /**
+ * Sets the <code>Id</code> attribute
+ *
+ * @param Id the <code>Id</code> attribute in <code>ds:Manifest</code>
+ */
+ 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 (Id != null) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
-
- /**
- * Returns the <code>Id</code> attribute
- *
- * @return the <code>Id</code> attribute in <code>ds:Manifest</code>
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
+ /**
+ * Returns the <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> attribute in <code>ds:Manifest</code>
+ */
+ public String getId() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ }
- /**
- * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
- * validation</A> of all enclosed references using the {@link Reference#verify} method.
- *
- * <p>This step loops through all {@link Reference}s and does verify the hash
- * values. If one or more verifications fail, the method returns
- * <code>false</code>. If <i>all</i> verifications are successful,
- * it returns <code>true</code>. The results of the individual reference
- * validations are available by using the {@link #getVerificationResult(int)} method
- *
- * @return true if all References verify, false if one or more do not verify.
- * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput}
- * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
- * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()
- * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
- * @throws XMLSecurityException
- */
- public boolean verifyReferences()
- throws MissingResourceFailureException, XMLSecurityException {
- return this.verifyReferences(false);
- }
+ /**
+ * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
+ * validation</A> of all enclosed references using the {@link Reference#verify} method.
+ *
+ * <p>This step loops through all {@link Reference}s and does verify the hash
+ * values. If one or more verifications fail, the method returns
+ * <code>false</code>. If <i>all</i> verifications are successful,
+ * it returns <code>true</code>. The results of the individual reference
+ * validations are available by using the {@link #getVerificationResult(int)} method
+ *
+ * @return true if all References verify, false if one or more do not verify.
+ * @throws MissingResourceFailureException if a {@link Reference} does not verify
+ * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException}
+ * because of an uninitialized {@link XMLSignatureInput}
+ * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
+ * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()
+ * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
+ * @throws XMLSecurityException
+ */
+ public boolean verifyReferences()
+ throws MissingResourceFailureException, XMLSecurityException {
+ return this.verifyReferences(false);
+ }
- /**
- * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
- * validation</A> of all enclosed references using the {@link Reference#verify} method.
- *
- * <p>This step loops through all {@link Reference}s and does verify the hash
- * values. If one or more verifications fail, the method returns
- * <code>false</code>. If <i>all</i> verifications are successful,
- * it returns <code>true</code>. The results of the individual reference
- * validations are available by using the {@link #getVerificationResult(int)} method
- *
- * @param followManifests
- * @return true if all References verify, false if one or more do not verify.
- * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput}
- * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify
- * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean)
- * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException
- * @throws XMLSecurityException
- */
- public boolean verifyReferences(boolean followManifests)
- throws MissingResourceFailureException, XMLSecurityException {
- if (_referencesEl==null) {
- this._referencesEl =
- XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(),
- Constants._TAG_REFERENCE);
- }
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "verify " +_referencesEl.length + " References");
- log.log(java.util.logging.Level.FINE, "I am " + (followManifests
- ? ""
- : "not") + " requested to follow nested Manifests");
- }
- boolean verify = true;
-
- if (_referencesEl.length==0) {
- throw new XMLSecurityException("empty");
- }
+ /**
+ * Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
+ * validation</A> of all enclosed references using the {@link Reference#verify} method.
+ *
+ * <p>This step loops through all {@link Reference}s and does verify the hash
+ * values. If one or more verifications fail, the method returns
+ * <code>false</code>. If <i>all</i> verifications are successful,
+ * it returns <code>true</code>. 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 };
- this.verificationResults =
- new boolean[_referencesEl.length];
-
- for (int i =
- 0; i < this._referencesEl.length; i++) {
- Reference currentRef =
- new Reference(_referencesEl[i], this._baseURI, this);
+ throw new XMLSecurityException("signature.tooManyReferences", exArgs);
+ }
- this._references.set(i, currentRef);
+ 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 only one item does not verify, the whole verification fails */
- try {
- boolean currentRefVerified = currentRef.verify();
+ this.references.set(i, currentRef);
- this.setVerificationResult(i, currentRefVerified);
+ // if only one item does not verify, the whole verification fails
+ try {
+ boolean currentRefVerified = currentRef.verify();
+
+ this.setVerificationResult(i, currentRefVerified);
- if (!currentRefVerified) {
- verify = false;
- }
- if (log.isLoggable(java.util.logging.Level.FINE))
- log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType());
+ if (!currentRefVerified) {
+ verify = false;
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType());
+ }
- // was verification successful till now and do we want to verify the Manifest?
- if (verify && followManifests
- && currentRef.typeIsReferenceToManifest()) {
- log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest");
+ // was verification successful till now and do we want to verify the Manifest?
+ if (verify && followManifests && currentRef.typeIsReferenceToManifest()) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest");
+ }
- try {
- XMLSignatureInput signedManifestNodes =
- currentRef.dereferenceURIandPerformTransforms(null);
- Set<Node> nl = signedManifestNodes.getNodeSet();
- Manifest referencedManifest = null;
- Iterator<Node> nlIterator = nl.iterator();
+ try {
+ XMLSignatureInput signedManifestNodes =
+ currentRef.dereferenceURIandPerformTransforms(null);
+ Set<Node> nl = signedManifestNodes.getNodeSet();
+ Manifest referencedManifest = null;
+ Iterator<Node> nlIterator = nl.iterator();
- findManifest: while (nlIterator.hasNext()) {
- Node n = nlIterator.next();
+ 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) {
+ 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
+ }
+ }
+ }
- // Hm, seems not to be a ds:Manifest
+ if (referencedManifest == null) {
+ // The Reference stated that it points to a ds:Manifest
+ // but we did not find a ds:Manifest in the signed area
+ throw new MissingResourceFailureException("empty", currentRef);
}
- }
- }
- 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);
- }
+ 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 {
- 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);
- }
+ log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)");
+ } else {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)");
+ }
+ }
+ } catch (IOException ex) {
+ throw new ReferenceNotInitializedException("empty", ex);
+ } catch (ParserConfigurationException ex) {
+ throw new ReferenceNotInitializedException("empty", ex);
+ } catch (SAXException ex) {
+ throw new ReferenceNotInitializedException("empty", ex);
+ }
+ }
+ } catch (ReferenceNotInitializedException ex) {
+ Object exArgs[] = { currentRef.getURI() };
+
+ throw new MissingResourceFailureException(
+ "signature.Verification.Reference.NoInput", exArgs, ex, currentRef
+ );
}
- } 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()];
+ }
+
+ this.verificationResults[index] = verify;
+ }
- /**
- * Method setVerificationResult
- *
- * @param index
- * @param verify
- */
- private void setVerificationResult(int index, boolean verify)
- {
-
- if (this.verificationResults == null) {
- this.verificationResults = new boolean[this.getLength()];
- }
-
- this.verificationResults[index] = verify;
- }
+ /**
+ * After verifying a {@link Manifest} or a {@link SignedInfo} using the
+ * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods,
+ * the individual results can be retrieved with this method.
+ *
+ * @param index an index of into a {@link Manifest} or a {@link SignedInfo}
+ * @return the results of reference validation at the specified index
+ * @throws XMLSecurityException
+ */
+ public boolean getVerificationResult(int index) throws XMLSecurityException {
+ if ((index < 0) || (index > this.getLength() - 1)) {
+ Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) };
+ Exception e =
+ new IndexOutOfBoundsException(
+ I18n.translate("signature.Verification.IndexOutOfBounds", exArgs)
+ );
- /**
- * 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 {
+ throw new XMLSecurityException("generic.EmptyMessage", e);
+ }
- 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));
+ if (this.verificationResults == null) {
+ try {
+ this.verifyReferences();
+ } catch (Exception ex) {
+ throw new XMLSecurityException("generic.EmptyMessage", ex);
+ }
+ }
+
+ return this.verificationResults[index];
+ }
- throw new XMLSecurityException("generic.EmptyMessage", e);
- }
-
- if (this.verificationResults == null) {
- try {
- this.verifyReferences();
- } catch (Exception ex) {
- throw new XMLSecurityException("generic.EmptyMessage", ex);
- }
- }
-
- return this.verificationResults[index];
- }
-
- /**
- * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute in <code>reference</code> element
- *
- * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource.
- */
- public void addResourceResolver(ResourceResolver resolver) {
+ /**
+ * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
+ * in <code>reference</code> 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<ResourceResolver>();
+ }
+ this.perManifestResolvers.add(resolver);
+ }
- if (resolver == null) {
- return;
- }
- if (_perManifestResolvers==null)
- _perManifestResolvers = new ArrayList<ResourceResolver>();
- this._perManifestResolvers.add(resolver);
-
- }
+ /**
+ * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
+ * in <code>reference</code> 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<ResourceResolver>();
+ }
+ perManifestResolvers.add(new ResourceResolver(resolverSpi));
+ }
- /**
- * Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute in <code>reference</code> element
- *
- * @param resolverSpi the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource.
- */
- public void addResourceResolver(ResourceResolverSpi resolverSpi) {
-
- if (resolverSpi == null) {
- return;
- }
- if (_perManifestResolvers==null)
- _perManifestResolvers = new ArrayList<ResourceResolver>();
- this._perManifestResolvers.add(new ResourceResolver(resolverSpi));
+ /**
+ * Get the Per-Manifest Resolver List
+ * @return the per-manifest Resolver List
+ */
+ public List<ResourceResolver> getPerManifestResolvers() {
+ return perManifestResolvers;
+ }
- }
+ /**
+ * Get the resolver property map
+ * @return the resolver property map
+ */
+ public Map<String, String> getResolverProperties() {
+ return resolverProperties;
+ }
- /**
- * Used to pass parameters like proxy servers etc to the ResourceResolver
- * implementation.
- *
- * @param key the key
- * @param value the value
- */
- public void setResolverProperty(String key, String value) {
- if (_resolverProperties==null) {
- _resolverProperties=new HashMap<String, String>(10);
- }
- this._resolverProperties.put(key, value);
- }
+ /**
+ * 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<String, String>(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);
- }
+ /**
+ * 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 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 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 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 getSignedContentLength
+ *
+ * @return The number of references contained in this reference.
+ */
+ public int getSignedContentLength() {
+ return this.getLength();
+ }
- /**
- * Method getBaseLocalName
- *
- * @inheritDoc
- */
- public String getBaseLocalName() {
- return Constants._TAG_MANIFEST;
- }
+ /**
+ * Method getBaseLocalName
+ *
+ * @inheritDoc
+ */
+ public String getBaseLocalName() {
+ return Constants._TAG_MANIFEST;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
-
-
/**
* Thrown by {@link com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()} when
* testing the signature fails because of uninitialized
@@ -34,97 +32,93 @@
*/
public class MissingResourceFailureException extends XMLSignatureException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- /** Field uninitializedReference */
- Reference uninitializedReference = null;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ /** Field uninitializedReference */
+ private Reference uninitializedReference = null;
- /**
- * MissingKeyResourceFailureException constructor.
- * @param _msgID
- * @param reference
- * @see #getReference
- */
- public MissingResourceFailureException(String _msgID, Reference reference) {
-
- super(_msgID);
+ /**
+ * 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) {
+ /**
+ * Constructor MissingResourceFailureException
+ *
+ * @param msgID
+ * @param originalException
+ * @param reference
+ * @see #getReference
+ */
+ public MissingResourceFailureException(
+ String msgID, Exception originalException, Reference reference
+ ) {
+ super(msgID, originalException);
- super(_msgID, _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) {
+ /**
+ * 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);
- super(_msgID, exArgs, _originalException);
-
- this.uninitializedReference = reference;
- }
+ 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 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.signature;
@@ -24,30 +26,30 @@
/**
* An interface to tell to the c14n if a node is included or not in the output
- * @author raul
- *
*/
public interface NodeFilter {
- /**
- * Tells if a node must be outputed in c14n.
- * @param n
- * @return 1 if the node should be outputed.
- * 0 if node must not be outputed,
- * -1 if the node and all it's child must not be output.
- *
- */
- public int isNodeInclude(Node n);
- /**
- * Tells if a node must be outputed in a c14n.
- * The caller must assured that this method is always call
- * in document order. The implementations can use this
- * restriction to optimize the transformation.
- * @param n
- * @param level the relative level in the tree
- * @return 1 if the node should be outputed.
- * 0 if node must not be outputed,
- * -1 if the node and all it's child must not be output.
- */
- public int isNodeIncludeDO(Node n, int level);
+
+ /**
+ * Tells if a node must be output in c14n.
+ * @param n
+ * @return 1 if the node should be output.
+ * 0 if node must not be output,
+ * -1 if the node and all it's child must not be output.
+ *
+ */
+ int isNodeInclude(Node n);
+
+ /**
+ * Tells if a node must be output in a c14n.
+ * The caller must assured that this method is always call
+ * in document order. The implementations can use this
+ * restriction to optimize the transformation.
+ * @param n
+ * @param level the relative level in the tree
+ * @return 1 if the node should be output.
+ * 0 if node must not be output,
+ * -1 if the node and all it's child must not be output.
+ */
+ int isNodeIncludeDO(Node n, int level);
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -38,111 +39,99 @@
*/
public class ObjectContainer extends SignatureElementProxy {
- /**
- * Constructs {@link ObjectContainer}
- *
- * @param doc the {@link Document} in which <code>Object</code> element is placed
- */
- public ObjectContainer(Document doc) {
-
- super(doc);
- }
+ /**
+ * Constructs {@link ObjectContainer}
+ *
+ * @param doc the {@link Document} in which <code>Object</code> element is placed
+ */
+ public ObjectContainer(Document doc) {
+ super(doc);
+ }
- /**
- * Constructs {@link ObjectContainer} from {@link Element}
- *
- * @param element is <code>Object</code> 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 <code>Object</code> element
+ * @param baseURI the URI of the resource where the XML instance was stored
+ * @throws XMLSecurityException
+ */
+ public ObjectContainer(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
+ }
- /**
- * Sets the <code>Id</code> attribute
- *
- * @param Id <code>Id</code> attribute
- */
- public void setId(String Id) {
-
- if (Id != null) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
+ /**
+ * Sets the <code>Id</code> attribute
+ *
+ * @param Id <code>Id</code> attribute
+ */
+ public void setId(String Id) {
+ if (Id != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+ this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ }
+ }
- /**
- * Returns the <code>Id</code> attribute
- *
- * @return the <code>Id</code> attribute
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
-
- /**
- * Sets the <code>MimeType</code> attribute
- *
- * @param MimeType the <code>MimeType</code> attribute
- */
- public void setMimeType(String MimeType) {
+ /**
+ * Returns the <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> attribute
+ */
+ public String getId() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ }
- if ( (MimeType != null)) {
- this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE,
- MimeType);
- }
- }
+ /**
+ * Sets the <code>MimeType</code> attribute
+ *
+ * @param MimeType the <code>MimeType</code> attribute
+ */
+ public void setMimeType(String MimeType) {
+ if (MimeType != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType);
+ }
+ }
- /**
- * Returns the <code>MimeType</code> attribute
- *
- * @return the <code>MimeType</code> attribute
- */
- public String getMimeType() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE);
- }
-
- /**
- * Sets the <code>Encoding</code> attribute
- *
- * @param Encoding the <code>Encoding</code> attribute
- */
- public void setEncoding(String Encoding) {
-
- if ((Encoding != null)) {
- this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING,
- Encoding);
- }
- }
+ /**
+ * Returns the <code>MimeType</code> attribute
+ *
+ * @return the <code>MimeType</code> attribute
+ */
+ public String getMimeType() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE);
+ }
- /**
- * Returns the <code>Encoding</code> attribute
- *
- * @return the <code>Encoding</code> attribute
- */
- public String getEncoding() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING);
- }
+ /**
+ * Sets the <code>Encoding</code> attribute
+ *
+ * @param Encoding the <code>Encoding</code> attribute
+ */
+ public void setEncoding(String Encoding) {
+ if (Encoding != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding);
+ }
+ }
- /**
- * Adds child Node
- *
- * @param node child Node
- * @return the new node in the tree.
- */
- public Node appendChild(Node node) {
-
- Node result = null;
+ /**
+ * Returns the <code>Encoding</code> attribute
+ *
+ * @return the <code>Encoding</code> attribute
+ */
+ public String getEncoding() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING);
+ }
- result = this._constructionElement.appendChild(node);
-
- return result;
- }
+ /**
+ * Adds child Node
+ *
+ * @param node child Node
+ * @return the new node in the tree.
+ */
+ public Node appendChild(Node node) {
+ return this.constructionElement.appendChild(node);
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_OBJECT;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_OBJECT;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,31 +2,32 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
import java.io.IOException;
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
@@ -34,6 +35,10 @@
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceOctetStreamData;
+import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceSubTreeData;
import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
@@ -42,7 +47,6 @@
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
@@ -54,7 +58,6 @@
import org.w3c.dom.Node;
import org.w3c.dom.Text;
-
/**
* Handles <code><ds:Reference></code> elements.
*
@@ -64,17 +67,17 @@
*
* <p>Create a new reference</p>
* <pre>
- * 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);
* </pre>
*
* <p>Verify a reference</p>
* <pre>
- * 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 @@
*/
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<Boolean>() {
- 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;
+
+ /** Field MANIFEST_URI */
+ public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
+
+ /**
+ * The maximum number of transforms per reference, if secure validation is enabled.
+ */
+ public static final int MAXIMUM_TRANSFORM_COUNT = 5;
+
+ private boolean secureValidation;
-/*
- static {
- try {
- useC14N11 = Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11");
- } catch (Exception e) {
- // ignore exceptions
- }
- }
-*/
+ /**
+ * 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<Boolean>() {
+ public Boolean run() {
+ return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
+ }
+ })).booleanValue();
- /** Field CacheSignedNodes */
- public final static boolean CacheSignedNodes = false;
-
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static final java.util.logging.Logger log =
java.util.logging.Logger.getLogger(Reference.class.getName());
- /** Field OBJECT_URI */
- public static final String OBJECT_URI = Constants.SignatureSpecNS
- + Constants._TAG_OBJECT;
+ private Manifest manifest;
+ private XMLSignatureInput transformsOutput;
+
+ private Transforms transforms;
- /** Field MANIFEST_URI */
- public static final String MANIFEST_URI = Constants.SignatureSpecNS
- + Constants._TAG_MANIFEST;
- //J-
- Manifest _manifest = null;
- XMLSignatureInput _transformsOutput;
- //J+
+ private Element digestMethodElem;
-private Transforms transforms;
+ private Element digestValueElement;
-private Element digestMethodElem;
+ private ReferenceData referenceData;
-private Element digestValueElement;
-
- /**
- * Constructor Reference
- *
- * @param doc the {@link Document} in which <code>XMLsignature</code> 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);
+ /**
+ * Constructor Reference
+ *
+ * @param doc the {@link Document} in which <code>XMLsignature</code> 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);
+ XMLUtils.addReturnToElement(this.constructionElement);
- this._baseURI = BaseURI;
- this._manifest = manifest;
+ this.baseURI = baseURI;
+ this.manifest = manifest;
- this.setURI(ReferenceURI);
+ 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"));
+ // 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);
+ 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);
+ digestMethodElem = mda.getElement();
+ this.constructionElement.appendChild(digestMethodElem);
+ XMLUtils.addReturnToElement(this.constructionElement);
- this._constructionElement.appendChild(digestValueElement);
- 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 <code>Reference</code> 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;
- }
+ /**
+ * Build a {@link Reference} from an {@link Element}
+ *
+ * @param element <code>Reference</code> 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);
+ }
- String uri = digestMethodElem.getAttributeNS(null,
- Constants._ATT_ALGORITHM);
-
- if (uri == null) {
- return null;
- }
-
- return MessageDigestAlgorithm.getInstance(this._doc, uri);
- }
-
- /**
- * Sets the <code>URI</code> of this <code>Reference</code> element
- *
- * @param URI the <code>URI</code> of this <code>Reference</code> element
- */
- public void setURI(String URI) {
+ /**
+ * Build a {@link Reference} from an {@link Element}
+ *
+ * @param element <code>Reference</code> 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 };
- if ( URI != null) {
- this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
- URI);
- }
- }
-
- /**
- * Returns the <code>URI</code> of this <code>Reference</code> element
- *
- * @return URI the <code>URI</code> of this <code>Reference</code> element
- */
- public String getURI() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
- }
-
- /**
- * Sets the <code>Id</code> attribute of this <code>Reference</code> element
- *
- * @param Id the <code>Id</code> attribute of this <code>Reference</code> element
- */
- public void setId(String Id) {
+ throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
+ }
+ el = XMLUtils.getNextElement(el.getNextSibling());
+ }
+ digestMethodElem = el;
+ digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
+ this.manifest = manifest;
+ }
- if ( Id != null ) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
-
- /**
- * Returns the <code>Id</code> attribute of this <code>Reference</code> element
- *
- * @return Id the <code>Id</code> attribute of this <code>Reference</code> element
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
+ /**
+ * Returns {@link MessageDigestAlgorithm}
+ *
+ *
+ * @return {@link MessageDigestAlgorithm}
+ *
+ * @throws XMLSignatureException
+ */
+ public MessageDigestAlgorithm getMessageDigestAlgorithm() throws XMLSignatureException {
+ if (digestMethodElem == null) {
+ return null;
+ }
- /**
- * Sets the <code>type</code> atttibute of the Reference indicate whether an <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code> element
- *
- * @param Type the <code>type</code> attribute of the Reference
- */
- public void setType(String Type) {
+ String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
+
+ if (uri == null) {
+ return null;
+ }
- if (Type != null) {
- this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
- Type);
- }
- }
+ if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
+ Object exArgs[] = { uri };
- /**
- * Return the <code>type</code> atttibute of the Reference indicate whether an <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code> element
- *
- * @return the <code>type</code> attribute of the Reference
- */
- public String getType() {
- return this._constructionElement.getAttributeNS(null,
- Constants._ATT_TYPE);
- }
+ throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
+ }
+
+ return MessageDigestAlgorithm.getInstance(this.doc, uri);
+ }
- /**
- * Method isReferenceToObject
- *
- * This returns true if the <CODE>Type</CODE> attribute of the
- * <CODE>Refernce</CODE> element points to a <CODE>#Object</CODE> element
- *
- * @return true if the Reference type indicates that this Reference points to an <code>Object</code>
- */
- public boolean typeIsReferenceToObject() {
+ /**
+ * Sets the <code>URI</code> of this <code>Reference</code> element
+ *
+ * @param uri the <code>URI</code> of this <code>Reference</code> element
+ */
+ public void setURI(String uri) {
+ if (uri != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
+ }
+ }
- if (Reference.OBJECT_URI.equals(this.getType())) {
- return true;
- }
-
- return false;
- }
+ /**
+ * Returns the <code>URI</code> of this <code>Reference</code> element
+ *
+ * @return URI the <code>URI</code> of this <code>Reference</code> element
+ */
+ public String getURI() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
+ }
- /**
- * Method isReferenceToManifest
- *
- * This returns true if the <CODE>Type</CODE> attribute of the
- * <CODE>Refernce</CODE> element points to a <CODE>#Manifest</CODE> 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;
- }
+ /**
+ * Sets the <code>Id</code> attribute of this <code>Reference</code> element
+ *
+ * @param id the <code>Id</code> attribute of this <code>Reference</code> 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);
+ }
+ }
- return false;
- }
-
- /**
- * Method setDigestValueElement
- *
- * @param digestValue
- */
- private void setDigestValueElement(byte[] digestValue)
- {
- Node n=digestValueElement.getFirstChild();
- while (n!=null) {
- digestValueElement.removeChild(n);
- n = n.getNextSibling();
- }
+ /**
+ * Returns the <code>Id</code> attribute of this <code>Reference</code> element
+ *
+ * @return Id the <code>Id</code> attribute of this <code>Reference</code> element
+ */
+ public String getId() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ }
- String base64codedValue = Base64.encode(digestValue);
- Text t = this._doc.createTextNode(base64codedValue);
-
- digestValueElement.appendChild(t);
- }
+ /**
+ * Sets the <code>type</code> atttibute of the Reference indicate whether an
+ * <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code>
+ * element.
+ *
+ * @param type the <code>type</code> attribute of the Reference
+ */
+ public void setType(String type) {
+ if (type != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
+ }
+ }
- /**
- * 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 {
+ /**
+ * Return the <code>type</code> atttibute of the Reference indicate whether an
+ * <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code>
+ * element
+ *
+ * @return the <code>type</code> attribute of the Reference
+ */
+ public String getType() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+ }
- try {
- Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
- Constants._ATT_URI);
- String URI;
+ /**
+ * Method isReferenceToObject
+ *
+ * This returns true if the <CODE>Type</CODE> attribute of the
+ * <CODE>Reference</CODE> element points to a <CODE>#Object</CODE> element
+ *
+ * @return true if the Reference type indicates that this Reference points to an
+ * <code>Object</code>
+ */
+ public boolean typeIsReferenceToObject() {
+ if (Reference.OBJECT_URI.equals(this.getType())) {
+ return true;
+ }
- 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 };
+ return false;
+ }
- throw new ReferenceNotInitializedException(
- "signature.Verification.Reference.NoInput", exArgs);
- }
-
- resolver.addProperties(this._manifest._resolverProperties);
-
- XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
+ /**
+ * Method isReferenceToManifest
+ *
+ * This returns true if the <CODE>Type</CODE> attribute of the
+ * <CODE>Reference</CODE> element points to a <CODE>#Manifest</CODE> 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 input;
- } catch (ResourceResolverException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- } catch (XMLSecurityException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- }
- }
+ return false;
+ }
- /**
- * 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;
+ /**
+ * 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);
- private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os)
- throws XMLSignatureException {
-
- try {
- Transforms transforms = this.getTransforms();
- XMLSignatureInput output = null;
+ digestValueElement.appendChild(t);
+ }
- if (transforms != null) {
- output = transforms.performTransforms(input,os);
- this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
-
- //this._transformsOutput.setSourceURI(output.getSourceURI());
- } else {
- output = input;
- }
+ /**
+ * Method generateDigestValue
+ *
+ * @throws ReferenceNotInitializedException
+ * @throws XMLSignatureException
+ */
+ public void generateDigestValue()
+ throws XMLSignatureException, ReferenceNotInitializedException {
+ this.setDigestValueElement(this.calculateDigest(false));
+ }
- 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 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);
- /**
- * 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);
- }
+ ResourceResolver resolver =
+ ResourceResolver.getInstance(
+ uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation
+ );
+ resolver.addProperties(this.manifest.getResolverProperties());
- /**
- * 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();
+ return resolver.resolve(uriAttr, this.baseURI, secureValidation);
+ } catch (ResourceResolverException ex) {
+ throw new ReferenceNotInitializedException("empty", ex);
+ }
+ }
- if (transforms != null) {
- doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
- Transform t = transforms.item(i);
- String URI = t.getURI();
+ private XMLSignatureInput getContentsAfterTransformation(
+ XMLSignatureInput input, OutputStream os
+ ) throws XMLSignatureException {
+ try {
+ Transforms transforms = this.getTransforms();
+ XMLSignatureInput output = null;
- 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)) {
+ if (transforms != null) {
+ output = transforms.performTransforms(input, os);
+ this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
- break doTransforms;
- }
-
- output = t.performTransform(output, null);
+ //this.transformsOutput.setSourceURI(output.getSourceURI());
+ } else {
+ output = input;
}
+ return output;
+ } catch (ResourceResolverException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (CanonicalizationException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (InvalidCanonicalizerException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (TransformationException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (XMLSecurityException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
+
+ /**
+ * Returns the XMLSignatureInput which is the result of the Transforms.
+ * @return a XMLSignatureInput with all transformations applied.
+ * @throws XMLSignatureException
+ */
+ public XMLSignatureInput getContentsAfterTransformation()
+ throws XMLSignatureException {
+ XMLSignatureInput input = this.getContentsBeforeTransformation();
+ cacheDereferencedElement(input);
+
+ return this.getContentsAfterTransformation(input, null);
+ }
+
+ /**
+ * This method returns the XMLSignatureInput which represents the node set before
+ * some kind of canonicalization is applied for the first time.
+ * @return Gets a the node doing everything till the first c14n is needed
+ *
+ * @throws XMLSignatureException
+ */
+ public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
+ throws XMLSignatureException {
+ try {
+ XMLSignatureInput input = this.getContentsBeforeTransformation();
+ cacheDereferencedElement(input);
+ XMLSignatureInput output = input;
+ Transforms transforms = this.getTransforms();
+
+ if (transforms != null) {
+ doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+ Transform t = transforms.item(i);
+ String uri = t.getURI();
+
+ if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+ || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)
+ || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS)
+ || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)) {
+ break doTransforms;
+ }
+
+ output = t.performTransform(output, null);
+ }
+
output.setSourceURI(input.getSourceURI());
- }
- return output;
- } catch (IOException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (ResourceResolverException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (CanonicalizationException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (InvalidCanonicalizerException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (TransformationException ex) {
- throw new XMLSignatureException("empty", ex);
- } catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ }
+ 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<String> inclusiveNamespaces = new HashSet<String>();
-
- {
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;
+ Set<String> inclusiveNamespaces = new HashSet<String>();
+ if (c14nTransform != null
+ && (c14nTransform.length(
+ InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+ InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
- break doTransforms;
- }
- }
+ // there is one InclusiveNamespaces element
+ InclusiveNamespaces in =
+ new InclusiveNamespaces(
+ XMLUtils.selectNode(
+ c14nTransform.getElement().getFirstChild(),
+ InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+ InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+ 0
+ ), this.getBaseURI());
+
+ inclusiveNamespaces =
+ InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
}
- if (c14nTransform != null) {
-
- if (c14nTransform
- .length(InclusiveNamespaces
- .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
- ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
+ 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);
+ }
+ }
- // there is one InclusiveNamespaces element
- InclusiveNamespaces in = new InclusiveNamespaces(
- XMLUtils.selectNode(
- c14nTransform.getElement().getFirstChild(),
- InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
- InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
+ /**
+ * 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;
+ }
- inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
- in.getInclusiveNamespaces());
- }
- }
- }
+ /**
+ * Get the ReferenceData that corresponds to the cached representation of the dereferenced
+ * object before transformation.
+ */
+ public ReferenceData getReferenceData() {
+ return referenceData;
+ }
- 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 returns the {@link XMLSignatureInput} which is referenced by the
+ * <CODE>URI</CODE> 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);
- /**
- * 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;
- }
+ XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+ this.transformsOutput = output;
+ return output;
+ } catch (XMLSecurityException ex) {
+ throw new ReferenceNotInitializedException("empty", ex);
+ }
+ }
- /**
- * This method returns the {@link XMLSignatureInput} which is referenced by the
- * <CODE>URI</CODE> 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 {
+ /**
+ * Store the dereferenced Element(s) so that it/they can be retrieved later.
+ */
+ private void cacheDereferencedElement(XMLSignatureInput input) {
+ if (input.isNodeSet()) {
+ try {
+ final Set<Node> s = input.getNodeSet();
+ referenceData = new ReferenceNodeSetData() {
+ public Iterator<Node> iterator() {
+ return new Iterator<Node>() {
- try {
- XMLSignatureInput input = this.getContentsBeforeTransformation();
- XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+ Iterator<Node> sIterator = s.iterator();
- /* 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) {
+ public boolean hasNext() {
+ return sIterator.hasNext();
+ }
+
+ public Node next() {
+ return sIterator.next();
+ }
- this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
-
- //this._transformsOutput.setSourceURI(output.getSourceURI());
- }
- return output;
- } catch (XMLSecurityException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- }
- }
+ 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);
+ }
+ }
+ }
- /**
- * Method getTransforms
- *
- * @return The transforms that applied this reference.
- * @throws InvalidTransformException
- * @throws TransformationException
- * @throws XMLSecurityException
- * @throws XMLSignatureException
- */
- public Transforms getTransforms()
- throws XMLSignatureException, InvalidTransformException,
- TransformationException, XMLSecurityException {
-
- return transforms;
- }
+ /**
+ * Method getTransforms
+ *
+ * @return The transforms that applied this reference.
+ * @throws InvalidTransformException
+ * @throws TransformationException
+ * @throws XMLSecurityException
+ * @throws XMLSignatureException
+ */
+ public Transforms getTransforms()
+ throws XMLSignatureException, InvalidTransformException,
+ TransformationException, XMLSecurityException {
+ return transforms;
+ }
- /**
- * Method getReferencedBytes
- *
- * @return the bytes that will be used to generated digest.
- * @throws ReferenceNotInitializedException
- * @throws XMLSignatureException
- */
- public byte[] getReferencedBytes()
- throws ReferenceNotInitializedException, XMLSignatureException {
- try {
- XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);
-
- byte[] signedBytes = output.getBytes();
-
- return signedBytes;
- } catch (IOException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- } catch (CanonicalizationException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- }
-
- }
+ /**
+ * Method 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 {
-
- MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
+ mda.reset();
+ DigesterOutputStream diOs = new DigesterOutputStream(mda);
+ os = new UnsyncBufferedOutputStream(diOs);
+ XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);
+ // if signing and c14n11 property == true explicitly add
+ // C14N11 transform if needed
+ if (Reference.useC14N11 && !validating && !output.isOutputStreamSet()
+ && !output.isOctetStream()) {
+ if (transforms == null) {
+ transforms = new Transforms(this.doc);
+ transforms.setSecureValidation(secureValidation);
+ this.constructionElement.insertBefore(transforms.getElement(), digestMethodElem);
+ }
+ transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
+ output.updateOutputStream(os, true);
+ } else {
+ output.updateOutputStream(os);
+ }
+ os.flush();
- 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);
+ if (output.getOctetStreamReal() != null) {
+ output.getOctetStreamReal().close();
+ }
+
+ //this.getReferencedBytes(diOs);
+ //mda.update(data);
- return diOs.getDigestValue();
- } catch (XMLSecurityException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- } catch (IOException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
- }
- }
+ 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 {
-
- byte[] elemDig = this.getDigestValue();
- byte[] calcDig = this.calculateDigest(true);
- boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
+ /**
+ * Tests reference validation is success or false
+ *
+ * @return true if reference validation is success, otherwise false
+ * @throws ReferenceNotInitializedException
+ * @throws XMLSecurityException
+ */
+ public boolean verify()
+ throws ReferenceNotInitializedException, XMLSecurityException {
+ byte[] elemDig = this.getDigestValue();
+ byte[] calcDig = this.calculateDigest(true);
+ boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
- if (!equal) {
- log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
- log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
- log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
- } else {
- log.log(java.util.logging.Level.INFO, "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 {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,28 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
-
-
/**
* Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
* because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
@@ -32,58 +30,56 @@
*/
public class ReferenceNotInitializedException extends XMLSignatureException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ /**
+ *
+ */
+ 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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,34 +2,34 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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 <code><ds:SignatureProperties></code> elements
* This Element holds {@link SignatureProperty} that contian additional information items
@@ -37,120 +37,112 @@
* for example, data-time stamp, serial number of cryptographic hardware.
*
* @author Christian Geuer-Pollmann
- *
*/
public class SignatureProperties extends SignatureElementProxy {
- /**
- * Constructor SignatureProperties
- *
- * @param doc
- */
- public SignatureProperties(Document doc) {
-
- super(doc);
+ /**
+ * Constructor SignatureProperties
+ *
+ * @param doc
+ */
+ public SignatureProperties(Document doc) {
+ super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Constructs {@link SignatureProperties} from {@link Element}
- * @param element <code>SignatureProperties</code> 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);
+ /**
+ * Constructs {@link SignatureProperties} from {@link Element}
+ * @param element <code>SignatureProperties</code> element
+ * @param BaseURI the URI of the resource where the XML instance was stored
+ * @throws XMLSecurityException
+ */
+ public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
+ super(element, BaseURI);
- Attr attr = element.getAttributeNodeNS(null, "Id");
- if (attr != null) {
- element.setIdAttributeNode(attr, true);
- }
+ Attr attr = element.getAttributeNodeNS(null, "Id");
+ if (attr != null) {
+ element.setIdAttributeNode(attr, true);
+ }
- int length = getLength();
- for (int i = 0; i < length; i++) {
- Element propertyElem =
- XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
- Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
- if (propertyAttr != null) {
- propertyElem.setIdAttributeNode(propertyAttr, true);
- }
- }
- }
+ int length = getLength();
+ for (int i = 0; i < length; i++) {
+ Element propertyElem =
+ XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+ Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
+ if (propertyAttr != null) {
+ propertyElem.setIdAttributeNode(propertyAttr, true);
+ }
+ }
+ }
- /**
- * Return the nonnegative number of added SignatureProperty elements.
- *
- * @return the number of SignatureProperty elements
- */
- public int getLength() {
+ /**
+ * 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);
- Element[] propertyElems =
- XMLUtils.selectDsNodes(this._constructionElement,
- Constants._TAG_SIGNATUREPROPERTY
- );
-
- return propertyElems.length;
- }
+ return propertyElems.length;
+ }
- /**
- * Return the <it>i</it><sup>th</sup> SignatureProperty. Valid <code>i</code>
- * values are 0 to <code>{link@ getSize}-1</code>.
- *
- * @param i Index of the requested {@link SignatureProperty}
- * @return the <it>i</it><sup>th</sup> SignatureProperty
- * @throws XMLSignatureException
- */
- public SignatureProperty item(int i) throws XMLSignatureException {
- try {
- Element propertyElem =
- XMLUtils.selectDsNode(this._constructionElement,
- Constants._TAG_SIGNATUREPROPERTY,
- i );
+ /**
+ * Return the <it>i</it><sup>th</sup> SignatureProperty. Valid <code>i</code>
+ * values are 0 to <code>{link@ getSize}-1</code>.
+ *
+ * @param i Index of the requested {@link SignatureProperty}
+ * @return the <it>i</it><sup>th</sup> SignatureProperty
+ * @throws XMLSignatureException
+ */
+ public SignatureProperty item(int i) throws XMLSignatureException {
+ try {
+ Element propertyElem =
+ XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
- if (propertyElem == null) {
- return null;
- }
- return new SignatureProperty(propertyElem, this._baseURI);
- } catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ if (propertyElem == null) {
+ return null;
+ }
+ return new SignatureProperty(propertyElem, this.baseURI);
+ } catch (XMLSecurityException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- /**
- * Sets the <code>Id</code> attribute
- *
- * @param Id the <code>Id</code> attribute
- */
- public void setId(String Id) {
-
- if (Id != null) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
+ /**
+ * Sets the <code>Id</code> attribute
+ *
+ * @param Id the <code>Id</code> attribute
+ */
+ public void setId(String Id) {
+ if (Id != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+ this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ }
+ }
- /**
- * Returns the <code>Id</code> attribute
- *
- * @return the <code>Id</code> attribute
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
+ /**
+ * Returns the <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> 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);
- }
+ /**
+ * 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -37,96 +38,96 @@
*/
public class SignatureProperty extends SignatureElementProxy {
- /**
- * Constructs{@link SignatureProperty} using specified <code>Target</code> attribute
- *
- * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
- * @param Target the <code>Target</code> attribute references the <code>Signature</code> element to which the property applies SignatureProperty
- */
- public SignatureProperty(Document doc, String Target) {
- this(doc, Target, null);
- }
-
- /**
- * Constructs {@link SignatureProperty} using sepcified <code>Target</code> attribute and <code>Id</code> attribute
- *
- * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
- * @param Target the <code>Target</code> attribute references the <code>Signature</code> element to which the property applies
- * @param Id the <code>Id</code> will be specified by {@link Reference#getURI} in validation
- */
- public SignatureProperty(Document doc, String Target, String Id) {
-
- super(doc);
+ /**
+ * Constructs{@link SignatureProperty} using specified <code>target</code> attribute
+ *
+ * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+ * @param target the <code>target</code> attribute references the <code>Signature</code>
+ * element to which the property applies SignatureProperty
+ */
+ public SignatureProperty(Document doc, String target) {
+ this(doc, target, null);
+ }
- this.setTarget(Target);
- this.setId(Id);
- }
+ /**
+ * Constructs {@link SignatureProperty} using sepcified <code>target</code> attribute and
+ * <code>id</code> attribute
+ *
+ * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
+ * @param target the <code>target</code> attribute references the <code>Signature</code>
+ * element to which the property applies
+ * @param id the <code>id</code> will be specified by {@link Reference#getURI} in validation
+ */
+ public SignatureProperty(Document doc, String target, String id) {
+ super(doc);
- /**
- * Constructs a {@link SignatureProperty} from an {@link Element}
- * @param element <code>SignatureProperty</code> 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);
- }
+ this.setTarget(target);
+ this.setId(id);
+ }
- /**
- * Sets the <code>Id</code> attribute
- *
- * @param Id the <code>Id</code> attribute
- */
- public void setId(String Id) {
+ /**
+ * Constructs a {@link SignatureProperty} from an {@link Element}
+ * @param element <code>SignatureProperty</code> 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);
+ }
- if (Id != null) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
+ /**
+ * Sets the <code>id</code> attribute
+ *
+ * @param id the <code>id</code> attribute
+ */
+ public void setId(String id) {
+ if (id != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+ this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ }
+ }
- /**
- * Returns the <code>Id</code> attribute
- *
- * @return the <code>Id</code> attribute
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
-
- /**
- * Sets the <code>Target</code> attribute
- *
- * @param Target the <code>Target</code> attribute
- */
- public void setTarget(String Target) {
+ /**
+ * Returns the <code>id</code> attribute
+ *
+ * @return the <code>id</code> attribute
+ */
+ public String getId() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ }
- if ((Target != null)) {
- this._constructionElement.setAttributeNS(null, Constants._ATT_TARGET, Target);
- }
- }
-
- /**
- * Returns the <code>Target</code> attribute
- *
- * @return the <code>Target</code> attribute
- */
- public String getTarget() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
- }
+ /**
+ * Sets the <code>target</code> attribute
+ *
+ * @param target the <code>target</code> attribute
+ */
+ public void setTarget(String target) {
+ if (target != null) {
+ this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
+ }
+ }
- /**
- * Method appendChild
- *
- * @param node
- * @return the node in this element.
- */
- public Node appendChild(Node node) {
- return this._constructionElement.appendChild(node);
- }
+ /**
+ * Returns the <code>target</code> attribute
+ *
+ * @return the <code>target</code> attribute
+ */
+ public String getTarget() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_SIGNATUREPROPERTY;
- }
+ /**
+ * 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.signature;
@@ -50,11 +52,11 @@
*/
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 @@
* 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 @@
* Canonicalization method
* @throws XMLSecurityException
*/
- public SignedInfo(Document doc, String signatureMethodURI,
- int hMACOutputLength, String canonicalizationMethodURI)
- throws XMLSecurityException {
-
+ public SignedInfo(
+ Document doc, String signatureMethodURI,
+ int hMACOutputLength, String canonicalizationMethodURI
+ ) throws XMLSecurityException {
super(doc);
- c14nMethod = XMLUtils.createElementInSignatureSpace(this._doc,
- Constants._TAG_CANONICALIZATIONMETHOD);
+ c14nMethod =
+ XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
- c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM,
- canonicalizationMethodURI);
- this._constructionElement.appendChild(c14nMethod);
- XMLUtils.addReturnToElement(this._constructionElement);
+ c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
+ this.constructionElement.appendChild(c14nMethod);
+ XMLUtils.addReturnToElement(this.constructionElement);
if (hMACOutputLength > 0) {
- this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
- signatureMethodURI, hMACOutputLength);
+ this.signatureAlgorithm =
+ new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
} else {
- this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
- signatureMethodURI);
+ this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
}
- signatureMethod = this._signatureAlgorithm.getElement();
- this._constructionElement.appendChild(signatureMethod);
- XMLUtils.addReturnToElement(this._constructionElement);
+ signatureMethod = this.signatureAlgorithm.getElement();
+ this.constructionElement.appendChild(signatureMethod);
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -133,22 +133,22 @@
* @param canonicalizationMethodElem
* @throws XMLSecurityException
*/
- public SignedInfo(Document doc, Element signatureMethodElem,
- Element canonicalizationMethodElem) throws XMLSecurityException {
-
+ public SignedInfo(
+ Document doc, Element signatureMethodElem, Element canonicalizationMethodElem
+ ) throws XMLSecurityException {
super(doc);
// Check this?
this.c14nMethod = canonicalizationMethodElem;
- this._constructionElement.appendChild(c14nMethod);
- XMLUtils.addReturnToElement(this._constructionElement);
+ this.constructionElement.appendChild(c14nMethod);
+ XMLUtils.addReturnToElement(this.constructionElement);
- this._signatureAlgorithm =
+ this.signatureAlgorithm =
new SignatureAlgorithm(signatureMethodElem, null);
- signatureMethod = this._signatureAlgorithm.getElement();
- this._constructionElement.appendChild(signatureMethod);
+ signatureMethod = this.signatureAlgorithm.getElement();
+ this.constructionElement.appendChild(signatureMethod);
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -157,48 +157,76 @@
* @param element <code>SignedInfo</code>
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
- * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">Question</A>
- * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">Answer</A>
+ * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
+ * Question</A>
+ * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
+ * Answer</A>
*/
- public SignedInfo(Element element, String baseURI)
- throws XMLSecurityException {
+ public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
+ this(element, baseURI, false);
+ }
+ /**
+ * Build a {@link SignedInfo} from an {@link Element}
+ *
+ * @param element <code>SignedInfo</code>
+ * @param baseURI the URI of the resource where the XML instance was stored
+ * @param secureValidation whether secure validation is enabled or not
+ * @throws XMLSecurityException
+ * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0033.html">
+ * Question</A>
+ * @see <A HREF="http://lists.w3.org/Archives/Public/w3c-ietf-xmldsig/2001OctDec/0054.html">
+ * Answer</A>
+ */
+ public SignedInfo(
+ Element element, String baseURI, boolean secureValidation
+ ) throws XMLSecurityException {
// 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 @@
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 <CODE>ds:Manifest</CODE>s, too
+ * @return true if verification was successful
+ * @throws MissingResourceFailureException
+ * @throws XMLSecurityException
+ */
+ public boolean verify(boolean followManifests)
+ throws MissingResourceFailureException, XMLSecurityException {
+ return super.verifyReferences(followManifests);
+ }
+
+ /**
+ * Returns getCanonicalizedOctetStream
+ *
+ * @return the canonicalization result octet stream of <code>SignedInfo</code> element
+ * @throws CanonicalizationException
+ * @throws InvalidCanonicalizerException
+ * @throws XMLSecurityException
+ */
+ public byte[] getCanonicalizedOctetStream()
+ throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+ if (this.c14nizedBytes == null) {
+ Canonicalizer c14nizer =
+ Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+
+ this.c14nizedBytes =
+ c14nizer.canonicalizeSubtree(this.constructionElement);
+ }
+
+ // make defensive copy
+ return this.c14nizedBytes.clone();
+ }
+
+ /**
+ * Output the C14n stream to the given OutputStream.
+ * @param os
+ * @throws CanonicalizationException
+ * @throws InvalidCanonicalizerException
+ * @throws XMLSecurityException
+ */
+ public void signInOctetStream(OutputStream os)
+ throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+ if (this.c14nizedBytes == null) {
+ Canonicalizer c14nizer =
+ Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+ c14nizer.setWriter(os);
+ String inclusiveNamespaces = this.getInclusiveNamespaces();
+
+ if (inclusiveNamespaces == null) {
+ c14nizer.canonicalizeSubtree(this.constructionElement);
+ } else {
+ c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
+ }
+ } else {
+ try {
+ os.write(this.c14nizedBytes);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
- /**
- * Tests core validation process
- *
- * @return true if verification was successful
- * @throws MissingResourceFailureException
- * @throws XMLSecurityException
- */
- public boolean verify()
- throws MissingResourceFailureException, XMLSecurityException {
- return super.verifyReferences(false);
- }
-
- /**
- * Tests core validation process
- *
- * @param followManifests defines whether the verification process has to verify referenced <CODE>ds:Manifest</CODE>s, too
- * @return true if verification was successful
- * @throws MissingResourceFailureException
- * @throws XMLSecurityException
- */
- public boolean verify(boolean followManifests)
- throws MissingResourceFailureException, XMLSecurityException {
- return super.verifyReferences(followManifests);
- }
+ /**
+ * Returns the Canonicalization method URI
+ *
+ * @return the Canonicalization method URI
+ */
+ public String getCanonicalizationMethodURI() {
+ return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ }
- /**
- * Returns getCanonicalizedOctetStream
- *
- * @return the canonicalization result octedt stream of <code>SignedInfo</code> element
- * @throws CanonicalizationException
- * @throws InvalidCanonicalizerException
- * @throws XMLSecurityException
- */
- public byte[] getCanonicalizedOctetStream()
- throws CanonicalizationException, InvalidCanonicalizerException,
- XMLSecurityException {
+ /**
+ * Returns the Signature method URI
+ *
+ * @return the Signature method URI
+ */
+ public String getSignatureMethodURI() {
+ Element signatureElement = this.getSignatureMethodElement();
- if ((this._c14nizedBytes == null)
- /*&& (this._state == ElementProxy.MODE_SIGN)*/) {
- Canonicalizer c14nizer =
- Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-
- this._c14nizedBytes =
- c14nizer.canonicalizeSubtree(this._constructionElement);
- }
+ if (signatureElement != null) {
+ return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ }
- // make defensive copy
- byte[] output = new byte[this._c14nizedBytes.length];
-
- System.arraycopy(this._c14nizedBytes, 0, output, 0, output.length);
-
- return output;
- }
+ return null;
+ }
- /**
- * 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();
+ /**
+ * Method getSignatureMethodElement
+ * @return returns the SignatureMethod Element
+ *
+ */
+ public Element getSignatureMethodElement() {
+ return signatureMethod;
+ }
- 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);
- }
+ /**
+ * 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());
}
- }
-
- /**
- * Returns the Canonicalization method URI
- *
- * @return the Canonicalization method URI
- */
- public String getCanonicalizationMethodURI() {
-
- return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
- }
-
- /**
- * Returns the Signature method URI
- *
- * @return the Signature method URI
- */
- public String getSignatureMethodURI() {
-
- Element signatureElement = this.getSignatureMethodElement();
-
- if (signatureElement != null) {
- return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
- }
-
- return null;
- }
+ protected SignatureAlgorithm getSignatureAlgorithm() {
+ return signatureAlgorithm;
+ }
- /**
- * Method getSignatureMethodElement
- * @return gets The SignatureMethod Node.
- *
- */
- public Element getSignatureMethodElement() {
- return signatureMethod;
- }
-
- /**
- * Creates a SecretKey for the appropriate Mac algorithm based on a
- * byte[] array password.
- *
- * @param secretKeyBytes
- * @return the secret key for the SignedInfo element.
- */
- public SecretKey createSecretKey(byte[] secretKeyBytes)
- {
+ /**
+ * Method getBaseLocalName
+ * @inheritDoc
+ *
+ */
+ public String getBaseLocalName() {
+ return Constants._TAG_SIGNEDINFO;
+ }
- return new SecretKeySpec(secretKeyBytes,
- this._signatureAlgorithm
- .getJCEAlgorithmString());
- }
+ 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());
- protected SignatureAlgorithm getSignatureAlgorithm() {
- return _signatureAlgorithm;
- }
- /**
- * Method getBaseLocalName
- * @inheritDoc
- *
- */
- public String getBaseLocalName() {
- return Constants._TAG_SIGNEDINFO;
- }
-
- public String getInclusiveNamespaces() {
-
-
-
- String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
- if(!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
- c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+ 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;
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
import java.io.IOException;
import java.io.OutputStream;
import java.security.Key;
@@ -42,7 +42,6 @@
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import com.sun.org.apache.xml.internal.security.utils.SignerOutputStream;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
@@ -56,7 +55,6 @@
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
-
/**
* Handles <code><ds:Signature></code> elements.
* This is the main class that deals with creating and verifying signatures.
@@ -64,7 +62,7 @@
* <p>There are 2 types of constructors for this class. The ones that take a
* document, baseURI and 1 or more Java Objects. This is mostly used for
* signing purposes.
- * The other constructor is the one that takes a DOM Element and a BaseURI.
+ * The other constructor is the one that takes a DOM Element and a baseURI.
* This is used mostly with for verifying, when you have a SignatureElement.
*
* There are a few different types of methods:
@@ -76,329 +74,391 @@
* ObjectContainer during signing.</li>
* <li>sign and checkSignatureValue methods are used to sign and validate the
* signature. </li></ul>
- *
- * @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;
+
+ /** ds:Signature.ds:KeyInfo */
+ private KeyInfo keyInfo;
- /** Signature - Required DSAwithSHA1 (DSS) */
- public static final String ALGO_ID_SIGNATURE_DSA = Constants.SignatureSpecNS + "dsa-sha1";
+ /**
+ * Checking the digests in References in a Signature are mandatory, but for
+ * References inside a Manifest it is application specific. This boolean is
+ * to indicate that the References inside Manifests should be validated.
+ */
+ private boolean followManifestsDuringValidation = false;
+
+ private Element signatureValueElement;
- /** 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";
+ private static final int MODE_SIGN = 0;
+ private static final int MODE_VERIFY = 1;
+ private int state = MODE_SIGN;
- /** 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";
+ /**
+ * This creates a new <CODE>ds:Signature</CODE> Element and adds an empty
+ * <CODE>ds:SignedInfo</CODE>.
+ * The <code>ds:SignedInfo</code> 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);
+ }
-
- //J+
-
- /** ds:Signature.ds:SignedInfo element */
- private SignedInfo _signedInfo = null;
-
- /** ds:Signature.ds:KeyInfo */
- private KeyInfo _keyInfo = null;
-
- /**
- * Checking the digests in References in a Signature are mandatory, but for
- * References inside a Manifest it is application specific. This boolean is
- * to indicate that the References inside Manifests should be validated.
- */
- private boolean _followManifestsDuringValidation = false;
-
-private Element signatureValueElement;
+ /**
+ * 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 creates a new <CODE>ds:Signature</CODE> Element and adds an empty
- * <CODE>ds:SignedInfo</CODE>.
- * The <code>ds:SignedInfo</code> is initialized with the specified Signature
- * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED
- * by the spec. This method's main use is for creating a new signature.
- *
- * @param doc Document in which the signature will be appended after creation.
- * @param BaseURI URI to be used as context for all relative URIs.
- * @param SignatureMethodURI signature algorithm to use.
- * @throws XMLSecurityException
- */
- public XMLSignature(Document doc, String BaseURI, String SignatureMethodURI)
- throws XMLSecurityException {
- this(doc, BaseURI, SignatureMethodURI, 0,
- Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
- }
+ /**
+ * Constructor XMLSignature
+ *
+ * @param doc
+ * @param baseURI
+ * @param signatureMethodURI the Signature method to be used.
+ * @param canonicalizationMethodURI the canonicalization algorithm to be
+ * used to c14nize the SignedInfo element.
+ * @throws XMLSecurityException
+ */
+ public XMLSignature(
+ Document doc,
+ String baseURI,
+ String signatureMethodURI,
+ String canonicalizationMethodURI
+ ) throws XMLSecurityException {
+ this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI);
+ }
- /**
- * Constructor XMLSignature
- *
- * @param doc
- * @param BaseURI
- * @param SignatureMethodURI the Signature method to be used.
- * @param HMACOutputLength
- * @throws XMLSecurityException
- */
- public XMLSignature(
- Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength)
- throws XMLSecurityException {
- this(doc, BaseURI, SignatureMethodURI, HMACOutputLength,
- Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
- }
+ /**
+ * Constructor XMLSignature
+ *
+ * @param doc
+ * @param baseURI
+ * @param signatureMethodURI
+ * @param hmacOutputLength
+ * @param canonicalizationMethodURI
+ * @throws XMLSecurityException
+ */
+ public XMLSignature(
+ Document doc,
+ String baseURI,
+ String signatureMethodURI,
+ int hmacOutputLength,
+ String canonicalizationMethodURI
+ ) throws XMLSecurityException {
+ super(doc);
- /**
- * 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);
- }
+ String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
+ if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
+ this.constructionElement.setAttributeNS(
+ Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
+ );
+ } else {
+ this.constructionElement.setAttributeNS(
+ Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
+ );
+ }
+ XMLUtils.addReturnToElement(this.constructionElement);
+
+ this.baseURI = baseURI;
+ this.signedInfo =
+ new SignedInfo(
+ this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI
+ );
+
+ this.constructionElement.appendChild(this.signedInfo.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
- /**
- * 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 {
+ // create an empty SignatureValue; this is filled by setSignatureValueElement
+ signatureValueElement =
+ XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
- super(doc);
-
- String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
- if (xmlnsDsPrefix == null) {
- this._constructionElement.setAttributeNS
- (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS);
- } else {
- this._constructionElement.setAttributeNS
- (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS);
- }
- XMLUtils.addReturnToElement(this._constructionElement);
+ this.constructionElement.appendChild(signatureValueElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- this._baseURI = BaseURI;
- this._signedInfo = new SignedInfo(this._doc, SignatureMethodURI,
- HMACOutputLength,
- CanonicalizationMethodURI);
-
- this._constructionElement.appendChild(this._signedInfo.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
-
- // create an empty SignatureValue; this is filled by setSignatureValueElement
- signatureValueElement =
- XMLUtils.createElementInSignatureSpace(this._doc,
- Constants._TAG_SIGNATUREVALUE);
+ /**
+ * 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);
- 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 {
+ String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
+ if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
+ this.constructionElement.setAttributeNS(
+ Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
+ );
+ } else {
+ this.constructionElement.setAttributeNS(
+ Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
+ );
+ }
+ XMLUtils.addReturnToElement(this.constructionElement);
+
+ this.baseURI = baseURI;
+ this.signedInfo =
+ new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem);
- super(doc);
+ this.constructionElement.appendChild(this.signedInfo.getElement());
+ XMLUtils.addReturnToElement(this.constructionElement);
- 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);
+ // create an empty SignatureValue; this is filled by setSignatureValueElement
+ signatureValueElement =
+ XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
+
+ this.constructionElement.appendChild(signatureValueElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- this._baseURI = BaseURI;
- this._signedInfo = new SignedInfo(this._doc, SignatureMethodElem, CanonicalizationMethodElem);
-
- this._constructionElement.appendChild(this._signedInfo.getElement());
- XMLUtils.addReturnToElement(this._constructionElement);
-
- // create an empty SignatureValue; this is filled by setSignatureValueElement
- signatureValueElement =
- XMLUtils.createElementInSignatureSpace(this._doc,
- Constants._TAG_SIGNATUREVALUE);
-
- this._constructionElement.appendChild(signatureValueElement);
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ /**
+ * This will parse the element and construct the Java Objects.
+ * That will allow a user to validate the signature.
+ *
+ * @param element ds:Signature element that contains the whole signature
+ * @param baseURI URI to be prepended to all relative URIs
+ * @throws XMLSecurityException
+ * @throws XMLSignatureException if the signature is badly formatted
+ */
+ public XMLSignature(Element element, String baseURI)
+ throws XMLSignatureException, XMLSecurityException {
+ this(element, baseURI, false);
+ }
- /**
- * This will parse the element and construct the Java Objects.
- * That will allow a user to validate the signature.
- *
- * @param element ds:Signature element that contains the whole signature
- * @param BaseURI URI to be prepended to all relative URIs
- * @throws XMLSecurityException
- * @throws XMLSignatureException if the signature is badly formatted
- */
- public XMLSignature(Element element, String BaseURI)
- throws XMLSignatureException, XMLSecurityException {
+ /**
+ * 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);
- super(element, BaseURI);
+ // check out SignedInfo child
+ Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());
- // check out SignedInfo child
- Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());// XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- //Constants._TAG_SIGNEDINFO,0);
-
- // check to see if it is there
- if (signedInfoElem == null) {
- Object exArgs[] = { Constants._TAG_SIGNEDINFO,
- Constants._TAG_SIGNATURE };
+ // check to see if it is there
+ if (signedInfoElem == null) {
+ Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE };
+ throw new XMLSignatureException("xml.WrongContent", exArgs);
+ }
- throw new XMLSignatureException("xml.WrongContent", exArgs);
- }
+ // create a SignedInfo object from that element
+ this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation);
+ // get signedInfoElem again in case it has changed
+ signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());
- // create a SignedInfo object from that element
- this._signedInfo = new SignedInfo(signedInfoElem, BaseURI);
-
- // check out SignatureValue child
- this.signatureValueElement =XMLUtils.getNextElement(signedInfoElem.getNextSibling()); //XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- // Constants._TAG_SIGNATUREVALUE,0);
+ // check out SignatureValue child
+ this.signatureValueElement =
+ XMLUtils.getNextElement(signedInfoElem.getNextSibling());
- // check to see if it exists
- if (signatureValueElement == null) {
- Object exArgs[] = { Constants._TAG_SIGNATUREVALUE,
- Constants._TAG_SIGNATURE };
+ // 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);
+ }
- throw new XMLSignatureException("xml.WrongContent", exArgs);
- }
- Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id");
- if (signatureValueAttr != null) {
- signatureValueElement.setIdAttributeNode(signatureValueAttr, true);
- }
-
- // <element ref="ds:KeyInfo" minOccurs="0"/>
- Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
- // Constants._TAG_KEYINFO,0);
+ // <element ref="ds:KeyInfo" minOccurs="0"/>
+ Element keyInfoElem =
+ XMLUtils.getNextElement(signatureValueElement.getNextSibling());
- // If it exists use it, but it's not mandatory
- if ((keyInfoElem != null) && (keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) &&
- keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) ) {
- this._keyInfo = new KeyInfo(keyInfoElem, BaseURI);
- }
+ // If it exists use it, but it's not mandatory
+ if (keyInfoElem != null
+ && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS)
+ && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) {
+ this.keyInfo = new KeyInfo(keyInfoElem, baseURI);
+ this.keyInfo.setSecureValidation(secureValidation);
+ }
- // <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
- Element objectElem =
- XMLUtils.getNextElement(signatureValueElement.getNextSibling());
- while (objectElem != null) {
- Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id");
- if (objectAttr != null) {
- objectElem.setIdAttributeNode(objectAttr, true);
- }
+ // <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
+ 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);
- }
- }
- }
+ 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());
- }
- }
+ objectElem = XMLUtils.getNextElement(objectElem.getNextSibling());
+ }
+
+ this.state = MODE_VERIFY;
+ }
- /**
- * Sets the <code>Id</code> attribute
- *
- * @param Id Id value to be used by the id attribute on the Signature Element
- */
- public void setId(String Id) {
+ /**
+ * Sets the <code>Id</code> 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);
+ }
+ }
- if (Id != null) {
- setLocalIdAttribute(Constants._ATT_ID, Id);
- }
- }
-
- /**
- * Returns the <code>Id</code> attribute
- *
- * @return the <code>Id</code> attribute
- */
- public String getId() {
- return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
- }
+ /**
+ * Returns the <code>Id</code> attribute
+ *
+ * @return the <code>Id</code> attribute
+ */
+ public String getId() {
+ return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ }
- /**
- * Returns the completely parsed <code>SignedInfo</code> object.
- *
- * @return the completely parsed <code>SignedInfo</code> object.
- */
- public SignedInfo getSignedInfo() {
- return this._signedInfo;
- }
+ /**
+ * Returns the completely parsed <code>SignedInfo</code> object.
+ *
+ * @return the completely parsed <code>SignedInfo</code> 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 void setSignatureValueElement(byte[] bytes) {
while (signatureValueElement.hasChildNodes()) {
- signatureValueElement.removeChild
- (signatureValueElement.getFirstChild());
+ signatureValueElement.removeChild(signatureValueElement.getFirstChild());
}
String base64codedValue = Base64.encode(bytes);
@@ -419,373 +478,393 @@
base64codedValue = "\n" + base64codedValue + "\n";
}
- Text t = this._doc.createTextNode(base64codedValue);
+ Text t = this.doc.createTextNode(base64codedValue);
signatureValueElement.appendChild(t);
}
- /**
- * Returns the KeyInfo child. If we are in signing mode and the KeyInfo
- * does not exist yet, it is created on demand and added to the Signature.
- * <br>
- * 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.
+ * <br>
+ * 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 <code>java.lang.Object</code> 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 <code>java.lang.Object</code> 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 <code>i<code>th <code>ds:Object</code> child of the signature
- * or null if no such <code>ds:Object</code> element exists.
- *
- * @param i
- * @return the <code>i<code>th <code>ds:Object</code> child of the signature or null if no such <code>ds:Object</code> element exists.
- */
- public ObjectContainer getObjectItem(int i) {
+ /**
+ * Returns the <code>i<code>th <code>ds:Object</code> child of the signature
+ * or null if no such <code>ds:Object</code> element exists.
+ *
+ * @param i
+ * @return the <code>i<code>th <code>ds:Object</code> child of the signature
+ * or null if no such <code>ds:Object</code> 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 <code>ds:Object</code> elements.
- *
- * @return the number of all <code>ds:Object</code> elements.
- */
- public int getObjectLength() {
- return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT);
- }
+ /**
+ * Returns the number of all <code>ds:Object</code> elements.
+ *
+ * @return the number of all <code>ds:Object</code> 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 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);
- }
- }
+ // set them on the SignatureValue element
+ this.setSignatureValueElement(sa.sign());
+ } catch (XMLSignatureException ex) {
+ throw ex;
+ } catch (CanonicalizationException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (InvalidCanonicalizerException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } catch (XMLSecurityException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- /**
- * Adds a {@link ResourceResolver} to enable the retrieval of resources.
- *
- * @param resolver
- */
- public void addResourceResolver(ResourceResolver resolver) {
- this.getSignedInfo().addResourceResolver(resolver);
- }
+ /**
+ * Adds a {@link 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 {
+ /**
+ * 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());
+ }
- // 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);
-
- }
+ 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 {
- bos.close();
- } catch (IOException e) {
- //Imposible
- }
+ // Get the canonicalized (normalized) SignedInfo
+ SignerOutputStream so = new SignerOutputStream(sa);
+ OutputStream bos = new UnsyncBufferedOutputStream(so);
- //retrieve the byte[] from the stored signature
- byte sigBytes[] = this.getSignatureValue();
+ si.signInOctetStream(bos);
+ bos.close();
+ // retrieve the byte[] from the stored signature
+ sigBytes = this.getSignatureValue();
+ } catch (IOException ex) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+ }
+ // Impossible...
+ } catch (XMLSecurityException ex) {
+ throw ex;
+ }
- //Have SignatureAlgorithm sign the input bytes and compare them to the
- //bytes that were stored in the signature.
- if (!sa.verify(sigBytes)) {
- log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
- return false;
- }
+ // have SignatureAlgorithm sign the input bytes and compare them to
+ // the bytes that were stored in the signature.
+ if (!sa.verify(sigBytes)) {
+ log.log(java.util.logging.Level.WARNING, "Signature verification failed.");
+ return false;
+ }
- return si.verify(this._followManifestsDuringValidation);
- } catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
- }
- }
+ return si.verify(this.followManifestsDuringValidation);
+ } catch (XMLSignatureException ex) {
+ throw ex;
+ } catch (XMLSecurityException ex) {
+ throw new XMLSignatureException("empty", ex);
+ }
+ }
- /**
- * Add a Reference with full parameters to this Signature
- *
- * @param referenceURI URI of the resource to be signed. Can be null in which
- * case the dereferencing is application specific. Can be "" in which it's
- * the parent node (or parent document?). There can only be one "" in each
- * signature.
- * @param trans Optional list of transformations to be done before digesting
- * @param digestURI Mandatory URI of the digesting algorithm to use.
- * @param ReferenceId Optional id attribute for this Reference
- * @param ReferenceType Optional mimetype for the URI
- * @throws XMLSignatureException
- */
- public void addDocument(
- String referenceURI, Transforms trans, String digestURI, String ReferenceId, String ReferenceType)
- throws XMLSignatureException {
- this._signedInfo.addDocument(this._baseURI, referenceURI, trans,
- digestURI, ReferenceId, ReferenceType);
- }
+ /**
+ * 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 {
+ /**
+ * Add an X509 Certificate to the KeyInfo. This will include the whole cert
+ * inside X509Data/X509Certificate tags.
+ *
+ * @param cert Certificate to be included. This should be the certificate of
+ * the key that was used to sign.
+ * @throws XMLSecurityException
+ */
+ public void addKeyInfo(X509Certificate cert) throws XMLSecurityException {
+ X509Data x509data = new X509Data(this.doc);
- X509Data x509data = new X509Data(this._doc);
-
- x509data.addCertificate(cert);
- this.getKeyInfo().add(x509data);
- }
+ x509data.addCertificate(cert);
+ this.getKeyInfo().add(x509data);
+ }
- /**
- * Add this public key to the KeyInfo. This will include the complete key in
- * the KeyInfo structure.
- *
- * @param pk
- */
- public void addKeyInfo(PublicKey pk) {
- this.getKeyInfo().add(pk);
- }
+ /**
+ * Add this public key to the KeyInfo. This will include the complete key in
+ * the KeyInfo structure.
+ *
+ * @param pk
+ */
+ public void addKeyInfo(PublicKey pk) {
+ this.getKeyInfo().add(pk);
+ }
+
+ /**
+ * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want
+ * to create a MAC, this method helps you to obtain the
+ * {@link javax.crypto.SecretKey} from octets.
+ *
+ * @param secretKeyBytes
+ * @return the secret key created.
+ * @see SignedInfo#createSecretKey(byte[])
+ */
+ public SecretKey createSecretKey(byte[] secretKeyBytes) {
+ return this.getSignedInfo().createSecretKey(secretKeyBytes);
+ }
- /**
- * 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 <a href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">
+ * Core validation section in the XML Signature Rec.</a>
+ */
+ public void setFollowNestedManifests(boolean followManifests) {
+ this.followManifestsDuringValidation = followManifests;
+ }
- /**
- * 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 <a href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core validation section in the XML Signature Rec.</a>
- */
- 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,29 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
-
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
/**
* All XML Signature related exceptions inherit herefrom.
*
@@ -33,57 +32,56 @@
*/
public class XMLSignatureException extends XMLSecurityException {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ /**
+ *
+ */
+ 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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.signature;
@@ -25,7 +27,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
@@ -53,17 +54,13 @@
* @author Christian Geuer-Pollmann
* $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set?
*/
-public class XMLSignatureInput implements Cloneable {
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger
- (XMLSignatureInput.class.getName());
-
+public class XMLSignatureInput {
/*
* The XMLSignature Input can be either:
* A byteArray like with/or without InputStream.
* Or a nodeSet like defined either:
* * as a collection of nodes
- * * or as subnode excluding or not commets and excluding or
+ * * or as subnode excluding or not comments and excluding or
* not other nodes.
*/
@@ -71,63 +68,55 @@
* 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<Node> _inputNodeSet = null;
+ private Set<Node> 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<NodeFilter> nodeFilters=new ArrayList<NodeFilter>();
-
- boolean needsToBeExpanded=false;
- OutputStream outputStream=null;
+ private List<NodeFilter> nodeFilters = new ArrayList<NodeFilter>();
- /**
- * Check if the structured is needed to be circumbented.
- * @return true if so.
- */
- public boolean isNeedsToBeExpanded() {
- return needsToBeExpanded;
- }
+ private boolean needsToBeExpanded = false;
+ private OutputStream outputStream = null;
- /**
- * 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 @@
* @param inputOctets an octet array which including XML document or node
*/
public XMLSignatureInput(byte[] inputOctets) {
-
- // NO defensive copy
-
- //this._inputOctetStreamProxy = new ByteArrayInputStream(inputOctets);
- this.bytes=inputOctets;
+ // NO defensive copy
+ this.bytes = inputOctets;
}
/**
@@ -152,39 +138,7 @@
* @param inputOctetStream
*/
public XMLSignatureInput(InputStream inputOctetStream) {
- this._inputOctetStreamProxy=inputOctetStream;
-
- //this(JavaUtils.getBytesFromStream(inputOctetStream));
- }
-
- /**
- * Construct a XMLSignatureInput from a String.
- * <p>
- * 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.
- * <p>
- * 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 <code>encoding</code>
- * @param encoding the encoding of <code>inputStr</code>
- * @throws UnsupportedEncodingException
- */
- @Deprecated
- public XMLSignatureInput(String inputStr, String encoding)
- throws UnsupportedEncodingException {
- this(inputStr.getBytes(encoding));
+ this.inputOctetStreamProxy = inputOctetStream;
}
/**
@@ -193,19 +147,33 @@
*
* @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<Node> 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,12 +186,20 @@
* @throws ParserConfigurationException
* @throws CanonicalizationException
*/
- public Set<Node> getNodeSet() throws CanonicalizationException,
- ParserConfigurationException, IOException, SAXException {
+ public Set<Node> getNodeSet() throws CanonicalizationException, ParserConfigurationException,
+ IOException, SAXException {
return getNodeSet(false);
}
/**
+ * Get the Input NodeSet.
+ * @return the Input NodeSet.
+ */
+ public Set<Node> getInputNodeSet() {
+ return inputNodeSet;
+ }
+
+ /**
* Returns the node set from input which was specified as the parameter of
* {@link XMLSignatureInput} constructor
* @param circumvent
@@ -234,51 +210,54 @@
* @throws ParserConfigurationException
* @throws CanonicalizationException
*/
- public Set<Node> getNodeSet(boolean circumvent)
- throws ParserConfigurationException, IOException, SAXException,
- CanonicalizationException {
- if (this._inputNodeSet!=null) {
- return this._inputNodeSet;
+ public Set<Node> 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<Node>();
- XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments);
-
- return this._inputNodeSet;
- } else if (this.isOctetStream()) {
+ inputNodeSet = new LinkedHashSet<Node>();
+ XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments);
+ return inputNodeSet;
+ } else if (isOctetStream()) {
convertToNodes();
- LinkedHashSet<Node> result = new LinkedHashSet<Node>();
- XMLUtils.getSet(_subNode, result,null,false);
- //this._inputNodeSet=result;
+ Set<Node> result = new LinkedHashSet<Node>();
+ 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 @@
* @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 @@
* @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 @@
* @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 @@
* @return true is the object has been set up with an octet stream
*/
public boolean isByteArray() {
- return ( (bytes!=null)
- && ((this._inputNodeSet == null) && _subNode ==null));
+ return (bytes != null && (this.inputNodeSet == null && subNode == null));
}
/**
@@ -367,25 +336,25 @@
* @return true if the object has been set up correctly
*/
public boolean isInitialized() {
- return (this.isOctetStream() || this.isNodeSet());
+ return isOctetStream() || isNodeSet();
}
/**
- * Returns MIMEType
+ * Returns mimeType
*
- * @return MIMEType
+ * @return mimeType
*/
public String getMIMEType() {
- return this._MIMEType;
+ return mimeType;
}
/**
- * Sets MIMEType
+ * Sets mimeType
*
- * @param MIMEType
+ * @param mimeType
*/
- public void setMIMEType(String MIMEType) {
- this._MIMEType = MIMEType;
+ public void setMIMEType(String mimeType) {
+ this.mimeType = mimeType;
}
/**
@@ -394,16 +363,16 @@
* @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 @@
* @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 @@
* @return The HTML representation for this XMLSignature
*/
public String getHTMLRepresentation() throws XMLSignatureException {
-
XMLSignatureInputDebugger db = new XMLSignatureInputDebugger(this);
-
return db.getHTMLRepresentation();
}
@@ -451,11 +418,9 @@
* @return The HTML representation for this XMLSignature
*/
public String getHTMLRepresentation(Set<String> inclusiveNamespaces)
- throws XMLSignatureException {
-
- XMLSignatureInputDebugger db = new XMLSignatureInputDebugger( this,
- inclusiveNamespaces);
-
+ throws XMLSignatureException {
+ XMLSignatureInputDebugger db =
+ new XMLSignatureInputDebugger(this, inclusiveNamespaces);
return db.getHTMLRepresentation();
}
@@ -480,7 +445,7 @@
* @return The excludeNode set.
*/
public Node getSubNode() {
- return _subNode;
+ return subNode;
}
/**
@@ -503,19 +468,18 @@
* @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 @@
}
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 @@
* @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 (inputOctetStreamProxy == null) {
+ return null;
}
- if (bytes!=null) {
- _inputOctetStreamProxy=new ByteArrayInputStream(bytes);
- return _inputOctetStreamProxy;
+ try {
+ bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy);
+ } finally {
+ inputOctetStreamProxy.close();
}
- 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;
+ return bytes;
}
/**
@@ -578,7 +532,9 @@
try {
convertToNodes();
} catch (Exception e) {
- throw new XMLSecurityRuntimeException("signature.XMLSignatureInput.nodesetReference",e);
+ throw new XMLSecurityRuntimeException(
+ "signature.XMLSignatureInput.nodesetReference", e
+ );
}
}
nodeFilters.add(filter);
@@ -588,7 +544,6 @@
* @return the node filters
*/
public List<NodeFilter> getNodeFilters() {
- // TODO Auto-generated method stub
return nodeFilters;
}
@@ -596,39 +551,42 @@
* @param b
*/
public void setNodeSet(boolean b) {
- isNodeSet=b;
+ isNodeSet = b;
}
void convertToNodes() throws CanonicalizationException,
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("<container>".getBytes());
+ baos.write("<container>".getBytes("UTF-8"));
baos.write(this.getBytes());
- baos.write("</container>".getBytes());
+ baos.write("</container>".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;
}
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.signature;
@@ -38,681 +40,591 @@
/**
* Class XMLSignatureInputDebugger
- *
- * @author $Author: mullan $
- * @version $Revision: 1.3 $
*/
public class XMLSignatureInputDebugger {
-
+ /** Field _xmlSignatureInput */
+ private Set<Node> xpathNodeSet;
- /** Field _xmlSignatureInput */
- private Set<Node> _xpathNodeSet;
+ private Set<String> inclusiveNamespaces;
- private Set<String> _inclusiveNamespaces;
+ /** Field doc */
+ private Document doc = null;
- /** Field _doc */
- private Document _doc = null;
-
- /** Field _writer */
- private Writer _writer = null;
+ /** Field writer */
+ private Writer writer = null;
- // J-
- // public static final String HTMLPrefix = "<!DOCTYPE HTML PUBLIC
- // \"-//W3C//DTD HTML 4.01 Transitional//EN\"><html><head><style
- // type=\"text/css\"><!-- .INCLUDED { color: #000000; background-color:
- // #FFFFFF; font-weight: bold; } .EXCLUDED { color: #666666;
- // background-color: #999999; } .INCLUDEDINCLUSIVENAMESPACE { color:
- // #0000FF; background-color: #FFFFFF; font-weight: bold; font-style:
- // italic; } .EXCLUDEDINCLUSIVENAMESPACE { color: #0000FF; background-color:
- // #999999; font-style: italic; } --> </style> </head><body
- // bgcolor=\"#999999\"><pre>";
- /** The HTML Prefix* */
- static final String HTMLPrefix = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
- + "<html>\n"
- + "<head>\n"
- + "<title>Caninical XML node set</title>\n"
- + "<style type=\"text/css\">\n"
- + "<!-- \n"
- + ".INCLUDED { \n"
- + " color: #000000; \n"
- + " background-color: \n"
- + " #FFFFFF; \n"
- + " font-weight: bold; } \n"
- + ".EXCLUDED { \n"
- + " color: #666666; \n"
- + " background-color: \n"
- + " #999999; } \n"
- + ".INCLUDEDINCLUSIVENAMESPACE { \n"
- + " color: #0000FF; \n"
- + " background-color: #FFFFFF; \n"
- + " font-weight: bold; \n"
- + " font-style: italic; } \n"
- + ".EXCLUDEDINCLUSIVENAMESPACE { \n"
- + " color: #0000FF; \n"
- + " background-color: #999999; \n"
- + " font-style: italic; } \n"
- + "--> \n"
- + "</style> \n"
- + "</head>\n"
- + "<body bgcolor=\"#999999\">\n"
- + "<h1>Explanation of the output</h1>\n"
- + "<p>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.</p>\n"
- + "<ul>\n"
- + "<li class=\"INCLUDED\">A node which is in the node set is labeled using the INCLUDED style.</li>\n"
- + "<li class=\"EXCLUDED\">A node which is <em>NOT</em> in the node set is labeled EXCLUDED style.</li>\n"
- + "<li class=\"INCLUDEDINCLUSIVENAMESPACE\">A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
- + "<li class=\"EXCLUDEDINCLUSIVENAMESPACE\">A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
- + "</ul>\n" + "<h1>Output</h1>\n" + "<pre>\n";
+ /** The HTML Prefix* */
+ static final String HTMLPrefix =
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
+ + "<html>\n"
+ + "<head>\n"
+ + "<title>Caninical XML node set</title>\n"
+ + "<style type=\"text/css\">\n"
+ + "<!-- \n"
+ + ".INCLUDED { \n"
+ + " color: #000000; \n"
+ + " background-color: \n"
+ + " #FFFFFF; \n"
+ + " font-weight: bold; } \n"
+ + ".EXCLUDED { \n"
+ + " color: #666666; \n"
+ + " background-color: \n"
+ + " #999999; } \n"
+ + ".INCLUDEDINCLUSIVENAMESPACE { \n"
+ + " color: #0000FF; \n"
+ + " background-color: #FFFFFF; \n"
+ + " font-weight: bold; \n"
+ + " font-style: italic; } \n"
+ + ".EXCLUDEDINCLUSIVENAMESPACE { \n"
+ + " color: #0000FF; \n"
+ + " background-color: #999999; \n"
+ + " font-style: italic; } \n"
+ + "--> \n"
+ + "</style> \n"
+ + "</head>\n"
+ + "<body bgcolor=\"#999999\">\n"
+ + "<h1>Explanation of the output</h1>\n"
+ + "<p>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.</p>\n"
+ + "<ul>\n"
+ + "<li class=\"INCLUDED\">A node which is in the node set is labeled using the INCLUDED style.</li>\n"
+ + "<li class=\"EXCLUDED\">A node which is <em>NOT</em> in the node set is labeled EXCLUDED style.</li>\n"
+ + "<li class=\"INCLUDEDINCLUSIVENAMESPACE\">A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
+ + "<li class=\"EXCLUDEDINCLUSIVENAMESPACE\">A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.</li>\n"
+ + "</ul>\n" + "<h1>Output</h1>\n" + "<pre>\n";
- /** HTML Suffix * */
- static final String HTMLSuffix = "</pre></body></html>";
-
- static final String HTMLExcludePrefix = "<span class=\"EXCLUDED\">";
-
- static final String HTMLExcludeSuffix = "</span>";
-
- static final String HTMLIncludePrefix = "<span class=\"INCLUDED\">";
-
- static final String HTMLIncludeSuffix = "</span>";
-
- static final String HTMLIncludedInclusiveNamespacePrefix = "<span class=\"INCLUDEDINCLUSIVENAMESPACE\">";
-
- static final String HTMLIncludedInclusiveNamespaceSuffix = "</span>";
-
- static final String HTMLExcludedInclusiveNamespacePrefix = "<span class=\"EXCLUDEDINCLUSIVENAMESPACE\">";
+ /** HTML Suffix * */
+ static final String HTMLSuffix = "</pre></body></html>";
- static final String HTMLExcludedInclusiveNamespaceSuffix = "</span>";
+ static final String HTMLExcludePrefix = "<span class=\"EXCLUDED\">";
- private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
-
- private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
+ static final String HTMLIncludePrefix = "<span class=\"INCLUDED\">";
- private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
-
- static final AttrCompare ATTR_COMPARE = new AttrCompare();
+ static final String HTMLIncludeOrExcludeSuffix = "</span>";
- // J+
- private XMLSignatureInputDebugger() {
- // do nothing
- }
+ static final String HTMLIncludedInclusiveNamespacePrefix = "<span class=\"INCLUDEDINCLUSIVENAMESPACE\">";
- /**
- * Constructor XMLSignatureInputDebugger
- *
- * @param xmlSignatureInput the signatur to pretty print
- */
- public XMLSignatureInputDebugger(
- XMLSignatureInput xmlSignatureInput) {
+ static final String HTMLExcludedInclusiveNamespacePrefix = "<span class=\"EXCLUDEDINCLUSIVENAMESPACE\">";
+
+ private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1;
- if (!xmlSignatureInput.isNodeSet()) {
- this._xpathNodeSet = null;
- } else {
- this._xpathNodeSet = xmlSignatureInput._inputNodeSet;
- }
- }
+ private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0;
- /**
- * Constructor XMLSignatureInputDebugger
- *
- * @param xmlSignatureInput the signatur to pretty print
- * @param inclusiveNamespace
- */
- public XMLSignatureInputDebugger(
- XMLSignatureInput xmlSignatureInput, Set<String> inclusiveNamespace) {
+ private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1;
+
+ static final AttrCompare ATTR_COMPARE = new AttrCompare();
- this(xmlSignatureInput);
-
- this._inclusiveNamespaces = inclusiveNamespace;
+ /**
+ * Constructor XMLSignatureInputDebugger
+ *
+ * @param xmlSignatureInput the signature to pretty print
+ */
+ public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) {
+ if (!xmlSignatureInput.isNodeSet()) {
+ this.xpathNodeSet = null;
+ } else {
+ this.xpathNodeSet = xmlSignatureInput.getInputNodeSet();
}
-
- /**
- * Method getHTMLRepresentation
- *
- * @return The HTML Representation.
- * @throws XMLSignatureException
- */
- public String getHTMLRepresentation() throws XMLSignatureException {
-
- if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) {
- return HTMLPrefix + "<blink>no node set, sorry</blink>"
- + 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();
+ /**
+ * Constructor XMLSignatureInputDebugger
+ *
+ * @param xmlSignatureInput the signatur to pretty print
+ * @param inclusiveNamespace
+ */
+ public XMLSignatureInputDebugger(
+ XMLSignatureInput xmlSignatureInput,
+ Set<String> inclusiveNamespace
+ ) {
+ this(xmlSignatureInput);
+ this.inclusiveNamespaces = inclusiveNamespace;
+ }
- 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 getHTMLRepresentation
+ *
+ * @return The HTML Representation.
+ * @throws XMLSignatureException
+ */
+ public String getHTMLRepresentation() throws XMLSignatureException {
+ if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) {
+ return HTMLPrefix + "<blink>no node set, sorry</blink>" + HTMLSuffix;
}
- /**
- * Method canonicalizeXPathNodeSet
- *
- * @param currentNode
- * @throws XMLSignatureException
- * @throws IOException
- */
- private void canonicalizeXPathNodeSet(Node currentNode)
- throws XMLSignatureException, IOException {
+ // get only a single node as anchor to fetch the owner document
+ Node n = this.xpathNodeSet.iterator().next();
- int currentNodeType = currentNode.getNodeType();
- switch (currentNodeType) {
-
- case Node.DOCUMENT_TYPE_NODE:
- default:
- break;
+ this.doc = XMLUtils.getOwnerDocument(n);
- 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);
- }
+ try {
+ this.writer = new StringWriter();
- 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);
+ this.canonicalizeXPathNodeSet(this.doc);
+ this.writer.close();
- 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);
+ return this.writer.toString();
+ } catch (IOException ex) {
+ throw new XMLSignatureException("empty", ex);
+ } finally {
+ this.xpathNodeSet = null;
+ this.doc = null;
+ this.writer = null;
+ }
+ }
- 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;
+ /**
+ * Method canonicalizeXPathNodeSet
+ *
+ * @param currentNode
+ * @throws XMLSignatureException
+ * @throws IOException
+ */
+ private void canonicalizeXPathNodeSet(Node currentNode)
+ throws XMLSignatureException, IOException {
- case Node.TEXT_NODE:
- case Node.CDATA_SECTION_NODE:
- if (this._xpathNodeSet.contains(currentNode)) {
- this._writer.write(HTMLIncludePrefix);
- } else {
- this._writer.write(HTMLExcludePrefix);
- }
+ int currentNodeType = currentNode.getNodeType();
+ switch (currentNodeType) {
- 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;
+ 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);
- if (this._xpathNodeSet.contains(currentNode)) {
- this._writer.write(HTMLIncludePrefix);
- } else {
- this._writer.write(HTMLExcludePrefix);
- }
-
- this._writer.write("<");
- this._writer.write(currentElement.getTagName());
+ for (Node currentChild = currentNode.getFirstChild();
+ currentChild != null; currentChild = currentChild.getNextSibling()) {
+ this.canonicalizeXPathNodeSet(currentChild);
+ }
- if (this._xpathNodeSet.contains(currentNode)) {
- this._writer.write(HTMLIncludeSuffix);
- } else {
- this._writer.write(HTMLExcludeSuffix);
- }
+ this.writer.write(HTMLSuffix);
+ break;
- // 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;
+ case Node.COMMENT_NODE:
+ if (this.xpathNodeSet.contains(currentNode)) {
+ this.writer.write(HTMLIncludePrefix);
+ } else {
+ this.writer.write(HTMLExcludePrefix);
+ }
- 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());
+ int position = getPositionRelativeToDocumentElement(currentNode);
- if (included) {
- if (inclusive) {
+ if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
+ this.writer.write("\n");
+ }
- // included and inclusive
- this._writer
- .write(HTMLIncludedInclusiveNamespacePrefix);
- } else {
+ this.outputCommentToWriter((Comment) currentNode);
- // included and not inclusive
- this._writer.write(HTMLIncludePrefix);
- }
- } else {
- if (inclusive) {
-
- // excluded and inclusive
- this._writer
- .write(HTMLExcludedInclusiveNamespacePrefix);
- } else {
+ if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
+ this.writer.write("\n");
+ }
- // 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 {
+ this.writer.write(HTMLIncludeOrExcludeSuffix);
+ break;
- // included and not inclusive
- this._writer.write(HTMLIncludeSuffix);
- }
- } else {
- if (inclusive) {
+ case Node.PROCESSING_INSTRUCTION_NODE:
+ if (this.xpathNodeSet.contains(currentNode)) {
+ this.writer.write(HTMLIncludePrefix);
+ } else {
+ this.writer.write(HTMLExcludePrefix);
+ }
- // excluded and inclusive
- this._writer
- .write(HTMLExcludedInclusiveNamespaceSuffix);
- } else {
-
- // excluded and not inclusive
- this._writer.write(HTMLExcludeSuffix);
- }
- }
- }
+ position = getPositionRelativeToDocumentElement(currentNode);
- if (this._xpathNodeSet.contains(currentNode)) {
- this._writer.write(HTMLIncludePrefix);
- } else {
- this._writer.write(HTMLExcludePrefix);
- }
+ if (position == NODE_AFTER_DOCUMENT_ELEMENT) {
+ this.writer.write("\n");
+ }
- this._writer.write(">");
+ this.outputPItoWriter((ProcessingInstruction) currentNode);
- if (this._xpathNodeSet.contains(currentNode)) {
- this._writer.write(HTMLIncludeSuffix);
- } else {
- this._writer.write(HTMLExcludeSuffix);
- }
+ if (position == NODE_BEFORE_DOCUMENT_ELEMENT) {
+ this.writer.write("\n");
+ }
- // 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(HTMLIncludeOrExcludeSuffix);
+ break;
- 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;
- }
- }
+ case Node.TEXT_NODE:
+ case Node.CDATA_SECTION_NODE:
+ if (this.xpathNodeSet.contains(currentNode)) {
+ this.writer.write(HTMLIncludePrefix);
+ } else {
+ this.writer.write(HTMLExcludePrefix);
+ }
- /**
- * 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;
- }
+ outputTextToWriter(currentNode.getNodeValue());
- 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;
- }
+ 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());
+ }
- /**
- * Normalizes an {@link Attr}ibute value
- *
- * The string value of the node is modified by replacing
- * <UL>
- * <LI>all ampersands (&) with <CODE>&amp;</CODE></LI>
- * <LI>all open angle brackets (<) with <CODE>&lt;</CODE></LI>
- * <LI>all quotation mark characters with <CODE>&quot;</CODE></LI>
- * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD,
- * with character references. The character references are written in
- * uppercase hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE>
- * is represented by the character reference <CODE>&#xD;</CODE>)</LI>
- * </UL>
- *
- * @param name
- * @param value
- * @throws IOException
- */
- private void outputAttrToWriter(String name, String value)
- throws IOException {
+ this.writer.write(HTMLIncludeOrExcludeSuffix);
+ break;
+
+ case Node.ELEMENT_NODE:
+ Element currentElement = (Element) currentNode;
- 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) {
+ if (this.xpathNodeSet.contains(currentNode)) {
+ this.writer.write(HTMLIncludePrefix);
+ } else {
+ this.writer.write(HTMLExcludePrefix);
+ }
- case '&':
- this._writer.write("&amp;");
- break;
-
- case '<':
- this._writer.write("&lt;");
- break;
-
- case '"':
- this._writer.write("&quot;");
- break;
+ this.writer.write("<");
+ this.writer.write(currentElement.getTagName());
- case 0x09: // '\t'
- this._writer.write("&#x9;");
- break;
-
- case 0x0A: // '\n'
- this._writer.write("&#xA;");
- break;
-
- case 0x0D: // '\r'
- this._writer.write("&#xD;");
- break;
+ this.writer.write(HTMLIncludeOrExcludeSuffix);
- default:
- this._writer.write(c);
- break;
- }
- }
-
- this._writer.write("\"");
- }
+ // we output all Attrs which are available
+ NamedNodeMap attrs = currentElement.getAttributes();
+ int attrsLength = attrs.getLength();
+ Attr attrs2[] = new Attr[attrsLength];
- /**
- * Normalizes a {@link org.w3c.dom.Comment} value
- *
- * @param currentPI
- * @throws IOException
- */
- private void outputPItoWriter(ProcessingInstruction currentPI)
- throws IOException {
+ for (int i = 0; i < attrsLength; i++) {
+ attrs2[i] = (Attr)attrs.item(i);
+ }
- 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);
+ Arrays.sort(attrs2, ATTR_COMPARE);
+ Object attrs3[] = attrs2;
- switch (c) {
-
- case 0x0D:
- this._writer.write("&#xD;");
- break;
-
- case ' ':
- this._writer.write("·");
- break;
-
- case '\n':
- this._writer.write("¶\n");
- break;
+ 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());
- 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 (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._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;
+ }
+
+ 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;
}
- /**
- * Method outputCommentToWriter
- *
- * @param currentComment
- * @throws IOException
- */
- private void outputCommentToWriter(Comment currentComment)
- throws IOException {
+ 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;
+ }
- 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);
+ /**
+ * Normalizes an {@link Attr}ibute value
+ *
+ * The string value of the node is modified by replacing
+ * <UL>
+ * <LI>all ampersands (&) with <CODE>&amp;</CODE></LI>
+ * <LI>all open angle brackets (<) with <CODE>&lt;</CODE></LI>
+ * <LI>all quotation mark characters with <CODE>&quot;</CODE></LI>
+ * <LI>and the whitespace characters <CODE>#x9</CODE>, #xA, and #xD,
+ * with character references. The character references are written in
+ * uppercase hexadecimal with no leading zeroes (for example, <CODE>#xD</CODE>
+ * is represented by the character reference <CODE>&#xD;</CODE>)</LI>
+ * </UL>
+ *
+ * @param name
+ * @param value
+ * @throws IOException
+ */
+ private void outputAttrToWriter(String name, String value) throws IOException {
+ this.writer.write(" ");
+ this.writer.write(name);
+ this.writer.write("=\"");
- switch (c) {
+ int length = value.length();
+
+ for (int i = 0; i < length; i++) {
+ char c = value.charAt(i);
+
+ switch (c) {
- case 0x0D:
- this._writer.write("&#xD;");
- break;
+ case '&':
+ this.writer.write("&amp;");
+ break;
- case ' ':
- this._writer.write("·");
- break;
+ case '<':
+ this.writer.write("&lt;");
+ break;
- case '\n':
- this._writer.write("¶\n");
- break;
+ case '"':
+ this.writer.write("&quot;");
+ break;
+
+ case 0x09: // '\t'
+ this.writer.write("&#x9;");
+ break;
- default:
- this._writer.write(c);
- break;
- }
- }
+ case 0x0A: // '\n'
+ this.writer.write("&#xA;");
+ break;
- this._writer.write("-->");
+ case 0x0D: // '\r'
+ this.writer.write("&#xD;");
+ break;
+
+ default:
+ this.writer.write(c);
+ break;
+ }
}
- /**
- * Method outputTextToWriter
- *
- * @param text
- * @throws IOException
- */
- private void outputTextToWriter(String text) throws IOException {
+ 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;
- if (text == null) {
- return;
+ 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;
}
-
- int length = text.length();
+ }
+ }
- for (int i = 0; i < length; i++) {
- char c = text.charAt(i);
+ this.writer.write("?>");
+ }
- switch (c) {
+ /**
+ * Method outputCommentToWriter
+ *
+ * @param currentComment
+ * @throws IOException
+ */
+ private void outputCommentToWriter(Comment currentComment) throws IOException {
- case '&':
- this._writer.write("&amp;");
- break;
+ if (currentComment == null) {
+ return;
+ }
- case '<':
- this._writer.write("&lt;");
- break;
+ 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("&gt;");
- break;
+ case ' ':
+ this.writer.write("·");
+ break;
+
+ case '\n':
+ this.writer.write("¶\n");
+ break;
- case 0xD:
- this._writer.write("&#xD;");
- break;
+ default:
+ this.writer.write(c);
+ break;
+ }
+ }
+
+ this.writer.write("-->");
+ }
- case ' ':
- this._writer.write("·");
- break;
+ /**
+ * Method outputTextToWriter
+ *
+ * @param text
+ * @throws IOException
+ */
+ private void outputTextToWriter(String text) throws IOException {
+ if (text == null) {
+ return;
+ }
- case '\n':
- this._writer.write("¶\n");
- break;
+ int length = text.length();
+
+ for (int i = 0; i < length; i++) {
+ char c = text.charAt(i);
+
+ switch (c) {
+
+ case '&':
+ this.writer.write("&amp;");
+ break;
- default:
- this._writer.write(c);
- 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;
+ }
}
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,34 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*
+ * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
+ */
+/*
+ * $Id$
+ */
+package com.sun.org.apache.xml.internal.security.signature.reference;
+
+/**
+ * An abstract representation of the result of dereferencing a ds:Reference URI.
+ */
+public interface ReferenceData { }
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>ReferenceData</code> type containing a node-set.
+ */
+public interface ReferenceNodeSetData extends ReferenceData {
+
+ /**
+ * Returns a read-only iterator over the nodes contained in this
+ * <code>NodeSetData</code> in
+ * <a href="http://www.w3.org/TR/1999/REC-xpath-19991116#dt-document-order">
+ * document order</a>. Attempts to modify the returned iterator
+ * via the <code>remove</code> method throw
+ * <code>UnsupportedOperationException</code>.
+ *
+ * @return an <code>Iterator</code> over the nodes in this
+ * <code>NodeSetData</code> in document order
+ */
+ Iterator<Node> iterator();
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>ReferenceData</code> type containing an OctetStream.
+ */
+public class ReferenceOctetStreamData implements ReferenceData {
+ private InputStream octetStream;
+ private String uri;
+ private String mimeType;
+
+ /**
+ * Creates a new <code>ReferenceOctetStreamData</code>.
+ *
+ * @param octetStream the input stream containing the octets
+ * @throws NullPointerException if <code>octetStream</code> is
+ * <code>null</code>
+ */
+ public ReferenceOctetStreamData(InputStream octetStream) {
+ if (octetStream == null) {
+ throw new NullPointerException("octetStream is null");
+ }
+ this.octetStream = octetStream;
+ }
+
+ /**
+ * Creates a new <code>ReferenceOctetStreamData</code>.
+ *
+ * @param octetStream the input stream containing the octets
+ * @param uri the URI String identifying the data object (may be
+ * <code>null</code>)
+ * @param mimeType the MIME type associated with the data object (may be
+ * <code>null</code>)
+ * @throws NullPointerException if <code>octetStream</code> is
+ * <code>null</code>
+ */
+ 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 <code>ReferenceOctetStreamData</code>.
+ *
+ * @return the input stream of this <code>ReferenceOctetStreamData</code>.
+ */
+ public InputStream getOctetStream() {
+ return octetStream;
+ }
+
+ /**
+ * Returns the URI String identifying the data object represented by this
+ * <code>ReferenceOctetStreamData</code>.
+ *
+ * @return the URI String or <code>null</code> if not applicable
+ */
+ public String getURI() {
+ return uri;
+ }
+
+ /**
+ * Returns the MIME type associated with the data object represented by this
+ * <code>ReferenceOctetStreamData</code>.
+ *
+ * @return the MIME type or <code>null</code> if not applicable
+ */
+ public String getMimeType() {
+ return mimeType;
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>ReferenceNodeSetData</code> 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<Node> 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<Node> {
+ private Node root;
+ private List<Node> nodeSet;
+ private ListIterator<Node> 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<Node> dereferenceSameDocumentURI(Node node) {
+ List<Node> nodeSet = new ArrayList<Node>();
+ 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<Node> 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);
+ }
+ }
+ }
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,86 +2,84 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java Fri Jul 05 14:37:41 2013 -0700
@@ -263,7 +263,7 @@
* @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 @@
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<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
if (transformSpiClass == null) {
@@ -360,7 +360,7 @@
// give it to the current document
if (contextNodes != null) {
for (int i = 0; i < contextNodes.getLength(); i++) {
- this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
+ this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true));
}
}
return newTransformSpi;
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,29 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms;
-/**
- *
- * @author $Author: mullan $
- */
-
public interface TransformParam {
-}
+}
\ No newline at end of file
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.transforms;
@@ -37,28 +39,13 @@
* @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 @@
* @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 @@
* implementation.
*
* @param input {@link XMLSignatureInput} as the input of transformation
- * @param _transformObject the Transform
+ * @param transformObject the Transform object
* @return {@link XMLSignatureInput} as the result of transformation
* @throws CanonicalizationException
* @throws IOException
@@ -93,26 +79,14 @@
* @throws TransformationException
*/
protected XMLSignatureInput enginePerformTransform(
- XMLSignatureInput input, Transform _transformObject)
- throws IOException,
- CanonicalizationException, InvalidCanonicalizerException,
- TransformationException, ParserConfigurationException,
- SAXException {
- //Default implementation overide with a much better
- try {
- TransformSpi tmp = (TransformSpi) getClass().newInstance();
- tmp.setTransform(_transformObject);
- return tmp.enginePerformTransform(input);
- } catch (InstantiationException e) {
- throw new TransformationException("",e);
- } catch (IllegalAccessException e) {
- throw new TransformationException("",e);
- }
+ XMLSignatureInput input, Transform transformObject
+ ) throws IOException, CanonicalizationException, InvalidCanonicalizerException,
+ TransformationException, ParserConfigurationException, SAXException {
+ return enginePerformTransform(input, null, transformObject);
}
/**
* The mega method which MUST be implemented by the Transformation Algorithm.
- * @deprecated
* @param input {@link XMLSignatureInput} as the input of transformation
* @return {@link XMLSignatureInput} as the result of transformation
* @throws CanonicalizationException
@@ -122,15 +96,13 @@
* @throws SAXException
* @throws TransformationException
*/
- @Deprecated
protected XMLSignatureInput enginePerformTransform(
- XMLSignatureInput input)
- throws IOException,
- CanonicalizationException, InvalidCanonicalizerException,
- TransformationException, ParserConfigurationException,
- SAXException {
- throw new UnsupportedOperationException();
+ XMLSignatureInput input
+ ) throws IOException, CanonicalizationException, InvalidCanonicalizerException,
+ TransformationException, ParserConfigurationException, SAXException {
+ return enginePerformTransform(input, null);
}
+
/**
* Returns the URI representation of <code>Transformation algorithm</code>
*
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,86 +2,83 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms;
@@ -51,56 +53,64 @@
*/
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 Transforms(Document doc) {
super(doc);
- XMLUtils.addReturnToElement(this._constructionElement);
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -125,25 +135,28 @@
* @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 <code>Transform</code> with the specified <code>Transform
* algorithm URI</code>
*
@@ -151,14 +164,13 @@
* 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 @@
* 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 @@
* 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 @@
* @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 @@
* @throws TransformationException
*/
public XMLSignatureInput performTransforms(
- XMLSignatureInput xmlSignatureInput) throws TransformationException {
+ XMLSignatureInput xmlSignatureInput
+ ) throws TransformationException {
return performTransforms(xmlSignatureInput, null);
}
@@ -250,21 +262,22 @@
* @throws TransformationException
*/
public XMLSignatureInput performTransforms(
- XMLSignatureInput xmlSignatureInput, OutputStream os)
- throws TransformationException {
-
+ XMLSignatureInput xmlSignatureInput, OutputStream os
+ ) throws TransformationException {
try {
- int last=this.getLength()-1;
+ int last = this.getLength() - 1;
for (int i = 0; i < last; i++) {
Transform t = this.item(i);
+ String uri = t.getURI();
if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + t.getURI()
- + " transform");
+ log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform");
}
+ checkSecureValidation(t);
xmlSignatureInput = t.performTransform(xmlSignatureInput);
}
- if (last>=0) {
+ if (last >= 0) {
Transform t = this.item(last);
+ checkSecureValidation(t);
xmlSignatureInput = t.performTransform(xmlSignatureInput, os);
}
@@ -278,16 +291,26 @@
}
}
+ 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 @@
* @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);
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
-
-
import javax.xml.transform.TransformerException;
import com.sun.org.apache.xml.internal.dtm.DTM;
@@ -36,7 +36,6 @@
import org.w3c.dom.Document;
import org.w3c.dom.Node;
-
/**
* The 'here()' function returns a node-set containing the attribute or
* processing instruction node or the parent element of the text node
@@ -56,107 +55,98 @@
*/
public class FuncHere extends Function {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ /**
+ *
+ */
+ 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();
-
- if (xpathOwnerNode == null) {
- return null;
- }
+ Node xpathOwnerNode = (Node) xctxt.getOwnerObject();
- int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode);
-
- int currentNode = xctxt.getCurrentNode();
- DTM dtm = xctxt.getDTM(currentNode);
- int docContext = dtm.getDocument();
+ if (xpathOwnerNode == null) {
+ return null;
+ }
- if (DTM.NULL == docContext) {
- error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null);
- }
+ int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode);
- {
+ int currentNode = xctxt.getCurrentNode();
+ DTM dtm = xctxt.getDTM(currentNode);
+ int docContext = dtm.getDocument();
- // 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 (DTM.NULL == docContext) {
+ error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null);
+ }
- if (currentDoc != xpathOwnerDoc) {
- throw new TransformerException(I18n
- .translate("xpath.funcHere.documentsDiffer"));
- }
- }
+ {
+ // 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);
- XNodeSet nodes = new XNodeSet(xctxt.getDTMManager());
- NodeSetDTM nodeSet = nodes.mutableNodeset();
+ if (currentDoc != xpathOwnerDoc) {
+ throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer"));
+ }
+ }
- {
- int hereNode = DTM.NULL;
-
- switch (dtm.getNodeType(xpathOwnerNodeDTM)) {
+ XNodeSet nodes = new XNodeSet(xctxt.getDTMManager());
+ NodeSetDTM nodeSet = nodes.mutableNodeset();
- case Node.ATTRIBUTE_NODE : {
- // returns a node-set containing the attribute
- hereNode = xpathOwnerNodeDTM;
+ {
+ int hereNode = DTM.NULL;
- nodeSet.addNode(hereNode);
+ switch (dtm.getNodeType(xpathOwnerNodeDTM)) {
- break;
- }
- case Node.PROCESSING_INSTRUCTION_NODE : {
- // returns a node-set containing the processing instruction node
- hereNode = xpathOwnerNodeDTM;
+ case Node.ATTRIBUTE_NODE :
+ case Node.PROCESSING_INSTRUCTION_NODE : {
+ // returns a node-set containing the attribute / processing instruction node
+ hereNode = xpathOwnerNodeDTM;
+
+ nodeSet.addNode(hereNode);
- 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.TEXT_NODE : {
- // returns a node-set containing the parent element of the
- // text node that directly bears the XPath expression
- hereNode = dtm.getParent(xpathOwnerNodeDTM);
+ nodeSet.addNode(hereNode);
- nodeSet.addNode(hereNode);
+ break;
+ }
+ default :
+ break;
+ }
+ }
- break;
- }
- default :
- break;
- }
- }
-
- /** $todo$ Do I have to do this detach() call? */
- nodeSet.detach();
+ /** $todo$ Do I have to do this detach() call? */
+ nodeSet.detach();
- return nodes;
- }
+ 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
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java Fri Jul 05 13:28:17 2013 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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 <CODE>here()</CODE> function. The here() function needs to know
- * <I>where</I> 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.
- *
- * <PRE>
- * From: Scott_Boag\@lotus.com
- * To: Christian Geuer-Pollmann <maillist\@nue.et-inf.uni-siegen.de>
- * 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
- * </PRE>
- *
- * @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 <A HREF="http://www.w3.org/Signature/Drafts/xmldsig-core/Overview.html#function-here">XML Signature - The here() function</A>
- */
-public class FuncHereContext extends XPathContext {
-
- /**
- * This constuctor is disabled because if we use the here() function we
- * <I>always</I> 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() + "\"");
- }
- }
-}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
-
-
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -72,115 +72,106 @@
*/
public class TransformBase64Decode extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_BASE64_DECODE;
+ /** 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();
+ }
+ 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;
+ }
- 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) {
+ 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();
}
- }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.transforms.implementations;
@@ -37,39 +39,30 @@
*/
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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
@@ -41,15 +43,9 @@
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);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
@@ -41,15 +43,9 @@
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) {
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.transforms.implementations;
@@ -36,71 +38,59 @@
/**
* Class TransformC14NExclusive
*
- * @author $Author: mullan $
- * @version $Revision: 1.5 $
*/
public class TransformC14NExclusive extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
-
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- protected String engineGetURI() {
- return implementedTransformURI;
- }
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI =
+ Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS;
- /**
- * 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);
- }
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ protected String engineGetURI() {
+ return implementedTransformURI;
+ }
- 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;
- result =c14n.engineCanonicalize(input, inclusiveNamespaces);
+ Canonicalizer20010315ExclOmitComments c14n =
+ new Canonicalizer20010315ExclOmitComments();
+ if (os != null) {
+ c14n.setWriter(os);
+ }
+ byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
- XMLSignatureInput output=new XMLSignatureInput(result);
- if (os!=null) {
- output.setOutputStream(os);
- }
- return output;
- } catch (XMLSecurityException ex) {
- throw new CanonicalizationException("empty", ex);
- }
- }
+ XMLSignatureInput output = new XMLSignatureInput(result);
+ if (os != null) {
+ output.setOutputStream(os);
+ }
+ return output;
+ } catch (XMLSecurityException ex) {
+ throw new CanonicalizationException("empty", ex);
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.transforms.implementations;
@@ -41,59 +43,54 @@
*/
public class TransformC14NExclusiveWithComments extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS;
-
- /**
- * Method engineGetURI
- *@inheritDoc
- *
- */
- protected String engineGetURI() {
- return implementedTransformURI;
- }
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI =
+ Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS;
- /**
- * @inheritDoc
- */
- protected XMLSignatureInput enginePerformTransform
- (XMLSignatureInput input, Transform _transformObject)
- throws CanonicalizationException {
- return enginePerformTransform(input, null, _transformObject);
- }
+ /**
+ * Method engineGetURI
+ *@inheritDoc
+ *
+ */
+ protected String engineGetURI() {
+ return implementedTransformURI;
+ }
- 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);
-
- inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
- _transformObject.getBaseURI()).getInclusiveNamespaces();
- }
+ if (transformObject.length(
+ InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+ InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1
+ ) {
+ Element inclusiveElement =
+ XMLUtils.selectNode(
+ transformObject.getElement().getFirstChild(),
+ InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+ InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+ 0
+ );
- Canonicalizer20010315ExclWithComments c14n =
- new Canonicalizer20010315ExclWithComments();
- if (os!=null) {
- c14n.setWriter( os);
+ 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);
}
- byte []result;
- result =c14n.engineCanonicalize(input, inclusiveNamespaces);
- XMLSignatureInput output=new XMLSignatureInput(result);
-
- return output;
- } catch (XMLSecurityException ex) {
- throw new CanonicalizationException("empty", ex);
- }
- }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.transforms.implementations;
@@ -37,37 +39,31 @@
*/
public class TransformC14NWithComments extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_C14N_WITH_COMMENTS;
-
- /** @inheritDoc */
- protected String engineGetURI() {
- return implementedTransformURI;
- }
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI =
+ Transforms.TRANSFORM_C14N_WITH_COMMENTS;
- /** @inheritDoc */
- protected XMLSignatureInput enginePerformTransform
- (XMLSignatureInput input, Transform _transformObject)
- throws CanonicalizationException {
- return enginePerformTransform(input, null, _transformObject);
- }
+ /** @inheritDoc */
+ protected String engineGetURI() {
+ return implementedTransformURI;
+ }
- /** @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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,24 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
+import java.io.OutputStream;
+
import com.sun.org.apache.xml.internal.security.signature.NodeFilter;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
@@ -39,99 +43,99 @@
*/
public class TransformEnvelopedSignature extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_ENVELOPED_SIGNATURE;
-
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- protected String engineGetURI() {
- return implementedTransformURI;
- }
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI =
+ Transforms.TRANSFORM_ENVELOPED_SIGNATURE;
- /**
- * @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.
- */
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ protected String engineGetURI() {
+ return implementedTransformURI;
+ }
- Node signatureElement = _transformObject.getElement();
-
+ /**
+ * @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.
+ */
- signatureElement = searchSignatureElement(signatureElement);
- input.setExcludeNode(signatureElement);
- input.addNodeFilter(new EnvelopedNodeFilter(signatureElement));
- return input;
-
- //
-
-
- }
+ Node signatureElement = transformObject.getElement();
- /**
- * @param signatureElement
- * @return the node that is the signature
- * @throws TransformationException
- */
- private static Node searchSignatureElement(Node signatureElement) throws TransformationException {
- boolean found=false;
+ signatureElement = searchSignatureElement(signatureElement);
+ input.setExcludeNode(signatureElement);
+ input.addNodeFilter(new EnvelopedNodeFilter(signatureElement));
+ return input;
+ }
- 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;
- }
+ /**
+ * @param signatureElement
+ * @return the node that is the signature
+ * @throws TransformationException
+ */
+ private static Node searchSignatureElement(Node signatureElement)
+ throws TransformationException {
+ boolean found = false;
- signatureElement = signatureElement.getParentNode();
+ 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;
}
- if (!found) {
- throw new TransformationException(
- "envelopedSignatureTransformNotInSignatureElement");
- }
- return signatureElement;
+ signatureElement = signatureElement.getParentNode();
+ }
+
+ if (!found) {
+ throw new TransformationException(
+ "transform.envelopedSignatureTransformNotInSignatureElement");
+ }
+ return signatureElement;
}
+
static class EnvelopedNodeFilter implements NodeFilter {
+
Node exclude;
+
EnvelopedNodeFilter(Node n) {
- exclude=n;
+ exclude = n;
}
- public int isNodeIncludeDO(Node n, int level) {
- if ((n==exclude))
- return -1;
- return 1;
- }
+
+ public int isNodeIncludeDO(Node n, int level) {
+ if (n == exclude) {
+ return -1;
+ }
+ return 1;
+ }
+
/**
* @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node)
*/
public int isNodeInclude(Node n) {
- if ((n==exclude) || XMLUtils.isDescendantOrSelf(exclude,n))
- return -1;
- return 1;
+ if (n == exclude || XMLUtils.isDescendantOrSelf(exclude, n)) {
+ return -1;
+ }
+ return 1;
//return !XMLUtils.isDescendantOrSelf(exclude,n);
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,24 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
+import java.io.OutputStream;
+
import javax.xml.transform.TransformerException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException;
@@ -29,12 +33,10 @@
import com.sun.org.apache.xml.internal.security.transforms.TransformSpi;
import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
-import com.sun.org.apache.xpath.internal.objects.XObject;
+import com.sun.org.apache.xml.internal.security.utils.XPathAPI;
+import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -51,118 +53,112 @@
*/
public class TransformXPath extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_XPATH;
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI = Transforms.TRANSFORM_XPATH;
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- protected String engineGetURI() {
- return implementedTransformURI;
- }
-
- /**
- * Method enginePerformTransform
- * @inheritDoc
- * @param input
- *
- * @throws TransformationException
- */
- protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject)
- throws TransformationException {
-
- try {
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ protected String engineGetURI() {
+ return implementedTransformURI;
+ }
- /**
- * If the actual input is an octet stream, then the application MUST
- * convert the octet stream to an XPath node-set suitable for use by
- * Canonical XML with Comments. (A subsequent application of the
- * REQUIRED Canonical XML algorithm would strip away these comments.)
- *
- * ...
- *
- * The evaluation of this expression includes all of the document's nodes
- * (including comments) in the node-set representing the octet stream.
- */
- CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument());
-
-
-
- Element xpathElement =XMLUtils.selectDsNode(
- _transformObject.getElement().getFirstChild(),
- Constants._TAG_XPATH,0);
-
- if (xpathElement == null) {
- Object exArgs[] = { "ds:XPath", "Transform" };
+ /**
+ * 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);
- 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");
- }
+ if (xpathElement == null) {
+ Object exArgs[] = { "ds:XPath", "Transform" };
+ throw new TransformationException("xml.WrongContent", exArgs);
+ }
+ Node xpathnode = xpathElement.getChildNodes().item(0);
+ String str = XMLUtils.getStrFromNode(xpathnode);
+ input.setNeedsToBeExpanded(needsCircumvent(str));
+ if (xpathnode == null) {
+ throw new DOMException(
+ DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath"
+ );
+ }
- input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str));
- input.setNodeSet(true);
- return input;
- } catch (DOMException ex) {
- throw new TransformationException("empty", ex);
- }
- }
+ XPathFactory xpathFactory = XPathFactory.newInstance();
+ XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
+ input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance));
+ input.setNodeSet(true);
+ return input;
+ } catch (DOMException ex) {
+ throw new TransformationException("empty", ex);
+ }
+ }
- /**
- * @param str
- * @return true if needs to be 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);
}
+
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,30 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
-
-
import java.io.IOException;
+import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
@@ -42,9 +42,9 @@
import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import com.sun.org.apache.xml.internal.security.transforms.params.XPath2FilterContainer;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder;
-import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
+import com.sun.org.apache.xml.internal.security.utils.XPathAPI;
+import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -55,254 +55,241 @@
/**
* Implements the <I>XML Signature XPath Filter v2.0</I>
*
- * @author $Author: mullan $
* @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
- * @see <a HREF="http://www.w3.org/Signature/Drafts/xmldsig-xfilter2/">XPath Filter v2.0 (editors copy)</a>
*/
public class TransformXPath2Filter extends TransformSpi {
- /** {@link java.util.logging} logging facility */
-// static java.util.logging.Logger log =
-// java.util.logging.Logger.getLogger(
-// TransformXPath2Filter.class.getName());
-
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_XPATH2FILTER;
- //J-
- // contains the type of the filter
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI =
+ Transforms.TRANSFORM_XPATH2FILTER;
- // contains the node set
-
- /**
- * 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 {
- CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument());
- try {
- List<NodeList> unionNodes=new ArrayList<NodeList>();
- List<NodeList> substractNodes=new ArrayList<NodeList>();
- List<NodeList> intersectNodes=new ArrayList<NodeList>();
+ /**
+ * Method enginePerformTransform
+ * @inheritDoc
+ * @param input
+ *
+ * @throws TransformationException
+ */
+ protected XMLSignatureInput enginePerformTransform(
+ XMLSignatureInput input, OutputStream os, Transform transformObject
+ ) throws TransformationException {
+ try {
+ List<NodeList> unionNodes = new ArrayList<NodeList>();
+ List<NodeList> subtractNodes = new ArrayList<NodeList>();
+ List<NodeList> intersectNodes = new ArrayList<NodeList>();
- CachedXPathFuncHereAPI xPathFuncHereAPI =
- new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI());
-
+ Element[] xpathElements =
+ XMLUtils.selectNodes(
+ transformObject.getElement().getFirstChild(),
+ XPath2FilterContainer.XPathFilter2NS,
+ XPath2FilterContainer._TAG_XPATH2
+ );
+ if (xpathElements.length == 0) {
+ Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" };
- Element []xpathElements =XMLUtils.selectNodes(
- _transformObject.getElement().getFirstChild(),
- XPath2FilterContainer.XPathFilter2NS,
- XPath2FilterContainer._TAG_XPATH2);
- int noOfSteps = xpathElements.length;
+ throw new TransformationException("xml.WrongContent", exArgs);
+ }
-
- if (noOfSteps == 0) {
- Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" };
+ Document inputDoc = null;
+ if (input.getSubNode() != null) {
+ inputDoc = XMLUtils.getOwnerDocument(input.getSubNode());
+ } else {
+ inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet());
+ }
- throw new TransformationException("xml.WrongContent", exArgs);
- }
+ for (int i = 0; i < xpathElements.length; i++) {
+ Element xpathElement = xpathElements[i];
- Document inputDoc = null;
- if (input.getSubNode() != null) {
- inputDoc = XMLUtils.getOwnerDocument(input.getSubNode());
- } else {
- inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet());
- }
+ XPath2FilterContainer xpathContainer =
+ XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI());
- 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());
+ String str =
+ XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode());
+ XPathFactory xpathFactory = XPathFactory.newInstance();
+ XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
- 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);
- }
- }
-
+ NodeList subtreeRoots =
+ xpathAPIInstance.selectNodeList(
+ inputDoc,
+ xpathContainer.getXPathFilterTextNode(),
+ str,
+ xpathContainer.getElement());
+ if (xpathContainer.isIntersect()) {
+ intersectNodes.add(subtreeRoots);
+ } else if (xpathContainer.isSubtract()) {
+ subtractNodes.add(subtreeRoots);
+ } else if (xpathContainer.isUnion()) {
+ unionNodes.add(subtreeRoots);
+ }
+ }
- input.addNodeFilter(new XPath2NodeFilter(unionNodes, 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<NodeList> unionNodes, List<NodeList> substractNodes,
- List<NodeList> intersectNodes) {
- hasUnionFilter=!unionNodes.isEmpty();
- this.unionNodes=convertNodeListToSet(unionNodes);
- hasSubstractFilter=!substractNodes.isEmpty();
- this.substractNodes=convertNodeListToSet(substractNodes);
- hasIntersectFilter=!intersectNodes.isEmpty();
- this.intersectNodes=convertNodeListToSet(intersectNodes);
- }
- Set<Node> unionNodes;
- Set<Node> substractNodes;
- Set<Node> intersectNodes;
+ boolean hasUnionFilter;
+ boolean hasSubtractFilter;
+ boolean hasIntersectFilter;
+ Set<Node> unionNodes;
+ Set<Node> subtractNodes;
+ Set<Node> intersectNodes;
+ int inSubtract = -1;
+ int inIntersect = -1;
+ int inUnion = -1;
+
+ XPath2NodeFilter(List<NodeList> unionNodes, List<NodeList> subtractNodes,
+ List<NodeList> 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;
+ /**
+ * @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;
+ }
- if (hasSubstractFilter && rooted(currentNode, substractNodes)) {
- result = -1;
- } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) {
- result = 0;
- }
-
- //TODO OPTIMIZE
- if (result==1)
- return 1;
- if (hasUnionFilter) {
- if (rooted(currentNode, unionNodes)) {
- return 1;
- }
- result=0;
- }
- return result;
+ //TODO OPTIMIZE
+ if (result == 1) {
+ return 1;
+ }
+ if (hasUnionFilter) {
+ if (rooted(currentNode, unionNodes)) {
+ return 1;
+ }
+ result = 0;
+ }
+ return result;
+ }
- }
- int inSubstract=-1;
- int inIntersect=-1;
- int inUnion=-1;
- public int isNodeIncludeDO(Node n, int level) {
- int result=1;
- if (hasSubstractFilter) {
- if ((inSubstract==-1) || (level<=inSubstract)) {
- if (inList(n, substractNodes)) {
- inSubstract=level;
- } else {
- inSubstract=-1;
- }
- }
- if (inSubstract!=-1){
- result=-1;
- }
- }
- if (result!=-1){
- if (hasIntersectFilter) {
- if ((inIntersect==-1) || (level<=inIntersect)) {
- if (!inList(n, intersectNodes)) {
- inIntersect=-1;
- result=0;
- } else {
- inIntersect=level;
- }
- }
- }
- }
+ public int isNodeIncludeDO(Node n, int level) {
+ int result = 1;
+ if (hasSubtractFilter) {
+ if ((inSubtract == -1) || (level <= inSubtract)) {
+ if (inList(n, subtractNodes)) {
+ inSubtract = level;
+ } else {
+ inSubtract = -1;
+ }
+ }
+ if (inSubtract != -1){
+ result = -1;
+ }
+ }
+ if (result != -1 && hasIntersectFilter
+ && ((inIntersect == -1) || (level <= inIntersect))) {
+ if (!inList(n, intersectNodes)) {
+ inIntersect = -1;
+ result = 0;
+ } else {
+ inIntersect = level;
+ }
+ }
- if (level<=inUnion)
- inUnion=-1;
- if (result==1)
- return 1;
- if (hasUnionFilter) {
- if ((inUnion==-1) && inList(n, unionNodes)) {
- inUnion=level;
- }
- if (inUnion!=-1)
- return 1;
- result=0;
- }
+ 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;
+ }
- return result;
- }
-
- /**
- * Method rooted
- * @param currentNode
- * @param nodeList
- *
- * @return if rooted bye the rootnodes
- */
- static boolean rooted(Node currentNode, Set<Node> nodeList ) {
- if (nodeList.isEmpty()) {
- return false;
- }
- if (nodeList.contains(currentNode)) {
- return true;
- }
+ /**
+ * Method rooted
+ * @param currentNode
+ * @param nodeList
+ *
+ * @return if rooted bye the rootnodes
+ */
+ static boolean rooted(Node currentNode, Set<Node> 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;
+ }
- 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<Node> nodeList) {
+ return nodeList.contains(currentNode);
+ }
- /**
- * Method rooted
- * @param currentNode
- * @param nodeList
- *
- * @return if rooted bye the rootnodes
- */
- static boolean inList(Node currentNode, Set<Node> nodeList ) {
- return nodeList.contains(currentNode);
- }
+ private static Set<Node> convertNodeListToSet(List<NodeList> l) {
+ Set<Node> result = new HashSet<Node>();
+ for (NodeList rootNodes : l) {
+ int length = rootNodes.getLength();
- private static Set<Node> convertNodeListToSet(List<NodeList> l){
- Set<Node> result=new HashSet<Node>();
-
- for (NodeList rootNodes : l) {
- int length = rootNodes.getLength();
- for (int i = 0; i < length; i++) {
- Node rootNode = rootNodes.item(i);
- result.add(rootNode);
- }
+ for (int i = 0; i < length; i++) {
+ Node rootNode = rootNodes.item(i);
+ result.add(rootNode);
+ }
}
return result;
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,27 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
-
-
+import java.io.OutputStream;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
@@ -29,8 +30,6 @@
import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
-
-
/**
* Class TransformXPointer
*
@@ -38,30 +37,29 @@
*/
public class TransformXPointer extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_XPOINTER;
+ /** 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);
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2007 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.implementations;
@@ -24,7 +26,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.lang.reflect.Method;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
@@ -55,132 +56,112 @@
*/
public class TransformXSLT extends TransformSpi {
- /** Field implementedTransformURI */
- public static final String implementedTransformURI =
- Transforms.TRANSFORM_XSLT;
- //J-
- static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform";
- static final String defaultXSLTSpecNSprefix = "xslt";
- static final String XSLTSTYLESHEET = "stylesheet";
+ /** Field implementedTransformURI */
+ public static final String implementedTransformURI =
+ Transforms.TRANSFORM_XSLT;
+
+ static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform";
+ static final String defaultXSLTSpecNSprefix = "xslt";
+ static final String XSLTSTYLESHEET = "stylesheet";
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- TransformXSLT.class.getName());
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(TransformXSLT.class.getName());
- /**
- * Method engineGetURI
- *
- * @inheritDoc
- */
- protected String engineGetURI() {
- return implementedTransformURI;
- }
+ /**
+ * Method engineGetURI
+ *
+ * @inheritDoc
+ */
+ protected String engineGetURI() {
+ return implementedTransformURI;
+ }
- /**
- * Method enginePerformTransform
- *
- * @param input the input for this transform
- * @return the result of this Transform
- * @throws IOException
- * @throws TransformationException
- */
- protected XMLSignatureInput enginePerformTransform
- (XMLSignatureInput input, Transform _transformObject)
- throws IOException,
- TransformationException {
- return enginePerformTransform(input, null, _transformObject);
- }
+ protected XMLSignatureInput enginePerformTransform(
+ XMLSignatureInput input, OutputStream baos, Transform transformObject
+ ) throws IOException, TransformationException {
+ try {
+ Element transformElement = transformObject.getElement();
+
+ Element xsltElement =
+ XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0);
+
+ if (xsltElement == null) {
+ Object exArgs[] = { "xslt:stylesheet", "Transform" };
- protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject)
- throws IOException,
- TransformationException {
- try {
- Element transformElement = _transformObject.getElement();
+ throw new TransformationException("xml.WrongContent", exArgs);
+ }
+
+ TransformerFactory tFactory = TransformerFactory.newInstance();
+ // Process XSLT stylesheets in a secure manner
+ tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
- Element _xsltElement =
- XMLUtils.selectNode(transformElement.getFirstChild(),
- XSLTSpecNS,"stylesheet", 0);
-
- if (_xsltElement == null) {
- Object exArgs[] = { "xslt:stylesheet", "Transform" };
-
- throw new TransformationException("xml.WrongContent", exArgs);
- }
-
- TransformerFactory tFactory = TransformerFactory.newInstance();
+ /*
+ * 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;
- // Process XSLT stylesheets in a secure manner
- tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
- Boolean.TRUE);
- /*
- * This transform requires an octet stream as input. If the actual
- * input is an XPath node-set, then the signature application should
- * attempt to convert it to octets (apply Canonical XML]) as described
- * in the Reference Processing Model (section 4.3.3.2).
- */
- Source xmlSource =
- new StreamSource(new ByteArrayInputStream(input.getBytes()));
- Source stylesheet;
+ /*
+ * This complicated transformation of the stylesheet itself is necessary
+ * because of the need to get the pure style sheet. If we simply say
+ * Source stylesheet = new DOMSource(this.xsltElement);
+ * whereby this.xsltElement is not the rootElement of the Document,
+ * this causes problems;
+ * so we convert the stylesheet to byte[] and use this as input stream
+ */
+ {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ Transformer transformer = tFactory.newTransformer();
+ DOMSource source = new DOMSource(xsltElement);
+ StreamResult result = new StreamResult(os);
- /*
- * 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);
+ if (baos == null) {
+ ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
+ StreamResult outputTarget = new StreamResult(baos1);
+ transformer.transform(xmlSource, outputTarget);
+ return new XMLSignatureInput(baos1.toByteArray());
+ }
+ StreamResult outputTarget = new StreamResult(baos);
+
transformer.transform(xmlSource, outputTarget);
- return new XMLSignatureInput(baos1.toByteArray());
- }
- StreamResult outputTarget = new StreamResult(baos);
-
- transformer.transform(xmlSource, outputTarget);
- XMLSignatureInput output=new XMLSignatureInput((byte[])null);
- output.setOutputStream(baos);
- return output;
- } catch (XMLSecurityException ex) {
- Object exArgs[] = { ex.getMessage() };
+ 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);
+ }
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,30 +2,28 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.params;
-
-
-import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
-import java.util.StringTokenizer;
import java.util.TreeSet;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
@@ -34,7 +32,6 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-
/**
* This Object serves as Content for the ds:Transforms for exclusive
* Canonicalization.
@@ -44,136 +41,130 @@
*
* @author Christian Geuer-Pollmann
*/
-public class InclusiveNamespaces extends ElementProxy
- implements TransformParam {
+public class InclusiveNamespaces extends ElementProxy implements TransformParam {
+
+ /** Field _TAG_EC_INCLUSIVENAMESPACES */
+ public static final String _TAG_EC_INCLUSIVENAMESPACES =
+ "InclusiveNamespaces";
- /** Field _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<String> prefixes) {
+ super(doc);
- /**
- * Constructor InclusiveNamespaces
- *
- * @param doc
- * @param prefixes
- */
- public InclusiveNamespaces(Document doc, Set<String> prefixes) {
+ SortedSet<String> prefixList = null;
+ if (prefixes instanceof SortedSet<?>) {
+ prefixList = (SortedSet<String>)prefixes;
+ } else {
+ prefixList = new TreeSet<String>(prefixes);
+ }
- super(doc);
-
- StringBuffer sb = new StringBuffer();
- SortedSet<String> prefixList = new TreeSet<String>(prefixes);
-
-
+ StringBuilder sb = new StringBuilder();
+ for (String prefix : prefixList) {
+ if (prefix.equals("xmlns")) {
+ sb.append("#default ");
+ } else {
+ sb.append(prefix + " ");
+ }
+ }
- 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());
+ }
- this._constructionElement
- .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST,
- sb.toString().trim());
- }
-
- /**
- * Method getInclusiveNamespaces
- *
- * @return The Inclusive Namespace string
- */
- public String getInclusiveNamespaces() {
- return this._constructionElement
- .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST);
- }
+ /**
+ * Constructor InclusiveNamespaces
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public InclusiveNamespaces(Element element, String BaseURI)
+ throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- /**
- * Constructor InclusiveNamespaces
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public InclusiveNamespaces(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * Method getInclusiveNamespaces
+ *
+ * @return The Inclusive Namespace string
+ */
+ public String getInclusiveNamespaces() {
+ return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST);
+ }
- /**
- * Decodes the <code>inclusiveNamespaces</code> String and returns all
- * selected namespace prefixes as a Set. The <code>#default</code>
- * namespace token is represented as an empty namespace prefix
- * (<code>"xmlns"</code>).
- * <BR/>
- * The String <code>inclusiveNamespaces=" xenc ds #default"</code>
- * is returned as a Set containing the following Strings:
- * <UL>
- * <LI><code>xmlns</code></LI>
- * <LI><code>xenc</code></LI>
- * <LI><code>ds</code></LI>
- * </UL>
- *
- * @param inclusiveNamespaces
- * @return A set to string
- */
- public static SortedSet<String> prefixStr2Set(String inclusiveNamespaces) {
-
- SortedSet<String> prefixes = new TreeSet<String>();
+ /**
+ * Decodes the <code>inclusiveNamespaces</code> String and returns all
+ * selected namespace prefixes as a Set. The <code>#default</code>
+ * namespace token is represented as an empty namespace prefix
+ * (<code>"xmlns"</code>).
+ * <BR/>
+ * The String <code>inclusiveNamespaces=" xenc ds #default"</code>
+ * is returned as a Set containing the following Strings:
+ * <UL>
+ * <LI><code>xmlns</code></LI>
+ * <LI><code>xenc</code></LI>
+ * <LI><code>ds</code></LI>
+ * </UL>
+ *
+ * @param inclusiveNamespaces
+ * @return A set to string
+ */
+ public static SortedSet<String> prefixStr2Set(String inclusiveNamespaces) {
+ SortedSet<String> prefixes = new TreeSet<String>();
- if ((inclusiveNamespaces == null)
- || (inclusiveNamespaces.length() == 0)) {
- return prefixes;
- }
-
- StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n");
+ if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) {
+ return prefixes;
+ }
- while (st.hasMoreTokens()) {
- String prefix = st.nextToken();
+ String[] tokens = inclusiveNamespaces.split("\\s");
+ for (String prefix : tokens) {
+ if (prefix.equals("#default")) {
+ prefixes.add("xmlns");
+ } else {
+ prefixes.add(prefix);
+ }
+ }
- if (prefix.equals("#default")) {
- prefixes.add("xmlns" );
- } else {
- prefixes.add( prefix);
- }
- }
+ return prefixes;
+ }
- return prefixes;
- }
+ /**
+ * Method getBaseNamespace
+ *
+ * @inheritDoc
+ */
+ public String getBaseNamespace() {
+ return InclusiveNamespaces.ExclusiveCanonicalizationNamespace;
+ }
- /**
- * 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.params;
-
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@@ -32,284 +32,261 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-
/**
* Implements the parameters for the <A
* HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0</A>.
*
- * @author $Author: mullan $
+ * @author $Author: coheigea $
* @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
- * @see <A HREF="http://www.w3.org/Signature/Drafts/xmldsig-xfilter2/">XPath Filter v2.0 (editors copy)</A>
*/
-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() {
-
- // no instantiation
- }
+ /**
+ * Constructor XPath2FilterContainer
+ *
+ */
+ private XPath2FilterContainer() {
+ // no instantiation
+ }
- /**
- * Constructor XPath2FilterContainer
- *
- * @param doc
- * @param xpath2filter
- * @param filterType
- */
- private XPath2FilterContainer(Document doc, String xpath2filter,
- String filterType) {
+ /**
+ * Constructor XPath2FilterContainer
+ *
+ * @param doc
+ * @param xpath2filter
+ * @param filterType
+ */
+ private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) {
+ super(doc);
- super(doc);
-
- this._constructionElement
- .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType);
- this._constructionElement.appendChild(doc.createTextNode(xpath2filter));
- }
+ this.constructionElement.setAttributeNS(
+ null, XPath2FilterContainer._ATT_FILTER, filterType);
+ this.constructionElement.appendChild(doc.createTextNode(xpath2filter));
+ }
- /**
- * Constructor XPath2FilterContainer
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- private XPath2FilterContainer(Element element, String BaseURI)
- throws XMLSecurityException {
+ /**
+ * Constructor XPath2FilterContainer
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ super(element, BaseURI);
- String filterStr = this._constructionElement.getAttributeNS(null,
- XPath2FilterContainer._ATT_FILTER);
+ String filterStr =
+ this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER);
- if (!filterStr
- .equals(XPath2FilterContainer
- ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr
- .equals(XPath2FilterContainer
- ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr
- .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) {
- Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr,
- XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT
- + ", "
- + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT
- + " or "
- + XPath2FilterContainer._ATT_FILTER_VALUE_UNION };
+ if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT)
+ && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT)
+ && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) {
+ Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr,
+ XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT
+ + ", "
+ + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT
+ + " or "
+ + XPath2FilterContainer._ATT_FILTER_VALUE_UNION };
- throw new XMLSecurityException("attributeValueIllegal", exArgs);
- }
- }
+ throw new XMLSecurityException("attributeValueIllegal", exArgs);
+ }
+ }
- /**
- * Creates a new XPath2FilterContainer with the filter type "intersect".
- *
- * @param doc
- * @param xpath2filter
- * @return the filter.
- */
- public static XPath2FilterContainer newInstanceIntersect(Document doc,
- String xpath2filter) {
-
- return new XPath2FilterContainer(doc, xpath2filter,
- XPath2FilterContainer
- ._ATT_FILTER_VALUE_INTERSECT);
- }
+ /**
+ * Creates a new XPath2FilterContainer with the filter type "intersect".
+ *
+ * @param doc
+ * @param xpath2filter
+ * @return the filter.
+ */
+ public static XPath2FilterContainer newInstanceIntersect(
+ Document doc, String xpath2filter
+ ) {
+ return new XPath2FilterContainer(
+ doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
+ }
- /**
- * Creates a new XPath2FilterContainer with the filter type "subtract".
- *
- * @param doc
- * @param xpath2filter
- * @return the filter.
- */
- public static XPath2FilterContainer newInstanceSubtract(Document doc,
- String xpath2filter) {
+ /**
+ * 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);
+ }
- return new XPath2FilterContainer(doc, xpath2filter,
- XPath2FilterContainer
- ._ATT_FILTER_VALUE_SUBTRACT);
- }
-
- /**
- * Creates a new XPath2FilterContainer with the filter type "union".
- *
- * @param doc
- * @param xpath2filter
- * @return the filter
- */
- public static XPath2FilterContainer newInstanceUnion(Document doc,
- String xpath2filter) {
+ /**
+ * 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_UNION);
- }
+ /**
+ * Method newInstances
+ *
+ * @param doc
+ * @param params
+ * @return the nodelist with the data
+ */
+ public static NodeList newInstances(Document doc, String[][] params) {
+ HelperNodeList nl = new HelperNodeList();
- /**
- * Method newInstances
- *
- * @param doc
- * @param params
- * @return the nodelist with the data
- */
- public static NodeList newInstances(Document doc, String[][] params) {
-
- HelperNodeList nl = new HelperNodeList();
+ XMLUtils.addReturnToElement(doc, nl);
- XMLUtils.addReturnToElement(doc, nl);
-
- for (int i = 0; i < params.length; i++) {
- String type = params[i][0];
- String xpath = params[i][1];
+ for (int i = 0; i < params.length; i++) {
+ String type = params[i][0];
+ String xpath = params[i][1];
- if (!(type.equals(XPath2FilterContainer
- ._ATT_FILTER_VALUE_INTERSECT) || type
- .equals(XPath2FilterContainer
- ._ATT_FILTER_VALUE_SUBTRACT) || type
- .equals(XPath2FilterContainer
- ._ATT_FILTER_VALUE_UNION))) {
- throw new IllegalArgumentException("The type(" + i + ")=\"" + type
- + "\" is illegal");
- }
+ if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT)
+ || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT)
+ || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))){
+ throw new IllegalArgumentException("The type(" + i + ")=\"" + type
+ + "\" is illegal");
+ }
+
+ XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type);
+
+ nl.appendChild(c.getElement());
+ XMLUtils.addReturnToElement(doc, nl);
+ }
- XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type);
-
- nl.appendChild(c.getElement());
- XMLUtils.addReturnToElement(doc, nl);
- }
-
- return nl;
- }
+ return nl;
+ }
- /**
- * Creates a XPath2FilterContainer from an existing Element; needed for verification.
- *
- * @param element
- * @param BaseURI
- * @return the filter
- *
- * @throws XMLSecurityException
- */
- public static XPath2FilterContainer newInstance(
- Element element, String BaseURI) throws XMLSecurityException {
- return new XPath2FilterContainer(element, BaseURI);
- }
+ /**
+ * Creates a XPath2FilterContainer from an existing Element; needed for verification.
+ *
+ * @param element
+ * @param BaseURI
+ * @return the filter
+ *
+ * @throws XMLSecurityException
+ */
+ public static XPath2FilterContainer newInstance(
+ Element element, String BaseURI
+ ) throws XMLSecurityException {
+ return new XPath2FilterContainer(element, BaseURI);
+ }
- /**
- * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
- *
- * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
- */
- public boolean isIntersect() {
-
- return this._constructionElement
- .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER)
- .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
- }
+ /**
+ * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+ *
+ * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+ */
+ public boolean isIntersect() {
+ return this.constructionElement.getAttributeNS(
+ null, XPath2FilterContainer._ATT_FILTER
+ ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
+ }
- /**
- * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
- *
- * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
- */
- public boolean isSubtract() {
-
- return this._constructionElement
- .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER)
- .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
- }
+ /**
+ * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+ *
+ * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+ */
+ public boolean isSubtract() {
+ return this.constructionElement.getAttributeNS(
+ null, XPath2FilterContainer._ATT_FILTER
+ ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
+ }
- /**
- * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
- *
- * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
- */
- public boolean isUnion() {
+ /**
+ * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
+ *
+ * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
+ */
+ public boolean isUnion() {
+ return this.constructionElement.getAttributeNS(
+ null, XPath2FilterContainer._ATT_FILTER
+ ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION);
+ }
- 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 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: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
- * @return the first Text node which contains information from the XPath 2 Filter String
- */
- public Node getXPathFilterTextNode() {
+ /**
+ * 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: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
+ * @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();
+ 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);
- }
- }
+ for (int i = 0; i < length; i++) {
+ if (children.item(i).getNodeType() == Node.TEXT_NODE) {
+ return children.item(i);
+ }
+ }
- return null;
- }
+ return null;
+ }
- /**
- * Method getBaseLocalName
- *
- * @return the XPATH2 tag
- */
- public final String getBaseLocalName() {
- return XPath2FilterContainer._TAG_XPATH2;
- }
+ /**
+ * 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.params;
-
-
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
import com.sun.org.apache.xml.internal.security.utils.ElementProxy;
@@ -31,237 +31,222 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-
/**
* Implements the parameters for the <A
* HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0</A>.
*
- * @author $Author: mullan $
+ * @author $Author: coheigea $
* @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
- * @see <A HREF="http://www.w3.org/Signature/Drafts/xmldsig-xfilter2/">XPath Filter v2.0 (editors copy)</A>
*/
-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
+ ) {
+ return new XPath2FilterContainer04(
+ doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
+ }
- /**
- * Creates a new XPath2FilterContainer04 with the filter type "subtract".
- *
- * @param doc
- * @param xpath2filter
- * @return the instance
- */
- public static XPath2FilterContainer04 newInstanceSubtract(Document doc,
- String xpath2filter) {
-
- return new XPath2FilterContainer04(doc, xpath2filter,
- XPath2FilterContainer04
- ._ATT_FILTER_VALUE_SUBTRACT);
- }
-
- /**
- * Creates a new XPath2FilterContainer04 with the filter type "union".
- *
- * @param doc
- * @param xpath2filter
- * @return the instance
- */
- public static XPath2FilterContainer04 newInstanceUnion(Document doc,
- String xpath2filter) {
+ /**
+ * 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_UNION);
- }
+ /**
+ * Creates a new XPath2FilterContainer04 with the filter type "union".
+ *
+ * @param doc
+ * @param xpath2filter
+ * @return the instance
+ */
+ public static XPath2FilterContainer04 newInstanceUnion(
+ Document doc, String xpath2filter
+ ) {
+ return new XPath2FilterContainer04(
+ doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
+ }
- /**
- * Creates a XPath2FilterContainer04 from an existing Element; needed for verification.
- *
- * @param element
- * @param BaseURI
- * @return the instance
- *
- * @throws XMLSecurityException
- */
- public static XPath2FilterContainer04 newInstance(
- Element element, String BaseURI) throws XMLSecurityException {
- return new XPath2FilterContainer04(element, BaseURI);
- }
+ /**
+ * 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 <code>true</code> if the <code>Filter</code> attribute has value "intersect".
- *
- * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
- */
- public boolean isIntersect() {
-
- return this._constructionElement
- .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER)
- .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
- }
+ /**
+ * Returns <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+ *
+ * @return <code>true</code> if the <code>Filter</code> attribute has value "intersect".
+ */
+ public boolean isIntersect() {
+ return this.constructionElement.getAttributeNS(
+ null, XPath2FilterContainer04._ATT_FILTER
+ ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
+ }
- /**
- * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
- *
- * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
- */
- public boolean isSubtract() {
-
- return this._constructionElement
- .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER)
- .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
- }
+ /**
+ * Returns <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+ *
+ * @return <code>true</code> if the <code>Filter</code> attribute has value "subtract".
+ */
+ public boolean isSubtract() {
+ return this.constructionElement.getAttributeNS(
+ null, XPath2FilterContainer04._ATT_FILTER
+ ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
+ }
- /**
- * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
- *
- * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
- */
- public boolean isUnion() {
+ /**
+ * Returns <code>true</code> if the <code>Filter</code> attribute has value "union".
+ *
+ * @return <code>true</code> if the <code>Filter</code> attribute has value "union".
+ */
+ public boolean isUnion() {
+ return this.constructionElement.getAttributeNS(
+ null, XPath2FilterContainer04._ATT_FILTER
+ ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
+ }
- 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 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: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
+ * @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();
- /**
- * 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: <XPath> here()<!-- comment -->/ds:Signature[1]</XPath>
- * @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;
+ }
- 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 getBaseLocalName() {
- return XPath2FilterContainer04._TAG_XPATH2;
- }
-
- /** @inheritDoc */
- public final String getBaseNamespace() {
- return XPath2FilterContainer04.XPathFilter2NS;
- }
+ /** @inheritDoc */
+ public final String getBaseNamespace() {
+ return XPath2FilterContainer04.XPathFilter2NS;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,27 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.transforms.params;
-
import com.sun.org.apache.xml.internal.security.transforms.TransformParam;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
@@ -29,7 +30,6 @@
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
-
/**
* This Object serves both as namespace prefix resolver and as container for
* the <CODE>ds:XPath</CODE> Element. It implements the {@link org.w3c.dom.Element} interface
@@ -39,45 +39,44 @@
*/
public class XPathContainer extends SignatureElementProxy implements TransformParam {
- /**
- * Constructor XPathContainer
- *
- * @param doc
- */
- public XPathContainer(Document doc) {
- super(doc);
- }
+ /**
+ * Constructor XPathContainer
+ *
+ * @param doc
+ */
+ public XPathContainer(Document doc) {
+ super(doc);
+ }
- /**
- * Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
- *
- * @param xpath
- */
- public void setXPath(String xpath) {
-
- if (this._constructionElement.getChildNodes() != null) {
- NodeList nl = this._constructionElement.getChildNodes();
+ /**
+ * Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
+ *
+ * @param xpath
+ */
+ public void setXPath(String xpath) {
+ if (this.constructionElement.getChildNodes() != null) {
+ NodeList nl = this.constructionElement.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++) {
- this._constructionElement.removeChild(nl.item(i));
- }
- }
+ 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 <CODE>ds:XPath</CODE> Element.
- *
- * @return the TEXT value of the <CODE>ds:XPath</CODE> Element.
- */
- public String getXPath() {
- return this.getTextFromTextChild();
- }
+ /**
+ * Returns the TEXT value of the <CODE>ds:XPath</CODE> Element.
+ *
+ * @return the TEXT value of the <CODE>ds:XPath</CODE> Element.
+ */
+ public String getXPath() {
+ return this.getTextFromTextChild();
+ }
- /** @inheritDoc */
- public String getBaseLocalName() {
- return Constants._TAG_XPATH;
- }
+ /** @inheritDoc */
+ public String getBaseLocalName() {
+ return Constants._TAG_XPATH;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,320 +2,315 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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 {
+
+ public static final String TRANSFORM_XPATHFILTERCHGP =
+ "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter";
- /** Field _ATT_FILTER_VALUE_INTERSECT */
- private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch";
+ /** Field _ATT_FILTER_VALUE_INTERSECT */
+ private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch";
- /** Field _ATT_FILTER_VALUE_SUBTRACT */
- private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch";
+ /** Field _ATT_FILTER_VALUE_SUBTRACT */
+ private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch";
- /** Field _ATT_FILTER_VALUE_UNION */
- private static final String _TAG_EXCLUDE = "Exclude";
+ /** Field _ATT_FILTER_VALUE_UNION */
+ private static final String _TAG_EXCLUDE = "Exclude";
- /** Field _TAG_XPATHCHGP */
- public static final String _TAG_XPATHCHGP = "XPathAlternative";
+ /** Field _TAG_XPATHCHGP */
+ public static final String _TAG_XPATHCHGP = "XPathAlternative";
- /** Field _ATT_INCLUDESLASH */
- public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy";
+ /** Field _ATT_INCLUDESLASH */
+ public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy";
- /** Field IncludeSlash */
- public static final boolean IncludeSlash = true;
+ /** Field IncludeSlash */
+ public static final boolean IncludeSlash = true;
- /** Field ExcludeSlash */
- public static final boolean ExcludeSlash = false;
+ /** Field ExcludeSlash */
+ public static final boolean ExcludeSlash = false;
- /**
- * Constructor XPathFilterCHGPContainer
- *
- */
- private XPathFilterCHGPContainer() {
-
- // 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) {
-
- super(doc);
+ /**
+ * Constructor XPathFilterCHGPContainer
+ *
+ * @param doc
+ * @param includeSlashPolicy
+ * @param includeButSearch
+ * @param excludeButSearch
+ * @param exclude
+ */
+ private XPathFilterCHGPContainer(
+ Document doc, boolean includeSlashPolicy, String includeButSearch,
+ String excludeButSearch, String exclude
+ ) {
+ super(doc);
- if (includeSlashPolicy) {
- this._constructionElement
- .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true");
- } else {
- this._constructionElement
- .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false");
- }
-
- if ((includeButSearch != null)
- && (includeButSearch.trim().length() > 0)) {
- Element includeButSearchElem =
- ElementProxy.createElementForFamily(doc, this.getBaseNamespace(),
- XPathFilterCHGPContainer
- ._TAG_INCLUDE_BUT_SEARCH);
+ if (includeSlashPolicy) {
+ this.constructionElement.setAttributeNS(
+ null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"
+ );
+ } else {
+ this.constructionElement.setAttributeNS(
+ null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"
+ );
+ }
- includeButSearchElem
- .appendChild(this._doc
- .createTextNode(indentXPathText(includeButSearch)));
- XMLUtils.addReturnToElement(this._constructionElement);
- this._constructionElement.appendChild(includeButSearchElem);
- }
+ if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) {
+ Element includeButSearchElem =
+ ElementProxy.createElementForFamily(
+ doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH
+ );
- if ((excludeButSearch != null)
- && (excludeButSearch.trim().length() > 0)) {
- Element excludeButSearchElem =
- ElementProxy.createElementForFamily(doc, this.getBaseNamespace(),
- XPathFilterCHGPContainer
- ._TAG_EXCLUDE_BUT_SEARCH);
+ includeButSearchElem.appendChild(
+ this.doc.createTextNode(indentXPathText(includeButSearch))
+ );
+ XMLUtils.addReturnToElement(this.constructionElement);
+ this.constructionElement.appendChild(includeButSearchElem);
+ }
- excludeButSearchElem
- .appendChild(this._doc
- .createTextNode(indentXPathText(excludeButSearch)));
- XMLUtils.addReturnToElement(this._constructionElement);
- this._constructionElement.appendChild(excludeButSearchElem);
- }
+ 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)));
- if ((exclude != null) && (exclude.trim().length() > 0)) {
- Element excludeElem = ElementProxy.createElementForFamily(doc,
- this.getBaseNamespace(),
- XPathFilterCHGPContainer._TAG_EXCLUDE);
+ XMLUtils.addReturnToElement(this.constructionElement);
+ this.constructionElement.appendChild(excludeButSearchElem);
+ }
- excludeElem
- .appendChild(this._doc.createTextNode(indentXPathText(exclude)));
- XMLUtils.addReturnToElement(this._constructionElement);
- this._constructionElement.appendChild(excludeElem);
- }
-
- XMLUtils.addReturnToElement(this._constructionElement);
- }
+ if ((exclude != null) && (exclude.trim().length() > 0)) {
+ Element excludeElem =
+ ElementProxy.createElementForFamily(
+ doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE);
- /**
- * Method indentXPathText
- *
- * @param xp
- * @return the string with enters
- */
- static String indentXPathText(String xp) {
+ excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude)));
+ XMLUtils.addReturnToElement(this.constructionElement);
+ this.constructionElement.appendChild(excludeElem);
+ }
- if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) {
- return "\n" + xp + "\n";
- }
- return xp;
-
- }
+ XMLUtils.addReturnToElement(this.constructionElement);
+ }
- /**
- * Constructor XPathFilterCHGPContainer
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- private XPathFilterCHGPContainer(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
- }
+ /**
+ * 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;
+ }
- /**
- * 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) {
+ /**
+ * Constructor XPathFilterCHGPContainer
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ private XPathFilterCHGPContainer(Element element, String BaseURI)
+ throws XMLSecurityException {
+ super(element, BaseURI);
+ }
- return new XPathFilterCHGPContainer(doc, includeSlashPolicy,
- includeButSearch, excludeButSearch,
- exclude);
- }
+ /**
+ * Creates a new XPathFilterCHGPContainer; needed for generation.
+ *
+ * @param doc
+ * @param includeSlashPolicy
+ * @param includeButSearch
+ * @param excludeButSearch
+ * @param exclude
+ * @return the created object
+ */
+ public static XPathFilterCHGPContainer getInstance(
+ Document doc, boolean includeSlashPolicy, String includeButSearch,
+ String excludeButSearch, String exclude
+ ) {
+ return new XPathFilterCHGPContainer(
+ doc, includeSlashPolicy, includeButSearch, excludeButSearch, exclude);
+ }
- /**
- * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification.
- *
- * @param element
- * @param BaseURI
- *
- * @throws XMLSecurityException
- * @return the created object.
- */
- public static XPathFilterCHGPContainer getInstance(
- Element element, String BaseURI) throws XMLSecurityException {
- return new XPathFilterCHGPContainer(element, BaseURI);
- }
-
- /**
- * Method getXStr
- *
- * @param type
- * @return The Xstr
- */
- private String getXStr(String type) {
-
- if (this.length(this.getBaseNamespace(), type) != 1) {
- return "";
- }
-
- Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(),
- type,0);
+ /**
+ * 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) {
+ if (this.length(this.getBaseNamespace(), type) != 1) {
+ return "";
+ }
- /**
- * Method getIncludeButSearch
- *
- * @return the string
- */
- public String getIncludeButSearch() {
- return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
- }
+ Element xElem =
+ XMLUtils.selectNode(
+ this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+ );
- /**
- * Method getExcludeButSearch
- *
- * @return the string
- */
- public String getExcludeButSearch() {
- return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
- }
+ return XMLUtils.getFullTextChildrenFromElement(xElem);
+ }
- /**
- * Method getExclude
- *
- * @return the string
- */
- public String getExclude() {
- return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE);
- }
+ /**
+ * Method getIncludeButSearch
+ *
+ * @return the string
+ */
+ public String getIncludeButSearch() {
+ return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
+ }
- /**
- * Method getIncludeSlashPolicy
- *
- * @return the string
- */
- public boolean getIncludeSlashPolicy() {
+ /**
+ * Method getExcludeButSearch
+ *
+ * @return the string
+ */
+ public String getExcludeButSearch() {
+ return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
+ }
- return this._constructionElement
- .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH)
- .equals("true");
- }
+ /**
+ * Method getExclude
+ *
+ * @return the string
+ */
+ public String getExclude() {
+ return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE);
+ }
- /**
- * 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: <XPath> he<!-- comment -->re()/ds:Signature[1]</XPath>
- * @param type
- * @return the first Text node which contains information from the XPath 2 Filter String
- */
- private Node getHereContextNode(String type) {
+ /**
+ * Method getIncludeSlashPolicy
+ *
+ * @return the string
+ */
+ public boolean getIncludeSlashPolicy() {
+ return this.constructionElement.getAttributeNS(
+ null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true");
+ }
- if (this.length(this.getBaseNamespace(), type) != 1) {
- return null;
- }
-
- return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(),
- type,0);
- }
+ /**
+ * 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: <XPath> he<!-- comment -->re()/ds:Signature[1]</XPath>
+ * @param type
+ * @return the first Text node which contains information from the XPath 2 Filter String
+ */
+ private Node getHereContextNode(String type) {
- /**
- * Method getHereContextNodeIncludeButSearch
- *
- * @return the string
- */
- public Node getHereContextNodeIncludeButSearch() {
- return this
- .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
- }
+ if (this.length(this.getBaseNamespace(), type) != 1) {
+ return null;
+ }
+
+ return XMLUtils.selectNodeText(
+ this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+ );
+ }
- /**
- * Method getHereContextNodeExcludeButSearch
- *
- * @return the string
- */
- public Node getHereContextNodeExcludeButSearch() {
- return this
- .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
- }
+ /**
+ * Method getHereContextNodeIncludeButSearch
+ *
+ * @return the string
+ */
+ public Node getHereContextNodeIncludeButSearch() {
+ return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH);
+ }
- /**
- * Method getHereContextNodeExclude
- *
- * @return the string
- */
- public Node getHereContextNodeExclude() {
- return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE);
- }
+ /**
+ * Method getHereContextNodeExcludeButSearch
+ *
+ * @return the string
+ */
+ public Node getHereContextNodeExcludeButSearch() {
+ return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH);
+ }
- /**
- * Method getBaseLocalName
- *
- * @inheritDoc
- */
- public final String getBaseLocalName() {
- return XPathFilterCHGPContainer._TAG_XPATHCHGP;
- }
+ /**
+ * Method getHereContextNodeExclude
+ *
+ * @return the string
+ */
+ public Node getHereContextNodeExclude() {
+ return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE);
+ }
- /**
- * Method getBaseNamespace
- *
- * @inheritDoc
- */
- public final String getBaseNamespace() {
- return Transforms.TRANSFORM_XPATHFILTERCHGP;
- }
+ /**
+ * Method getBaseLocalName
+ *
+ * @inheritDoc
+ */
+ public final String getBaseLocalName() {
+ return XPathFilterCHGPContainer._TAG_XPATHCHGP;
+ }
+
+ /**
+ * Method getBaseNamespace
+ *
+ * @inheritDoc
+ */
+ public final String getBaseNamespace() {
+ return TRANSFORM_XPATHFILTERCHGP;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.utils;
@@ -32,762 +34,765 @@
import org.w3c.dom.Node;
import org.w3c.dom.Text;
-
/**
* Implementation of MIME's Base64 encoding and decoding conversions.
* Optimized code. (raw version taken from oreilly.jonathan.util,
- * and currently com.sun.org.apache.xerces.internal.ds.util.Base64)
+ * 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 <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</A>
+ * @see <A HREF="ftp://ftp.isi.edu/in-notes/rfc2045.txt">RFC 2045</A>
* @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode
*/
public class Base64 {
-
- /** Field BASE64DEFAULTLENGTH */
- public static final int BASE64DEFAULTLENGTH = 76;
+ /** Field BASE64DEFAULTLENGTH */
+ public static final int BASE64DEFAULTLENGTH = 76;
- private Base64() {
- // we don't allow instantiation
- }
+ 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];
- /**
- * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
- * No sign-bit is outputed.
- *
- * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
- * retunrs eventually longer arrays because of the leading sign-bit.
- *
- * @param big <code>BigInteger<code> to be converted
- * @param bitlen <code>int<code> the desired length in bits of the representation
- * @return a byte array with <code>bitlen</code> bits of <code>big</code>
- */
- static final byte[] getBytes(BigInteger big, int bitlen) {
+ static {
+ for (int i = 0; i < BASELENGTH; i++) {
+ base64Alphabet[i] = -1;
+ }
+ for (int i = 'Z'; i >= 'A'; i--) {
+ base64Alphabet[i] = (byte) (i - 'A');
+ }
+ for (int i = 'z'; i>= 'a'; i--) {
+ base64Alphabet[i] = (byte) (i - 'a' + 26);
+ }
+
+ for (int i = '9'; i >= '0'; i--) {
+ base64Alphabet[i] = (byte) (i - '0' + 52);
+ }
+
+ base64Alphabet['+'] = 62;
+ base64Alphabet['/'] = 63;
+
+ for (int i = 0; i <= 25; i++) {
+ lookUpBase64Alphabet[i] = (char)('A' + i);
+ }
+
+ for (int i = 26, j = 0; i <= 51; i++, j++) {
+ lookUpBase64Alphabet[i] = (char)('a' + j);
+ }
- //round bitlen
- bitlen = ((bitlen + 7) >> 3) << 3;
+ for (int i = 52, j = 0; i <= 61; i++, j++) {
+ lookUpBase64Alphabet[i] = (char)('0' + j);
+ }
+ lookUpBase64Alphabet[62] = '+';
+ lookUpBase64Alphabet[63] = '/';
+ }
- if (bitlen < big.bitLength()) {
- throw new IllegalArgumentException(I18n
- .translate("utils.Base64.IllegalBitlength"));
- }
-
- byte[] bigBytes = big.toByteArray();
+ private Base64() {
+ // we don't allow instantiation
+ }
- if (((big.bitLength() % 8) != 0)
- && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
- return bigBytes;
- }
+ /**
+ * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
+ * No sign-bit is output.
+ *
+ * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
+ * returns eventually longer arrays because of the leading sign-bit.
+ *
+ * @param big <code>BigInteger<code> to be converted
+ * @param bitlen <code>int<code> the desired length in bits of the representation
+ * @return a byte array with <code>bitlen</code> bits of <code>big</code>
+ */
+ static final byte[] getBytes(BigInteger big, int bitlen) {
+
+ //round bitlen
+ bitlen = ((bitlen + 7) >> 3) << 3;
- // some copying needed
- int startSrc = 0; // no need to skip anything
- int bigLen = bigBytes.length; //valid length of the string
+ if (bitlen < big.bitLength()) {
+ throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
+ }
+
+ byte[] bigBytes = big.toByteArray();
- if ((big.bitLength() % 8) == 0) { // correct values
+ if (((big.bitLength() % 8) != 0)
+ && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+ return bigBytes;
+ }
+
+ // some copying needed
+ int startSrc = 0; // no need to skip anything
+ int bigLen = bigBytes.length; //valid length of the string
+
+ if ((big.bitLength() % 8) == 0) { // correct values
startSrc = 1; // skip sign bit
bigLen--; // valid length of the string
- }
+ }
+
+ int startDst = bitlen / 8 - bigLen; //pad with leading nulls
+ byte[] resizedBytes = new byte[bitlen / 8];
- int startDst = bitlen / 8 - bigLen; //pad with leading nulls
- byte[] resizedBytes = new byte[bitlen / 8];
+ System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
- System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
-
- return resizedBytes;
+ return resizedBytes;
+ }
- }
-
- /**
- * Encode in Base64 the given <code>{@link BigInteger}<code>.
- *
- * @param big
- * @return String with Base64 encoding
- */
- public static final String encode(BigInteger big) {
- return encode(getBytes(big, big.bitLength()));
- }
+ /**
+ * Encode in Base64 the given <code>{@link BigInteger}<code>.
+ *
+ * @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 <code>{@link BigInteger}<code>.
- * No sign-bit is outputed.
- *
- * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
- * retunrs eventually longer arrays because of the leading sign-bit.
- *
- * @param big <code>BigInteger<code> to be converted
- * @param bitlen <code>int<code> the desired length in bits of the representation
- * @return a byte array with <code>bitlen</code> bits of <code>big</code>
- */
- public static final byte[] encode(BigInteger big, int bitlen) {
+ /**
+ * Returns a byte-array representation of a <code>{@link BigInteger}<code>.
+ * No sign-bit is output.
+ *
+ * <b>N.B.:</B> <code>{@link BigInteger}<code>'s toByteArray
+ * returns eventually longer arrays because of the leading sign-bit.
+ *
+ * @param big <code>BigInteger<code> to be converted
+ * @param bitlen <code>int<code> the desired length in bits of the representation
+ * @return a byte array with <code>bitlen</code> bits of <code>big</code>
+ */
+ public static final byte[] encode(BigInteger big, int bitlen) {
- //round bitlen
- bitlen = ((bitlen + 7) >> 3) << 3;
+ //round bitlen
+ bitlen = ((bitlen + 7) >> 3) << 3;
- if (bitlen < big.bitLength()) {
- throw new IllegalArgumentException(I18n
- .translate("utils.Base64.IllegalBitlength"));
- }
+ if (bitlen < big.bitLength()) {
+ throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength"));
+ }
- byte[] bigBytes = big.toByteArray();
+ byte[] bigBytes = big.toByteArray();
- if (((big.bitLength() % 8) != 0)
- && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
- return bigBytes;
- }
+ 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
+ // 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
+ if ((big.bitLength() % 8) == 0) { // correct values
startSrc = 1; // skip sign bit
bigLen--; // valid length of the string
- }
+ }
+
+ int startDst = bitlen / 8 - bigLen; //pad with leading nulls
+ byte[] resizedBytes = new byte[bitlen / 8];
- int startDst = bitlen / 8 - bigLen; //pad with leading nulls
- byte[] resizedBytes = new byte[bitlen / 8];
+ System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen);
+
+ return resizedBytes;
+ }
- 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 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 (!XMLUtils.ignoreLineBreaks() && encodedInt.length() > BASE64DEFAULTLENGTH) {
+ encodedInt = "\n" + encodedInt + "\n";
+ }
- /**
- * 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()));
- }
+ Document doc = element.getOwnerDocument();
+ Text text = doc.createTextNode(encodedInt);
+
+ element.appendChild(text);
+ }
+
+ /**
+ * Method decode
+ *
+ * Takes the <CODE>Text</CODE> children of the Element and interprets
+ * them as input for the <CODE>Base64.decode()</CODE> 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;
- /**
- * 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) {
+ sb.append(t.getData());
+ }
+ sibling = sibling.getNextSibling();
+ }
+
+ return decode(sb.toString());
+ }
- String encodedInt = encode(biginteger);
-
- if (encodedInt.length() > 76) {
- encodedInt = "\n" + encodedInt + "\n";
- }
+ /**
+ * 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));
- Document doc = element.getOwnerDocument();
- Text text = doc.createTextNode(encodedInt);
+ el.appendChild(text);
- element.appendChild(text);
- }
+ return el;
+ }
- /**
- * Method decode
- *
- * Takes the <CODE>Text</CODE> children of the Element and interprets
- * them as input for the <CODE>Base64.decode()</CODE> 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 {
+ /**
+ * 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 <code>byte[]<code> to be base64 encoded
+ * @return the <code>String<code> with encoded data
+ */
+ public static final String encode(byte[] binaryData) {
+ return XMLUtils.ignoreLineBreaks()
+ ? encode(binaryData, Integer.MAX_VALUE)
+ : encode(binaryData, BASE64DEFAULTLENGTH);
+ }
- Node sibling = element.getFirstChild();
- StringBuffer sb = new StringBuffer();
-
- while (sibling!=null) {
- if (sibling.getNodeType() == Node.TEXT_NODE) {
- Text t = (Text) sibling;
+ /**
+ * 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 {
- sb.append(t.getData());
- }
- sibling=sibling.getNextSibling();
- }
+ byte[] retBytes = null;
+ UnsyncByteArrayOutputStream baos = null;
+ try {
+ baos = new UnsyncByteArrayOutputStream();
+ String line;
- return decode(sb.toString());
- }
+ 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);
+ }
- /**
- * 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) {
+ protected static final boolean isPad(byte octect) {
+ return (octect == PAD);
+ }
- Element el = XMLUtils.createElementInSignatureSpace(doc, localName);
- Text text = doc.createTextNode(encode(bytes));
+ /**
+ * 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 <code>byte[]</code> data to be encoded
+ * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4.
+ * @return a <code>String</code> with encoded data
+ */
+ public static final String encode(byte[] binaryData,int length) {
+ if (length < 4) {
+ length = Integer.MAX_VALUE;
+ }
- el.appendChild(text);
+ if (binaryData == null) {
+ return null;
+ }
- return el;
- }
+ 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];
- /**
- * 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);
- }
+ 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);
- /**
- * Encode a byte array and fold lines at the standard 76th character unless
- * ignore line breaks property is set.
- *
- * @param binaryData <code>byte[]<code> to be base64 encoded
- * @return the <code>String<code> with encoded data
- */
- public static final String encode(byte[] binaryData) {
- return XMLUtils.ignoreLineBreaks()
- ? encode(binaryData, Integer.MAX_VALUE)
- : encode(binaryData, BASE64DEFAULTLENGTH);
- }
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
- /**
- * 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();
- }
+ i++;
+ }
+ encodedData[encodedIndex++] = 0xa;
+ }
- 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<BASELENGTH; i++) {
- base64Alphabet[i] = -1;
- }
- for (int i = 'Z'; i >= 'A'; i--) {
- base64Alphabet[i] = (byte) (i-'A');
- }
- for (int i = 'z'; i>= 'a'; i--) {
- base64Alphabet[i] = (byte) ( i-'a' + 26);
- }
+ for (; i < numberTriplets; i++) {
+ b1 = binaryData[dataIndex++];
+ b2 = binaryData[dataIndex++];
+ b3 = binaryData[dataIndex++];
- 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);
+ l = (byte)(b2 & 0x0f);
+ k = (byte)(b1 & 0x03);
- for (int i = 52, j = 0; i<=61; i++, j++)
- lookUpBase64Alphabet[i] = (char)('0' + j);
- lookUpBase64Alphabet[62] = '+';
- lookUpBase64Alphabet[63] = '/';
-
- }
+ byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
- 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);
- }
+ byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);
+ byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc);
- /**
- * 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 <code>byte[]</code> data to be encoded
- * @param length <code>int<code> length of wrapped lines; No wrapping if less than 4.
- * @return a <code>String</code> with encoded data
- */
- public static final String encode(byte[] binaryData,int length) {
-
- if (length<4) {
- length=Integer.MAX_VALUE;
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
- if (binaryData == null)
- return null;
-
- 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;
- }
+ // 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);
- 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 ];
- }
+ byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
+ byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0);
- // 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 );
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
+ encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
+ encodedData[encodedIndex++] = PAD;
+ }
- 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] = 0xa;
- 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);
- }
+ return new String(encodedData);
+ }
/**
- * Decodes Base64 data into octects
+ * Decodes Base64 data into octets
*
* @param encoded String containing base64 encoded data
* @return byte array containing the decoded data
* @throws Base64DecodingException if there is a problem decoding the data
*/
- public final static byte[] decode(String encoded) throws Base64DecodingException {
-
- if (encoded == null)
- return null;
- byte []bytes=new byte[encoded.length()];
- int len=getBytesInternal(encoded, bytes);
+ 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];
+ }
- int i = 0;
- int encodedIndex = 0;
- int dataIndex = 0;
+ byte decodedData[] = null;
+ byte b1 = 0, b2 = 0, b3 = 0, b4 = 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
+ int i = 0;
+ int encodedIndex = 0;
+ int dataIndex = 0;
+
+ //decodedData = new byte[ (numberQuadruple)*3];
+ dataIndex = (numberQuadruple - 1) * 4;
+ encodedIndex = (numberQuadruple - 1) * 3;
+ //first last bits.
+ b1 = base64Alphabet[base64Data[dataIndex++]];
+ b2 = base64Alphabet[base64Data[dataIndex++]];
+ if ((b1==-1) || (b2==-1)) {
+ //if found "no data" just return null
+ throw new Base64DecodingException("decoding.general");
}
- byte d3,d4;
- b3 = base64Alphabet[d3=base64Data[dataIndex++]];
- b4 = base64Alphabet[d4=base64Data[dataIndex++]];
- if ((b3==-1 ) || (b4==-1) ) {
- //Check if they are PAD characters
- if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad]
- if ((b2 & 0xf) != 0)//last 4 bits should be zero
- throw new Base64DecodingException("decoding.general");
- decodedData = new byte[ encodedIndex + 1 ];
- decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ;
- } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad]
- if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
- throw new Base64DecodingException("decoding.general");
- decodedData = new byte[ encodedIndex + 2 ];
- decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 );
- decodedData[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
+ 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 {
+ decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ;
+ decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf));
+ decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 );
+ }
+ return decodedData;
+ }
- // remove white spaces
- if (len==-1)
- len = removeWhiteSpace(base64Data);
-
- if (len%FOURBYTE != 0) {
- throw new Base64DecodingException("decoding.divisible.four");
- //should be divisible by four
+ /**
+ * Decodes Base64 data into outputstream
+ *
+ * @param base64Data String containing Base64 data
+ * @param os the outputstream
+ * @throws IOException
+ * @throws Base64DecodingException
+ */
+ public static final void decode(String base64Data, OutputStream os)
+ throws Base64DecodingException, IOException {
+ byte[] bytes = new byte[base64Data.length()];
+ int len = getBytesInternal(base64Data, bytes);
+ decode(bytes,os,len);
}
- int numberQuadruple = (len/FOURBYTE );
+ /**
+ * Decodes Base64 data into outputstream
+ *
+ * @param base64Data Byte array containing Base64 data
+ * @param os the outputstream
+ * @throws IOException
+ * @throws Base64DecodingException
+ */
+ public static final void decode(byte[] base64Data, OutputStream os)
+ throws Base64DecodingException, IOException {
+ decode(base64Data,os,-1);
+ }
- if (numberQuadruple == 0)
- return;
+ protected static final void decode(byte[] base64Data, OutputStream os, int len)
+ throws Base64DecodingException, IOException {
+ // remove white spaces
+ if (len == -1) {
+ len = removeWhiteSpace(base64Data);
+ }
+
+ if (len % FOURBYTE != 0) {
+ throw new Base64DecodingException("decoding.divisible.four");
+ //should be divisible by four
+ }
+
+ int numberQuadruple = (len / FOURBYTE);
- //byte decodedData[] = null;
- byte b1=0,b2=0,b3=0, b4=0;
+ if (numberQuadruple == 0) {
+ return;
+ }
- int i = 0;
+ //byte decodedData[] = null;
+ byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
+
+ int i = 0;
+ int dataIndex = 0;
- int dataIndex = 0;
+ //the begin
+ for (i=numberQuadruple - 1; i > 0; i--) {
+ b1 = base64Alphabet[base64Data[dataIndex++]];
+ b2 = base64Alphabet[base64Data[dataIndex++]];
+ b3 = base64Alphabet[base64Data[dataIndex++]];
+ b4 = base64Alphabet[base64Data[dataIndex++]];
+ if ((b1 == -1) ||
+ (b2 == -1) ||
+ (b3 == -1) ||
+ (b4 == -1) ) {
+ //if found "no data" just return null
+ throw new Base64DecodingException("decoding.general");
+ }
- //the begin
- for (i=numberQuadruple-1; i>0; i--) {
+ os.write((byte)(b1 << 2 | b2 >> 4));
+ os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf)));
+ os.write( (byte)(b3 << 6 | b4));
+ }
b1 = base64Alphabet[base64Data[dataIndex++]];
b2 = base64Alphabet[base64Data[dataIndex++]];
- b3 = base64Alphabet[base64Data[dataIndex++]];
- b4 = base64Alphabet[base64Data[dataIndex++]];
- if ( (b1==-1) ||
- (b2==-1) ||
- (b3==-1) ||
- (b4==-1) )
- throw new Base64DecodingException("decoding.general");//if found "no data" just return null
-
-
- os.write((byte)( b1 <<2 | b2>>4 ) );
- os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
- os.write( (byte)( b3<<6 | b4 ));
- }
- b1 = base64Alphabet[base64Data[dataIndex++]];
- b2 = base64Alphabet[base64Data[dataIndex++]];
-
- // first last bits.
- if ((b1==-1) ||
- (b2==-1) ){
- throw new Base64DecodingException("decoding.general");//if found "no data" just return null
- }
-
- byte d3,d4;
- b3= base64Alphabet[d3 = base64Data[dataIndex++]];
- b4= base64Alphabet[d4 = base64Data[dataIndex++]];
- if ((b3==-1 ) ||
- (b4==-1) ) {//Check if they are PAD characters
- if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad]
- if ((b2 & 0xf) != 0)//last 4 bits should be zero
- throw new Base64DecodingException("decoding.general");
- os.write( (byte)( b1 <<2 | b2>>4 ) );
- } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad]
- if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
- throw new Base64DecodingException("decoding.general");
- os.write( (byte)( b1 <<2 | b2>>4 ));
- os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
- } else {
- throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
- }
- } else {
- //No PAD e.g 3cQl
- os.write((byte)( b1 <<2 | b2>>4 ) );
- os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ));
- os.write((byte)( b3<<6 | b4 ));
- }
- return ;
- }
-
- /**
- * Decodes Base64 data into outputstream
- *
- * @param is containing Base64 data
- * @param os the outputstream
- * @throws IOException
- * @throws Base64DecodingException
- */
- public final static void decode(InputStream is,
- OutputStream os) throws Base64DecodingException, IOException {
- //byte decodedData[] = null;
- byte b1=0,b2=0,b3=0, b4=0;
-
- int index=0;
- byte []data=new byte[4];
- int read;
- //the begin
- while ((read=is.read())>0) {
- byte readed=(byte)read;
- if (isWhiteSpace(readed)) {
- continue;
- }
- 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;
+ }
+
+ if ((data[index++] = readed) == -1) {
+ //if found "no data" just return null
+ throw new Base64DecodingException("decoding.general");
+ }
+
+ if (index != 4) {
+ continue;
+ }
+ index = 0;
+ b1 = base64Alphabet[data[0]];
+ b2 = base64Alphabet[data[1]];
+ b3 = base64Alphabet[data[2]];
+ b4 = base64Alphabet[data[3]];
+
+ os.write((byte)(b1 << 2 | b2 >> 4));
+ os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)));
+ os.write((byte)(b3 << 6 | b4));
+ }
- 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));
+ }
+ }
- 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;
+ /**
+ * remove WhiteSpace from MIME containing encoded Base64 data.
+ *
+ * @param data the byte array of base64 data (with WS)
+ * @return the new length
+ */
+ protected static final int removeWhiteSpace(byte[] data) {
+ if (data == null) {
+ return 0;
+ }
- // count characters that's not whitespace
- int newSize = 0;
- int len = data.length;
- for (int i = 0; i < len; i++) {
- byte dataS=data[i];
- if (!isWhiteSpace(dataS))
- data[newSize++] = dataS;
- }
- return newSize;
- }
+ // count characters that's not whitespace
+ int newSize = 0;
+ int len = data.length;
+ for (int i = 0; i < len; i++) {
+ byte dataS = data[i];
+ if (!isWhiteSpace(dataS)) {
+ data[newSize++] = dataS;
+ }
+ }
+ return newSize;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java Fri Jul 05 13:28:17 2013 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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<CachedXPathAPI> local=new ThreadLocal<CachedXPathAPI>();
- static ThreadLocal<Document> localDoc=new ThreadLocal<Document>();
-
- /**
- * 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;
- }
-}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java Fri Jul 05 13:28:17 2013 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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<XPath> 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");
- }
- }
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java Fri Jul 05 14:37:41 2013 -0700
@@ -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. <p/> This method will try to load the resource
+ * using the following methods (in order):
+ * <ul>
+ * <li>From Thread.currentThread().getContextClassLoader()
+ * <li>From ClassLoaderUtil.class.getClassLoader()
+ * <li>callingClass.getClassLoader()
+ * </ul>
+ *
+ * @param resourceName The name of the resource to load
+ * @param callingClass The Class object of the calling object
+ */
+ 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. <p/> This method will try to load the resources
+ * using the following methods (in order):
+ * <ul>
+ * <li>From Thread.currentThread().getContextClassLoader()
+ * <li>From ClassLoaderUtil.class.getClassLoader()
+ * <li>callingClass.getClassLoader()
+ * </ul>
+ *
+ * @param resourceName The name of the resource to load
+ * @param callingClass The Class object of the calling object
+ */
+ static List<URL> getResources(String resourceName, Class<?> callingClass) {
+ List<URL> ret = new ArrayList<URL>();
+ Enumeration<URL> urls = new Enumeration<URL>() {
+ 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. <p/> The
+ * algorithm used to find the resource is given in getResource()
+ *
+ * @param resourceName The name of the resource to load
+ * @param callingClass The Class object of the calling object
+ */
+ 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. <p/> It will try to load the class in the
+ * following order:
+ * <ul>
+ * <li>From Thread.currentThread().getContextClassLoader()
+ * <li>Using the basic Class.forName()
+ * <li>From ClassLoaderUtil.class.getClassLoader()
+ * <li>From the callingClass.getClassLoader()
+ * </ul>
+ *
+ * @param className The name of the class to load
+ * @param callingClass The Class object of the calling object
+ * @throws ClassNotFoundException If the class cannot be found anywhere.
+ */
+ static Class<?> loadClass(String className, Class<?> callingClass)
+ throws ClassNotFoundException {
+ try {
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+
+ if (cl != null) {
+ return cl.loadClass(className);
+ }
+ } catch (ClassNotFoundException e) {
+ 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;
+ }
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,26 +2,26 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-
/**
* Provides all constants and some translation functions for i18n.
*
@@ -29,202 +29,245 @@
* <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-TransformAlg">XML
* Signature specification</A>.
*
- * @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 exceptionMessagesResourceBundleDir */
+ public static final String exceptionMessagesResourceBundleDir =
+ "com/sun/org/apache/xml/internal/security/resource";
- /** Field configurationFileNew */
- public static final String configurationFileNew = ".xmlsecurityconfig";
+ /** Field exceptionMessagesResourceBundleBase is the location of the <CODE>ResourceBundle</CODE> */
+ public static final String exceptionMessagesResourceBundleBase =
+ exceptionMessagesResourceBundleDir + "/" + "xmlsecurity";
+
+ /**
+ * The URL of the
+ * <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
+ */
+ public static final String SIGNATURESPECIFICATION_URL =
+ "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
+
+ /**
+ * The namespace of the
+ * <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
+ */
+ public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#";
- /** Field exceptionMessagesResourceBundleDir */
- public static final String exceptionMessagesResourceBundleDir =
- "com/sun/org/apache/xml/internal/security/resource";
+ /**
+ * The namespace of the
+ * <A HREF="http://www.w3.org/TR/xmldsig-core1/">XML Signature specification</A>
+ */
+ public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#";
+
+ /** The URL for more algorithms **/
+ public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#";
+
+ /** The URI for XML spec*/
+ public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace";
+
+ /** The URI for XMLNS spec*/
+ public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/";
- /** Field exceptionMessagesResourceBundleBase is the location of the <CODE>ResourceBundle</CODE> */
- public static final String exceptionMessagesResourceBundleBase =
- exceptionMessagesResourceBundleDir + "/" + "xmlsecurity";
- //J-
- /**
- * The URL of the <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
- */
- 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";
- /**
- * The namespace of the <A HREF="http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/">XML Signature specification</A>
- */
- public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#";
- /** The URL for more algorithm **/
- public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#";
- /** The URI for XML spec*/
- public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace";
- /** The URI for XMLNS spec*/
- public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/";
+ /** Tag of Attr 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 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";
+ /** 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";
- // 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 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 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";
+ /** 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";
- /** Digest - Required SHA1 */
- public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1";
+ /** 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";
- /**
- * @see <A HREF="http://www.ietf.org/internet-drafts/draft-blake-wilson-xmldsig-ecdsa-02.txt">
- * draft-blake-wilson-xmldsig-ecdsa-02.txt</A>
- */
- public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1";
- //J+
+ /** Tag of Element X509Certificate **/
+ public static final String _TAG_X509CERTIFICATE = "X509Certificate";
+
+ /** Tag of Element X509CRL **/
+ public static final String _TAG_X509CRL = "X509CRL";
- private Constants() {
- // we don't allow instantiation
- }
+ /** 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";
- /**
- * Sets the namespace prefix which will be used to identify elements in the
- * XML Signature Namespace.
- *
- * <pre>
- * Constants.setSignatureSpecNSprefix("dsig");
- * </pre>
- *
- * @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 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";
- /**
- * Returns the XML namespace prefix which is used for elements in the XML
- * Signature namespace.
- *
- * It is defaulted to <code>dsig</code>, 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);
- }
+ /** Digest - Required SHA1 */
+ public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1";
+
+ /**
+ * @see <A HREF="http://www.ietf.org/internet-drafts/draft-blake-wilson-xmldsig-ecdsa-02.txt">
+ * draft-blake-wilson-xmldsig-ecdsa-02.txt</A>
+ */
+ 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
+ }
+
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java Fri Jul 05 14:37:41 2013 -0700
@@ -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<String, String> namespaceMap = new HashMap<String, String>();
+
+ 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<String> 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());
+ }
+ }
+ }
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
@@ -29,16 +31,16 @@
*
*/
public class DigesterOutputStream extends ByteArrayOutputStream {
+ private static final java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName());
+
final MessageDigestAlgorithm mda;
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger
- (DigesterOutputStream.class.getName());
/**
* @param mda
*/
public DigesterOutputStream(MessageDigestAlgorithm mda) {
- this.mda=mda;
+ this.mda = mda;
}
/** @inheritDoc */
@@ -55,9 +57,9 @@
public void write(byte[] arg0, int arg1, int arg2) {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Pre-digested input:");
- StringBuffer sb = new StringBuffer(arg2);
- for (int i=arg1; i<(arg1+arg2); i++) {
- sb.append((char) arg0[i]);
+ StringBuilder sb = new StringBuilder(arg2);
+ for (int i = arg1; i < (arg1 + arg2); i++) {
+ sb.append((char)arg0[i]);
}
log.log(java.util.logging.Level.FINE, sb.toString());
}
@@ -68,6 +70,6 @@
* @return the digest value
*/
public byte[] getDigestValue() {
- return mda.digest();
+ return mda.digest();
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java Fri Jul 05 14:37:41 2013 -0700
@@ -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);
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java Fri Jul 05 14:37:41 2013 -0700
@@ -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;
+ }
+
+ /** A checker for DOM that interns NS */
+ public static class InternedNsChecker extends ElementCheckerImpl {
+ public void guaranteeThatElementInCorrectSpace(
+ ElementProxy expected, Element actual
+ ) throws XMLSecurityException {
+
+ String expectedLocalname = expected.getBaseLocalName();
+ String expectedNamespace = expected.getBaseNamespace();
- String localnameSHOULDBE = expected.getBaseLocalName();
- String namespaceSHOULDBE = expected.getBaseNamespace();
+ String localnameIS = actual.getLocalName();
+ String namespaceIS = actual.getNamespaceURI();
+ if ((expectedNamespace != namespaceIS) ||
+ !expectedLocalname.equals(localnameIS)) {
+ Object exArgs[] = { namespaceIS + ":" + localnameIS,
+ expectedNamespace + ":" + expectedLocalname};
+ throw new XMLSecurityException("xml.WrongElement", exArgs);
+ }
+ }
+ }
+
+ /** A checker for DOM that interns NS */
+ public static class FullChecker extends ElementCheckerImpl {
- 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);
- }
- }
+ 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 {
- }
+ /** An empty checker if schema checking is used */
+ public static class EmptyChecker extends ElementCheckerImpl {
+ public void guaranteeThatElementInCorrectSpace(
+ ElementProxy expected, Element actual
+ ) throws XMLSecurityException {
+ // empty
}
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java Fri Jul 05 14:37:41 2013 -0700
@@ -45,13 +45,13 @@
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<String, String> prefixMappings = new ConcurrentHashMap<String, String>();
@@ -73,9 +73,9 @@
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 @@
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 @@
log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\"");
}
- this._doc = element.getOwnerDocument();
- this._constructionElement = element;
- this._baseURI = BaseURI;
+ this.doc = element.getOwnerDocument();
+ this.constructionElement = element;
+ this.baseURI = BaseURI;
}
@@ -196,7 +196,7 @@
* @return the Element which was constructed by the Object.
*/
public final Element getElement() {
- return this._constructionElement;
+ return this.constructionElement;
}
/**
@@ -208,9 +208,9 @@
HelperNodeList nl = new HelperNodeList();
- nl.appendChild(this._doc.createTextNode("\n"));
+ nl.appendChild(this.doc.createTextNode("\n"));
nl.appendChild(this.getElement());
- nl.appendChild(this._doc.createTextNode("\n"));
+ nl.appendChild(this.doc.createTextNode("\n"));
return nl;
}
@@ -221,7 +221,7 @@
* @return the Document where this element is contained.
*/
public Document getDocument() {
- return this._doc;
+ return this.doc;
}
/**
@@ -230,7 +230,7 @@
* @return the base uri of the namespace of this element
*/
public String getBaseURI() {
- return this._baseURI;
+ return this.baseURI;
}
/**
@@ -243,8 +243,8 @@
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 void addBigIntegerElement(BigInteger bi, String localname) {
if (bi != null) {
- Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
+ Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
Base64.fillElementWithBigInteger(e, bi);
- this._constructionElement.appendChild(e);
- XMLUtils.addReturnToElement(this._constructionElement);
+ this.constructionElement.appendChild(e);
+ XMLUtils.addReturnToElement(this.constructionElement);
}
}
@@ -278,11 +278,11 @@
*/
public void addBase64Element(byte[] bytes, String localname) {
if (bytes != null) {
- Element e = Base64.encodeToElement(this._doc, localname, bytes);
+ Element e = Base64.encodeToElement(this.doc, localname, bytes);
- this._constructionElement.appendChild(e);
+ this.constructionElement.appendChild(e);
if (!XMLUtils.ignoreLineBreaks()) {
- this._constructionElement.appendChild(this._doc.createTextNode("\n"));
+ this.constructionElement.appendChild(this.doc.createTextNode("\n"));
}
}
}
@@ -294,12 +294,12 @@
* @param localname
*/
public void addTextElement(String text, String localname) {
- Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname);
- Text t = this._doc.createTextNode(text);
+ Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
+ Text t = this.doc.createTextNode(text);
e.appendChild(t);
- this._constructionElement.appendChild(e);
- XMLUtils.addReturnToElement(this._constructionElement);
+ this.constructionElement.appendChild(e);
+ XMLUtils.addReturnToElement(this.constructionElement);
}
/**
@@ -310,9 +310,9 @@
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 void addText(String text) {
if (text != null) {
- Text t = this._doc.createTextNode(text);
+ Text t = this.doc.createTextNode(text);
- this._constructionElement.appendChild(t);
+ this.constructionElement.appendChild(t);
}
}
@@ -342,7 +342,7 @@
) throws Base64DecodingException {
return Base64.decodeBigIntegerFromText(
XMLUtils.selectNodeText(
- this._constructionElement.getFirstChild(), namespace, localname, 0
+ this.constructionElement.getFirstChild(), namespace, localname, 0
)
);
}
@@ -360,7 +360,7 @@
throws XMLSecurityException {
Element e =
XMLUtils.selectNode(
- this._constructionElement.getFirstChild(), namespace, localname, 0
+ this.constructionElement.getFirstChild(), namespace, localname, 0
);
return Base64.decode(e);
@@ -375,7 +375,7 @@
*/
public String getTextFromChildElement(String localname, String namespace) {
return XMLUtils.selectNode(
- this._constructionElement.getFirstChild(),
+ this.constructionElement.getFirstChild(),
namespace,
localname,
0).getTextContent();
@@ -388,7 +388,7 @@
* @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 @@
* element
*/
public String getTextFromTextChild() {
- return XMLUtils.getFullTextChildrenFromElement(this._constructionElement);
+ return XMLUtils.getFullTextChildrenFromElement(this.constructionElement);
}
/**
@@ -410,7 +410,7 @@
*/
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 @@
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 @@
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);
- }
- }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,179 +2,238 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
+public class EncryptionConstants {
+ // Attributes that exist in XML Signature in the same way
+ /** Tag of Attr Algorithm **/
+ public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM;
+ /** Tag of Attr Id**/
+ public static final String _ATT_ID = Constants._ATT_ID;
+
+ /** Tag of Attr Target **/
+ public static final String _ATT_TARGET = Constants._ATT_TARGET;
+
+ /** Tag of Attr Type **/
+ public static final String _ATT_TYPE = Constants._ATT_TYPE;
+
+ /** Tag of Attr URI **/
+ public static final String _ATT_URI = Constants._ATT_URI;
+
+ // Attributes new in XML Encryption
+ /** Tag of Attr encoding **/
+ public static final String _ATT_ENCODING = "Encoding";
+
+ /** Tag of Attr recipient **/
+ public static final String _ATT_RECIPIENT = "Recipient";
+
+ /** Tag of Attr mimetype **/
+ public static final String _ATT_MIMETYPE = "MimeType";
+
+ /** Tag of Element CarriedKeyName **/
+ public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName";
+
+ /** Tag of Element CipherData **/
+ public static final String _TAG_CIPHERDATA = "CipherData";
+
+ /** Tag of Element CipherReference **/
+ public static final String _TAG_CIPHERREFERENCE = "CipherReference";
+
+ /** Tag of Element CipherValue **/
+ public static final String _TAG_CIPHERVALUE = "CipherValue";
+
+ /** Tag of Element DataReference **/
+ public static final String _TAG_DATAREFERENCE = "DataReference";
+
+ /** Tag of Element EncryptedData **/
+ public static final String _TAG_ENCRYPTEDDATA = "EncryptedData";
+
+ /** Tag of Element EncryptedKey **/
+ public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey";
+
+ /** Tag of Element EncryptionMethod **/
+ public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod";
+
+ /** Tag of Element EncryptionProperties **/
+ public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties";
+
+ /** Tag of Element EncryptionProperty **/
+ public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty";
+
+ /** Tag of Element KeyReference **/
+ public static final String _TAG_KEYREFERENCE = "KeyReference";
+
+ /** Tag of Element KeySize **/
+ public static final String _TAG_KEYSIZE = "KeySize";
+
+ /** Tag of Element OAEPparams **/
+ public static final String _TAG_OAEPPARAMS = "OAEPparams";
+
+ /** Tag of Element 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
+ * <A HREF="http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/">
+ * XML Encryption Syntax and Processing</A> */
+ 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#";
-import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+ /** 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";
-/**
- *
- * @author $Author: mullan $
- */
-public class EncryptionConstants {
- //J-
- // Attributes that exist in XML Signature in the same way
- /** Tag of Attr Algorithm **/
- public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM;
- /** Tag of Attr Id**/
- public static final String _ATT_ID = Constants._ATT_ID;
- /** Tag of Attr Target **/
- public static final String _ATT_TARGET = Constants._ATT_TARGET;
- /** Tag of Attr Type **/
- public static final String _ATT_TYPE = Constants._ATT_TYPE;
- /** Tag of Attr URI **/
- public static final String _ATT_URI = Constants._ATT_URI;
-
- // Attributes new in XML Encryption
- /** Tag of Attr encoding **/
- public static final String _ATT_ENCODING = "Encoding";
- /** Tag of Attr recipient **/
- public static final String _ATT_RECIPIENT = "Recipient";
- /** Tag of Attr mimetype **/
- public static final String _ATT_MIMETYPE = "MimeType";
-
- /** Tag of Element CarriedKeyName **/
- public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName";
- /** Tag of Element CipherData **/
- public static final String _TAG_CIPHERDATA = "CipherData";
- /** Tag of Element CipherReference **/
- public static final String _TAG_CIPHERREFERENCE = "CipherReference";
- /** Tag of Element CipherValue **/
- public static final String _TAG_CIPHERVALUE = "CipherValue";
- /** Tag of Element DataReference **/
- public static final String _TAG_DATAREFERENCE = "DataReference";
- /** Tag of Element EncryptedData **/
- public static final String _TAG_ENCRYPTEDDATA = "EncryptedData";
- /** Tag of Element EncryptedKey **/
- public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey";
- /** Tag of Element EncryptionMethod **/
- public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod";
- /** Tag of Element EncryptionProperties **/
- public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties";
- /** Tag of Element EncryptionProperty **/
- public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty";
- /** Tag of Element KeyReference **/
- public static final String _TAG_KEYREFERENCE = "KeyReference";
- /** Tag of Element KeySize **/
- public static final String _TAG_KEYSIZE = "KeySize";
- /** Tag of Element OAEPparams **/
- public static final String _TAG_OAEPPARAMS = "OAEPparams";
- /** Tag of Element ReferenceList **/
- public static final String _TAG_REFERENCELIST = "ReferenceList";
- /** Tag of Element Transforms **/
- public static final String _TAG_TRANSFORMS = "Transforms";
- /** Tag of Element AgreementMethod **/
- public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod";
- /** Tag of Element KA-Nonce **/
- public static final String _TAG_KA_NONCE = "KA-Nonce";
- /** Tag of Element OriginatorKeyInfo **/
- public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo";
- /** Tag of Element RecipientKeyInfo **/
- public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo";
-
- /** Field ENCRYPTIONSPECIFICATION_URL */
- public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/";
-
- /** The namespace of the <A HREF="http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/">XML Encryption Syntax and Processing</A> */
- public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#";
+ private EncryptionConstants() {
+ // we don't allow instantiation
+ }
- /** URI for content*/
- public static final String TYPE_CONTENT = EncryptionSpecNS + "Content";
- /** URI for element*/
- public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element";
- /** URI for mediatype*/
- public static final String TYPE_MEDIATYPE = "http://www.isi.edu/in-notes/iana/assignments/media-types/"; // + "*/*";
-
- /** Block Encryption - REQUIRED TRIPLEDES */
- public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "tripledes-cbc";
- /** Block Encryption - REQUIRED AES-128 */
- public static final String ALGO_ID_BLOCKCIPHER_AES128 = EncryptionConstants.EncryptionSpecNS + "aes128-cbc";
- /** Block Encryption - REQUIRED AES-256 */
- public static final String ALGO_ID_BLOCKCIPHER_AES256 = EncryptionConstants.EncryptionSpecNS + "aes256-cbc";
- /** Block Encryption - OPTIONAL AES-192 */
- public static final String ALGO_ID_BLOCKCIPHER_AES192 = EncryptionConstants.EncryptionSpecNS + "aes192-cbc";
-
- /** Key Transport - REQUIRED RSA-v1.5*/
- public static final String ALGO_ID_KEYTRANSPORT_RSA15 = EncryptionConstants.EncryptionSpecNS + "rsa-1_5";
- /** Key Transport - REQUIRED RSA-OAEP */
- public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p";
-
- /** Key Agreement - OPTIONAL Diffie-Hellman */
- public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh";
-
- /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */
- public static final String ALGO_ID_KEYWRAP_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "kw-tripledes";
- /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */
- public static final String ALGO_ID_KEYWRAP_AES128 = EncryptionConstants.EncryptionSpecNS + "kw-aes128";
- /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */
- public static final String ALGO_ID_KEYWRAP_AES256 = EncryptionConstants.EncryptionSpecNS + "kw-aes256";
- /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */
- public static final String ALGO_ID_KEYWRAP_AES192 = EncryptionConstants.EncryptionSpecNS + "kw-aes192";
-
- /*
- // Message Digest - REQUIRED SHA1
- public static final String ALGO_ID_DIGEST_SHA160 = Constants.ALGO_ID_DIGEST_SHA1;
- // Message Digest - RECOMMENDED SHA256
- public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256";
- // Message Digest - OPTIONAL SHA512
- public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512";
- // Message Digest - OPTIONAL RIPEMD-160
- public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160";
- */
-
- /** Message Authentication - RECOMMENDED XML Digital Signature */
- public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/";
-
- /** Canonicalization - OPTIONAL Canonical XML with Comments */
- public static final String ALGO_ID_C14N_WITHCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
- /** Canonicalization - OPTIONAL Canonical XML (omits comments) */
- public static final String ALGO_ID_C14N_OMITCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
-
- /** Encoding - REQUIRED base64 */
- public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64";
- //J+
-
- private EncryptionConstants() {
- // we don't allow instantiation
- }
-
- /**
- * Method setEncryptionSpecNSprefix
- *
- * @param newPrefix
- * @throws XMLSecurityException
- */
- public static void setEncryptionSpecNSprefix(String newPrefix)
- throws XMLSecurityException {
- ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS,
- newPrefix);
- }
-
- /**
- * Method getEncryptionSpecNSprefix
- *
- * @return the prefix for this node.
- */
- public static String getEncryptionSpecNSprefix() {
- return ElementProxy
- .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS);
- }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,62 +2,62 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.utils;
@@ -28,75 +30,69 @@
import org.w3c.dom.NodeList;
/**
- *
* @author Christian Geuer-Pollmann
- *
*/
public class HelperNodeList implements NodeList {
- /** Field nodes */
- List<Node> nodes = new ArrayList<Node>(20);
- boolean _allNodesMustHaveSameParent = false;
+ /** Field nodes */
+ List<Node> nodes = new ArrayList<Node>();
+ 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) {
-
- // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes");
-
- return nodes.get(index);
- }
+ /**
+ * Method item
+ *
+ * @param index
+ * @return node with index i
+ */
+ public Node item(int index) {
+ return nodes.get(index);
+ }
- /**
- * Method getLength
- *
- * @return length of the list
- */
- public int getLength() {
- return nodes.size();
- }
+ /**
+ * Method 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));
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,85 +2,42 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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...
- * <BR />
- * The problem is that if you do not validate a document, you cannot use the
- * <CODE>getElementByID</CODE> 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 <CODE>@Id</CODE> attributes in an Element from the XML
- * Signature namespace are of type <CODE>ID</CODE>.
- *
- * @author $Author: mullan $
- * @see <A HREF="http://www.xml.com/lpt/a/2001/11/07/id.html">"Identity Crisis" on xml.com</A>
+ * 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<Document, Map<String, WeakReference<Element>>> docMap =
- new WeakHashMap<Document, Map<String, WeakReference<Element>>>();
-
- /**
- * 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<String, WeakReference<Element>> elementMap;
- synchronized (docMap) {
- elementMap = docMap.get(doc);
- if (elementMap == null) {
- elementMap = new WeakHashMap<String, WeakReference<Element>>();
- docMap.put(doc, elementMap);
- }
- }
- elementMap.put(idValue, new WeakReference<Element>(element));
+ // we don't allow instantiation
}
/**
@@ -90,7 +47,7 @@
* @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 @@
* @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<String, WeakReference<Element>> elementMap;
- synchronized (docMap) {
- elementMap = docMap.get(doc);
- }
- if (elementMap != null) {
- WeakReference<Element> weakReference = elementMap.get(id);
- if (weakReference != null) {
- return weakReference.get();
- }
- }
- return null;
- }
-
- private static java.util.List<String> 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;i<els.length;i++) {
- if (els[i]!=null) {
- return els[i];
- }
- }
- return null;
- }
-
- private static int getEl(Node currentNode,String id,Element []els) {
- Node sibling=null;
- Node parentNode=null;
- do {
- switch (currentNode.getNodeType()) {
- case Node.DOCUMENT_FRAGMENT_NODE :
- case Node.DOCUMENT_NODE :
- sibling= currentNode.getFirstChild();
- break;
-
-
- case Node.ELEMENT_NODE :
- Element currentElement = (Element) currentNode;
- if (isElement(currentElement, id, els)==1)
- return 1;
- sibling= currentNode.getFirstChild();
- if (sibling==null) {
- if (parentNode != null) {
- sibling= currentNode.getNextSibling();
- }
- } else {
- parentNode=currentElement;
- }
- break;
- } while (sibling==null && parentNode!=null) {
- sibling=parentNode.getNextSibling();
- parentNode=parentNode.getParentNode();
- if (parentNode != null && parentNode.getNodeType() != Node.ELEMENT_NODE) {
- parentNode=null;
- }
- }
- if (sibling==null)
- return 1;
- currentNode=sibling;
- sibling=currentNode.getNextSibling();
- } while(true);
-
- }
- public static int isElement(Element el, String id,Element[] els) {
- if (!el.hasAttributes()) {
- return 0;
- }
- NamedNodeMap ns=el.getAttributes();
- int elementIndex=names.indexOf(el.getNamespaceURI());
- elementIndex=(elementIndex<0) ? namesLength : elementIndex;
- for (int length=ns.getLength(), i=0; i<length; i++) {
- Attr n=(Attr)ns.item(i);
- String s=n.getNamespaceURI();
-
- int index=s==null ? elementIndex : names.indexOf(n.getNamespaceURI());
- index=(index<0) ? namesLength : index;
- String name=n.getLocalName();
- if (name == null)
- name = n.getName();
- if (name.length()>2)
- 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;
- }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,82 +2,80 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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);
}
+ if (IgnoreAllErrorHandler.throwExceptions) {
+ throw ex;
+ }
+ }
- /** @inheritDoc */
- public void error(SAXParseException ex) throws SAXException {
- if (IgnoreAllErrorHandler.warnOnExceptions) {
- log.log(java.util.logging.Level.SEVERE, "", ex);
- }
- if (IgnoreAllErrorHandler.throwExceptions) {
- throw ex;
- }
+ /** @inheritDoc */
+ public void error(SAXParseException ex) throws SAXException {
+ if (IgnoreAllErrorHandler.warnOnExceptions) {
+ log.log(java.util.logging.Level.SEVERE, "", ex);
}
+ if (IgnoreAllErrorHandler.throwExceptions) {
+ throw ex;
+ }
+ }
-
- /** @inheritDoc */
- public void fatalError(SAXParseException ex) throws SAXException {
- if (IgnoreAllErrorHandler.warnOnExceptions) {
- log.log(java.util.logging.Level.WARNING, "", ex);
- }
- if (IgnoreAllErrorHandler.throwExceptions) {
- throw ex;
- }
+ /** @inheritDoc */
+ public void fatalError(SAXParseException ex) throws SAXException {
+ if (IgnoreAllErrorHandler.warnOnExceptions) {
+ log.log(java.util.logging.Level.WARNING, "", ex);
}
+ if (IgnoreAllErrorHandler.throwExceptions) {
+ throw ex;
+ }
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,132 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import javax.xml.XMLConstants;
+import javax.xml.transform.TransformerException;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import javax.xml.xpath.XPathFactoryConfigurationException;
+
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * An implementation for XPath evaluation that uses the JDK API.
+ */
+public class JDKXPathAPI implements XPathAPI {
+
+ private XPathFactory xpf;
+
+ private String xpathStr;
+
+ private XPathExpression xpathExpression;
+
+ /**
+ * Use an XPath string to select a nodelist.
+ * XPath namespace prefixes are resolved from the namespaceNode.
+ *
+ * @param contextNode The node to start searching from.
+ * @param xpathnode
+ * @param str
+ * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+ * @return A NodeIterator, should never be null.
+ *
+ * @throws TransformerException
+ */
+ public NodeList selectNodeList(
+ Node contextNode, Node xpathnode, String str, Node namespaceNode
+ ) throws TransformerException {
+ if (!str.equals(xpathStr) || xpathExpression == null) {
+ if (xpf == null) {
+ xpf = XPathFactory.newInstance();
+ try {
+ xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+ } catch (XPathFactoryConfigurationException ex) {
+ throw new TransformerException("empty", ex);
+ }
+ }
+ XPath xpath = xpf.newXPath();
+ xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode));
+ xpathStr = str;
+ try {
+ xpathExpression = xpath.compile(xpathStr);
+ } catch (XPathExpressionException ex) {
+ throw new TransformerException("empty", ex);
+ }
+ }
+ try {
+ return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET);
+ } catch (XPathExpressionException ex) {
+ throw new TransformerException("empty", ex);
+ }
+ }
+
+ /**
+ * Evaluate an XPath string and return true if the output is to be included or not.
+ * @param contextNode The node to start searching from.
+ * @param xpathnode The XPath node
+ * @param str The XPath expression
+ * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+ */
+ public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+ throws TransformerException {
+ if (!str.equals(xpathStr) || xpathExpression == null) {
+ if (xpf == null) {
+ xpf = XPathFactory.newInstance();
+ try {
+ xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
+ } catch (XPathFactoryConfigurationException ex) {
+ throw new TransformerException("empty", ex);
+ }
+ }
+ XPath xpath = xpf.newXPath();
+ xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode));
+ xpathStr = str;
+ try {
+ xpathExpression = xpath.compile(xpathStr);
+ } catch (XPathExpressionException ex) {
+ throw new TransformerException("empty", ex);
+ }
+ }
+ try {
+ Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN);
+ return result.booleanValue();
+ } catch (XPathExpressionException ex) {
+ throw new TransformerException("empty", ex);
+ }
+ }
+
+ /**
+ * Clear any context information from this object
+ */
+ public void clear() {
+ xpathStr = null;
+ xpathExpression = null;
+ xpf = null;
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java Fri Jul 05 14:37:41 2013 -0700
@@ -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();
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.utils;
@@ -33,8 +35,8 @@
*/
public class JavaUtils {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(JavaUtils.class.getName());
private JavaUtils() {
@@ -45,7 +47,7 @@
* Method getBytesFromFile
*
* @param fileName
- * @return the bytes readed from the file
+ * @return the bytes read from the file
*
* @throws FileNotFoundException
* @throws IOException
@@ -55,9 +57,11 @@
byte refBytes[] = null;
- FileInputStream fisRef = new FileInputStream(fileName);
+ FileInputStream fisRef = null;
+ UnsyncByteArrayOutputStream baos = null;
try {
- UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
+ fisRef = new FileInputStream(fileName);
+ baos = new UnsyncByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
@@ -67,7 +71,12 @@
refBytes = baos.toByteArray();
} finally {
- fisRef.close();
+ if (baos != null) {
+ baos.close();
+ }
+ if (fisRef != null) {
+ fisRef.close();
+ }
}
return refBytes;
@@ -80,7 +89,6 @@
* @param bytes
*/
public static void writeBytesToFilename(String filename, byte[] bytes) {
-
FileOutputStream fos = null;
try {
if (filename != null && bytes != null) {
@@ -91,13 +99,19 @@
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 @@
* returns them as a byte array.
*
* @param inputStream
- * @return the bytes readed from the stream
+ * @return the bytes read from the stream
*
* @throws FileNotFoundException
* @throws IOException
*/
- public static byte[] getBytesFromStream(InputStream inputStream)
- throws IOException {
-
- byte refBytes[] = null;
+ public static byte[] getBytesFromStream(InputStream inputStream) throws IOException {
+ UnsyncByteArrayOutputStream baos = null;
- UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
- byte buf[] = new byte[1024];
- int len;
+ byte[] retBytes = null;
+ try {
+ baos = new UnsyncByteArrayOutputStream();
+ byte buf[] = new byte[4 * 1024];
+ int len;
- while ((len = inputStream.read(buf)) > 0) {
- baos.write(buf, 0, len);
+ while ((len = inputStream.read(buf)) > 0) {
+ baos.write(buf, 0, len);
+ }
+ retBytes = baos.toByteArray();
+ } finally {
+ baos.close();
}
- refBytes = baos.toByteArray();
- return refBytes;
+ return retBytes;
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,573 +2,473 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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());
- */
-
- static boolean _TOXML = true;
+ return rfctoXML(normalized);
+ }
- /**
- * Method rfc2253toXMLdsig
- *
- * @param dn
- * @return normalized string
- *
- */
- public static String rfc2253toXMLdsig(String dn) {
+ /**
+ * Method xmldsigtoRFC2253
+ *
+ * @param dn
+ * @return normalized string
+ */
+ public static String xmldsigtoRFC2253(String dn) {
+ // Transform from RFC1779 to RFC2253
+ String normalized = normalize(dn, false);
- _TOXML = true;
+ return xmltoRFC(normalized);
+ }
- // Transform from RFC1779 to RFC2253
- String normalized = normalize(dn);
-
- return rfctoXML(normalized);
- }
+ /**
+ * Method normalize
+ *
+ * @param dn
+ * @return normalized string
+ */
+ public static String normalize(String dn) {
+ return normalize(dn, true);
+ }
- /**
- * Method xmldsigtoRFC2253
- *
- * @param dn
- * @return normalized string
- */
- public static String xmldsigtoRFC2253(String 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 "";
+ }
- _TOXML = false;
-
- // Transform from RFC1779 to RFC2253
- String normalized = normalize(dn);
+ try {
+ String DN = semicolonToComma(dn);
+ StringBuilder sb = new StringBuilder();
+ int i = 0;
+ int l = 0;
+ int k;
- return xmltoRFC(normalized);
- }
+ //for name component
+ for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) {
+ l += countQuotes(DN, j, k);
+
+ if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) {
+ sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ",");
- /**
- * Method normalize
- *
- * @param dn
- * @return normalized string
- */
- public static String normalize(String dn) {
+ i = k + 1;
+ l = 0;
+ }
+ }
- //if empty string
- if ((dn == null) || dn.equals("")) {
- return "";
- }
+ sb.append(parseRDN(trim(DN.substring(i)), toXml));
+
+ return sb.toString();
+ } catch (IOException ex) {
+ return dn;
+ }
+ }
- try {
- String _DN = semicolonToComma(dn);
- StringBuffer sb = new StringBuffer();
- int i = 0;
- int l = 0;
- int k;
+ /**
+ * 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;
- //for name component
- for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) {
- l += countQuotes(_DN, j, k);
+ for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) {
+ l += countQuotes(str, j, k);
+
+ if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
+ sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+");
- 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(parseATAV(trim(str.substring(i)), toXml));
+
+ return sb.toString();
+ }
- sb.append(parseRDN(trim(_DN.substring(i))));
-
- return sb.toString();
- } catch (IOException ex) {
- return dn;
- }
- }
+ /**
+ * 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 parseRDN
- *
- * @param str
- * @return normalized string
- * @throws IOException
- */
- static String parseRDN(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);
+ }
+
+ return attrType + "=" + attrValue;
- 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);
+ /**
+ * Method normalizeAT
+ *
+ * @param str
+ * @return normalized string
+ */
+ static String normalizeAT(String str) {
- if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) {
- sb.append(parseATAV(trim(str.substring(i, k))) + "+");
+ String at = str.toUpperCase().trim();
+
+ if (at.startsWith("OID")) {
+ at = at.substring(3);
+ }
- i = k + 1;
- l = 0;
- }
- }
+ return at;
+ }
- sb.append(parseATAV(trim(str.substring(i))));
-
- return sb.toString();
- }
+ /**
+ * Method normalizeV
+ *
+ * @param str
+ * @param toXml
+ * @return normalized string
+ * @throws IOException
+ */
+ static String normalizeV(String str, boolean toXml) throws IOException {
+ String value = trim(str);
- /**
- * Method parseATAV
- *
- * @param str
- * @return normalized string
- * @throws IOException
- */
- static String parseATAV(String str) throws IOException {
+ if (value.startsWith("\"")) {
+ StringBuilder sb = new StringBuilder();
+ StringReader sr = new StringReader(value.substring(1, value.length() - 1));
+ int i = 0;
+ char c;
+
+ while ((i = sr.read()) > -1) {
+ c = (char) i;
- int i = str.indexOf("=");
+ //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253
+ if ((c == ',') || (c == '=') || (c == '+') || (c == '<')
+ || (c == '>') || (c == '#') || (c == ';')) {
+ sb.append('\\');
+ }
+
+ sb.append(c);
+ }
- 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));
- }
+ value = trim(sb.toString());
+ }
+
+ if (toXml) {
+ if (value.startsWith("#")) {
+ value = '\\' + value;
+ }
+ } else {
+ if (value.startsWith("\\#")) {
+ value = value.substring(1);
+ }
+ }
- return attrType + "=" + attrValue;
-
- }
+ return value;
+ }
- /**
- * Method normalizeAT
- *
- * @param str
- * @return normalized string
- */
- static String normalizeAT(String str) {
-
- String at = str.toUpperCase().trim();
+ /**
+ * Method rfctoXML
+ *
+ * @param string
+ * @return normalized string
+ */
+ static String rfctoXML(String string) {
+ try {
+ String s = changeLess32toXML(string);
- if (at.startsWith("OID")) {
- at = at.substring(3);
- }
+ return changeWStoXML(s);
+ } catch (Exception e) {
+ return string;
+ }
+ }
- return at;
- }
+ /**
+ * Method xmltoRFC
+ *
+ * @param string
+ * @return normalized string
+ */
+ static String xmltoRFC(String string) {
+ try {
+ String s = changeLess32toRFC(string);
- /**
- * Method normalizeV
- *
- * @param str
- * @return normalized string
- * @throws IOException
- */
- static String normalizeV(String str) throws IOException {
+ return changeWStoRFC(s);
+ } catch (Exception e) {
+ return string;
+ }
+ }
- String value = trim(str);
+ /**
+ * 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;
- if (value.startsWith("\"")) {
- StringBuffer sb = new StringBuffer();
- StringReader sr = new StringReader(value.substring(1,
- value.length() - 1));
- int i = 0;
- char c;
-
- for (; (i = sr.read()) > -1; ) {
+ 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('\\');
- }
-
- sb.append(c);
- }
-
- 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;
- }
- }
+ if (c == '\\') {
+ sb.append(c);
- /**
- * 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;
- }
- }
+ char c1 = (char) sr.read();
+ char c2 = (char) sr.read();
- /**
- * 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);
-
- sb.append(ch);
- } else {
- sb.append(c1);
- sb.append(c2);
- }
- } else {
- sb.append(c);
- }
- }
+ char ch = (char) Byte.parseByte("" + c1 + c2, 16);
- return sb.toString();
- }
+ sb.append(ch);
+ } else {
+ sb.append(c1);
+ sb.append(c2);
+ }
+ } else {
+ sb.append(c);
+ }
+ }
- /**
- * Method changeLess32toXML
- *
- * @param string
- * @return normalized string
- * @throws IOException
- */
- static String changeLess32toXML(String string) throws IOException {
-
- StringBuffer sb = new StringBuffer();
- StringReader sr = new StringReader(string);
- int i = 0;
+ return sb.toString();
+ }
- for (; (i = sr.read()) > -1; ) {
- if (i < 32) {
- sb.append('\\');
- sb.append(Integer.toHexString(i));
- } else {
- sb.append((char) i);
- }
- }
-
- return sb.toString();
- }
+ /**
+ * 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;
- /**
- * 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;
-
- for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) {
- sb.append(trim(string.substring(i, k)) + "\\ ");
+ while ((i = sr.read()) > -1) {
+ c = (char) i;
- i = k + 3;
- }
+ if (c == '\\') {
+ char c1 = (char) sr.read();
- sb.append(string.substring(i));
+ if (c1 == ' ') {
+ sb.append('\\');
- return sb.toString();
- }
+ String s = "20";
- /**
- * Method semicolonToComma
- *
- * @param str
- * @return normalized string
- */
- static String semicolonToComma(String str) {
- return removeWSandReplace(str, ";", ",");
- }
+ sb.append(s);
+ } else {
+ sb.append('\\');
+ sb.append(c1);
+ }
+ } else {
+ sb.append(c);
+ }
+ }
+
+ 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;
+ }
+
+ sb.append(string.substring(i));
- for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) {
- l += countQuotes(str, j, k);
-
- if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) {
- sb.append(trim(str.substring(i, k)) + replace);
-
- i = k + 1;
- l = 0;
- }
- }
-
- sb.append(trim(str.substring(i)));
-
- return sb.toString();
- }
+ return sb.toString();
+ }
- /**
- * Returns the number of Quotation from i to j
- *
- * @param s
- * @param i
- * @param j
- * @return number of quotes
- */
- private static int countQuotes(String s, int i, int j) {
-
- int k = 0;
-
- for (int l = i; l < j; l++) {
- if (s.charAt(l) == '"') {
- k++;
- }
- }
+ /**
+ * Method semicolonToComma
+ *
+ * @param str
+ * @return normalized string
+ */
+ static String semicolonToComma(String str) {
+ return removeWSandReplace(str, ";", ",");
+ }
- 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();
+ /**
+ * Method removeWhiteSpace
+ *
+ * @param str
+ * @param symbol
+ * @return normalized string
+ */
+ static String removeWhiteSpace(String str, String symbol) {
+ return removeWSandReplace(str, symbol, symbol);
+ }
- if ((str.length() > i) && trimed.endsWith("\\")
- &&!trimed.endsWith("\\\\")) {
- if (str.charAt(i) == ' ') {
- trimed = trimed + " ";
- }
- }
+ /**
+ * 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;
- return trimed;
- }
+ for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) {
+ l += countQuotes(str, j, k);
- /**
- * Method main
- *
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
+ if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) {
+ sb.append(trim(str.substring(i, k)) + replace);
- 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");
+ i = k + 1;
+ l = 0;
+ }
+ }
- {
- StringBuffer sb = new StringBuffer();
+ sb.append(trim(str.substring(i)));
+
+ return sb.toString();
+ }
- 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();
+ /**
+ * 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;
- sb.append('L');
- sb.append('u');
- sb.append('\uc48d');
- sb.append('i');
- sb.append('\uc487');
+ for (int l = i; l < j; l++) {
+ if (s.charAt(l) == '"') {
+ k++;
+ }
+ }
- String test7 = "SN=" + sb.toString();
+ return k;
+ }
- testToRFC(test7);
- }
- }
-
- /** Field i */
- static int counter = 0;
+ //only for the end of a space character occurring at the end of the string from rfc2253
- /**
- * Method test
- *
- * @param st
- */
- static void testToXML(String st) {
-
- System.out.println("start " + counter++ + ": " + st);
- System.out.println(" " + rfc2253toXMLdsig(st));
- System.out.println("");
- }
+ /**
+ * Method trim
+ *
+ * @param str
+ * @return the string
+ */
+ static String trim(String str) {
- /**
- * Method testToRFC
- *
- * @param st
- */
- static void testToRFC(String st) {
+ String trimed = str.trim();
+ int i = str.indexOf(trimed) + trimed.length();
- System.out.println("start " + counter++ + ": " + st);
- System.out.println(" " + xmldsigtoRFC2253(st));
- System.out.println("");
- }
+ if ((str.length() > i) && trimed.endsWith("\\")
+ && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) {
+ trimed = trimed + " ";
+ }
+
+ return trimed;
+ }
+
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java Fri Jul 05 14:37:41 2013 -0700
@@ -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;
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,70 +2,69 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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");
- }
+
+ protected SignatureElementProxy() {
+ };
- this._doc = doc;
- this._constructionElement = XMLUtils.createElementInSignatureSpace(this._doc,
- this.getBaseLocalName());
- }
+ /**
+ * Constructor SignatureElementProxy
+ *
+ * @param doc
+ */
+ public SignatureElementProxy(Document doc) {
+ if (doc == null) {
+ throw new RuntimeException("Document is null");
+ }
- /**
- * Constructor SignatureElementProxy
- *
- * @param element
- * @param BaseURI
- * @throws XMLSecurityException
- */
- public SignatureElementProxy(Element element, String BaseURI)
- throws XMLSecurityException {
- super(element, BaseURI);
+ this.doc = doc;
+ this.constructionElement =
+ XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName());
+ }
- }
+ /**
+ * Constructor SignatureElementProxy
+ *
+ * @param element
+ * @param BaseURI
+ * @throws XMLSecurityException
+ */
+ public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException {
+ super(element, BaseURI);
- /** @inheritDoc */
- public String getBaseNamespace() {
- return Constants.SignatureSpecNS;
- }
+ }
+
+ /** @inheritDoc */
+ public String getBaseNamespace() {
+ return Constants.SignatureSpecNS;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
@@ -30,53 +32,50 @@
*
*/
public class SignerOutputStream extends ByteArrayOutputStream {
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(SignerOutputStream.class.getName());
+
final SignatureAlgorithm sa;
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger
- (SignerOutputStream.class.getName());
/**
* @param sa
*/
public SignerOutputStream(SignatureAlgorithm sa) {
- this.sa=sa;
+ this.sa = sa;
}
/** @inheritDoc */
public void write(byte[] arg0) {
- super.write(arg0, 0, arg0.length);
try {
sa.update(arg0);
} catch (XMLSignatureException e) {
- throw new RuntimeException(""+e);
+ throw new RuntimeException("" + e);
}
}
/** @inheritDoc */
public void write(int arg0) {
- super.write(arg0);
try {
sa.update((byte)arg0);
} catch (XMLSignatureException e) {
- throw new RuntimeException(""+e);
+ throw new RuntimeException("" + e);
}
}
/** @inheritDoc */
public void write(byte[] arg0, int arg1, int arg2) {
- super.write(arg0, arg1, arg2);
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:");
- StringBuffer sb = new StringBuffer(arg2);
- for (int i=arg1; i<(arg1+arg2); i++) {
- sb.append((char) arg0[i]);
+ StringBuilder sb = new StringBuilder(arg2);
+ for (int i = arg1; i < (arg1 + arg2); i++) {
+ sb.append((char)arg0[i]);
}
log.log(java.util.logging.Level.FINE, sb.toString());
}
try {
- sa.update(arg0,arg1,arg2);
+ sa.update(arg0, arg1, arg2);
} catch (XMLSignatureException e) {
- throw new RuntimeException(""+e);
+ throw new RuntimeException("" + e);
}
}
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
@@ -24,75 +26,73 @@
import java.io.OutputStream;
/**
- * A class that buffers writte without synchronize its methods
+ * A class that buffers without synchronizing its methods
* @author raul
- *
*/
public class UnsyncBufferedOutputStream extends OutputStream {
- final OutputStream out;
+ static final int size = 8*1024;
+
+ private int pointer = 0;
+ private final OutputStream out;
+
+ private final byte[] buf;
- final byte[] buf;
- static final int size=8*1024;
- private static ThreadLocal<byte[]> bufCahce = new ThreadLocal<byte[]>() {
- protected synchronized byte[] initialValue() {
- return new byte[size];
- }
- };
- int pointer=0;
- /**
- * Creates a buffered output stream without synchronization
- * @param out the outputstream to buffer
- */
- public UnsyncBufferedOutputStream(OutputStream out) {
- buf=bufCahce.get();
- this.out=out;
- }
+ /**
+ * 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) throws IOException {
+ write(arg0, 0, arg0.length);
+ }
- /** @inheritDoc */
- public void write(byte[] arg0, int arg1, int len) throws IOException {
- int newLen=pointer+len;
- if (newLen> size) {
- flushBuffer();
- if (len>size) {
- out.write(arg0,arg1,len);
- return;
- }
- newLen=len;
- }
- System.arraycopy(arg0,arg1,buf,pointer,len);
- pointer=newLen;
+ /** @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;
-
+ private void flushBuffer() throws IOException {
+ if (pointer > 0) {
+ out.write(buf, 0, pointer);
}
+ pointer = 0;
- /** @inheritDoc */
- public void write(int arg0) throws IOException {
- if (pointer>= size) {
- flushBuffer();
- }
- buf[pointer++]=(byte)arg0;
+ }
+ /** @inheritDoc */
+ public void 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 flush() throws IOException {
+ flushBuffer();
+ out.flush();
+ }
+
+ /** @inheritDoc */
+ public void close() throws IOException {
+ flush();
+ out.close();
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2010 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
@@ -28,22 +30,21 @@
*
*/
public class UnsyncByteArrayOutputStream extends OutputStream {
+
private static final int INITIAL_SIZE = 8192;
- private static ThreadLocal<byte[]> bufCache = new ThreadLocal<byte[]>() {
- protected synchronized byte[] initialValue() {
- return new byte[INITIAL_SIZE];
- }
- };
private byte[] buf;
private int size = INITIAL_SIZE;
private int pos = 0;
public UnsyncByteArrayOutputStream() {
- buf = bufCache.get();
+ buf = new byte[INITIAL_SIZE];
}
public void write(byte[] arg0) {
+ if ((Integer.MAX_VALUE - pos) < arg0.length) {
+ throw new OutOfMemoryError();
+ }
int newPos = pos + arg0.length;
if (newPos > size) {
expandSize(newPos);
@@ -53,6 +54,9 @@
}
public void write(byte[] arg0, int arg1, int arg2) {
+ if ((Integer.MAX_VALUE - pos) < arg2) {
+ throw new OutOfMemoryError();
+ }
int newPos = pos + arg2;
if (newPos > size) {
expandSize(newPos);
@@ -62,6 +66,9 @@
}
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 @@
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);
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,35 +2,34 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils;
-
import java.io.IOException;
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
@@ -42,10 +41,9 @@
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
+import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
-
-
/**
* DOM and XML accessibility and comfort functions.
*
@@ -53,28 +51,31 @@
*/
public class XMLUtils {
- private static boolean ignoreLineBreaks =
- AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
- public Boolean run() {
- return Boolean.getBoolean
- ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks");
- }
- });
+ private static boolean ignoreLineBreaks =
+ AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
+ 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
@@ -85,6 +86,14 @@
}
/**
+ * 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 @@
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;
+ }
- /**
- * @param rootNode
- * @param result
- * @param exclude
- * @param com wheather comments or not
- */
- public static void getSet(Node rootNode,Set<Node> result,Node exclude ,boolean com) {
- if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){
- return;
- }
- getSetRec(rootNode,result,exclude,com);
- }
+ public static Element getNextElement(Node el) {
+ Node node = el;
+ while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) {
+ node = node.getNextSibling();
+ }
+ return (Element)node;
+ }
+
+ /**
+ * @param rootNode
+ * @param result
+ * @param exclude
+ * @param com whether comments or not
+ */
+ public static void getSet(Node rootNode, Set<Node> 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<Node> 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<nl.getLength();i++) {
- result.add(nl.item(i));
- }
+ @SuppressWarnings("fallthrough")
+ private static void getSetRec(final Node rootNode, final Set<Node> 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}. <I>If an Exception is
- * thrown during execution, it's StackTrace is output to System.out, but the
- * Exception is not re-thrown.</I>
- *
- * @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}. <I>If an Exception is
+ * thrown during execution, it's StackTrace is output to System.out, but the
+ * Exception is not re-thrown.</I>
+ *
+ * @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("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8"));
+ }
- try {
- if (addPreamble) {
- os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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 <CODE>contextNode</CODE> into the OutputStream, <I>but
+ * suppresses all Exceptions</I>.
+ * <BR />
+ * NOTE: <I>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
+ * <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
+ *
+ * @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 <CODE>contextNode</CODE> into the OutputStream, <I>but
- * supresses all Exceptions</I>.
- * <BR />
- * NOTE: <I>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
- * <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
- *
- * @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) {
+ /**
+ * Method getFullTextChildrenFromElement
+ *
+ * @param element
+ * @return the string of children
+ */
+ public static String getFullTextChildrenFromElement(Element element) {
+ StringBuilder sb = new StringBuilder();
- // throw new RuntimeException(ex.getMessage());
- } catch (InvalidCanonicalizerException 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 (CanonicalizationException ex) {
-
- // throw new RuntimeException(ex.getMessage());
- }
- }
-
+ return sb.toString();
+ }
- /**
- * Method getFullTextChildrenFromElement
- *
- * @param element
- * @return the string of chi;ds
- */
- public static String getFullTextChildrenFromElement(Element element) {
+ /**
+ * 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");
+ }
- StringBuffer sb = new StringBuffer();
- NodeList children = element.getChildNodes();
- int iMax = children.getLength();
+ if ((dsPrefix == null) || (dsPrefix.length() == 0)) {
+ return doc.createElementNS(Constants.SignatureSpecNS, elementName);
+ }
+ return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName);
+ }
- for (int i = 0; i < iMax; i++) {
- Node curr = children.item(i);
-
- if (curr.getNodeType() == Node.TEXT_NODE) {
- sb.append(((Text) curr).getData());
- }
- }
+ /**
+ * 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");
+ }
- return sb.toString();
- }
-
- static Map<String, String> namePrefixes=new HashMap<String, String>();
+ if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) {
+ return doc.createElementNS(Constants.SignatureSpec11NS, elementName);
+ }
+ return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName);
+ }
- /**
- * Creates an Element in the XML 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) {
+ /**
+ * Creates an Element in the XML Encryption specification namespace.
+ *
+ * @param doc the factory Document
+ * @param elementName the local name of the Element
+ * @return the Element
+ */
+ public static Element createElementInEncryptionSpace(Document doc, String elementName) {
+ if (doc == null) {
+ throw new RuntimeException("Document is null");
+ }
- if (doc == null) {
- throw new RuntimeException("Document is null");
- }
+ if ((xencPrefix == null) || (xencPrefix.length() == 0)) {
+ return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName);
+ }
+ return
+ doc.createElementNS(
+ EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName
+ );
+ }
- 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);
- }
+ /**
+ * Creates an Element in the XML Encryption 1.1 specification namespace.
+ *
+ * @param doc the factory Document
+ * @param elementName the local name of the Element
+ * @return the Element
+ */
+ public static Element createElementInEncryption11Space(Document doc, String elementName) {
+ if (doc == null) {
+ throw new RuntimeException("Document is null");
+ }
+
+ if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) {
+ return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName);
+ }
+ return
+ doc.createElementNS(
+ EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName
+ );
+ }
/**
* Returns true if the element is in XML Signature namespace and the local
@@ -290,14 +358,33 @@
*
* @param element
* @param localName
- * @return true if the element is in XML Signature namespace and the local name equals the supplied one
+ * @return true if the element is in XML Signature namespace and the local name equals
+ * the supplied one
*/
public static boolean elementIsInSignatureSpace(Element element, String localName) {
+ if (element == null){
+ return false;
+ }
+
+ return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
+ && element.getLocalName().equals(localName);
+ }
+
+ /**
+ * Returns true if the element is in XML Signature 1.1 namespace and the local
+ * name equals the supplied one.
+ *
+ * @param element
+ * @param localName
+ * @return true if the element is in XML Signature namespace and the local name equals
+ * the supplied one
+ */
+ public static boolean elementIsInSignature11Space(Element element, String localName) {
if (element == null) {
return false;
}
- return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
+ return Constants.SignatureSpec11NS.equals(element.getNamespaceURI())
&& element.getLocalName().equals(localName);
}
@@ -307,42 +394,58 @@
*
* @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 <I>always</I> returns a
- * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
- * 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 <I>always</I> returns a
+ * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
+ * 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 <I>always</I> returns a
* {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
* if the {@link Node} is a {@link Document}.
@@ -351,23 +454,23 @@
* @return the owner document
*/
public static Document getOwnerDocument(Set<Node> 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 @@
* @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");
+ }
+
+ Element ctx = doc.createElementNS(null, "namespaceContext");
+
+ ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace);
+
+ return ctx;
+ }
- if ((prefix == null) || (prefix.trim().length() == 0)) {
- throw new IllegalArgumentException("You must supply a prefix");
- }
+ /**
+ * Method addReturnToElement
+ *
+ * @param e
+ */
+ public static void addReturnToElement(Element e) {
+ if (!ignoreLineBreaks) {
+ Document doc = e.getOwnerDocument();
+ e.appendChild(doc.createTextNode("\n"));
+ }
+ }
- Element ctx = doc.createElementNS(null, "namespaceContext");
+ 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);
+ }
+ }
- ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(),
- namespace);
+ /**
+ * Method convertNodelistToSet
+ *
+ * @param xpathNodeSet
+ * @return the set with the nodelist
+ */
+ public static Set<Node> convertNodelistToSet(NodeList xpathNodeSet) {
+ if (xpathNodeSet == null) {
+ return new HashSet<Node>();
+ }
- return ctx;
+ int length = xpathNodeSet.getLength();
+ Set<Node> set = new HashSet<Node>(length);
+
+ for (int i = 0; i < length; i++) {
+ set.add(xpathNodeSet.item(i));
+ }
+
+ return set;
}
- /**
- * Method addReturnToElement
- *
- * @param e
- */
- public static void addReturnToElement(Element e) {
-
- if (!ignoreLineBreaks) {
- Document doc = e.getOwnerDocument();
- e.appendChild(doc.createTextNode("\n"));
- }
- }
-
- public static void addReturnToElement(Document doc, HelperNodeList nl) {
- if (!ignoreLineBreaks) {
- nl.appendChild(doc.createTextNode("\n"));
- }
- }
-
- public static void addReturnBeforeChild(Element e, Node child) {
- if (!ignoreLineBreaks) {
- Document doc = e.getOwnerDocument();
- e.insertBefore(doc.createTextNode("\n"), child);
- }
- }
-
- /**
- * Method convertNodelistToSet
- *
- * @param xpathNodeSet
- * @return the set with the nodelist
- */
- public static Set<Node> convertNodelistToSet(NodeList xpathNodeSet) {
+ /**
+ * 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 <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
+ * Namespace axis resolution is not XPath compliant </A>
+ */
+ public static void circumventBug2650(Document doc) {
- if (xpathNodeSet == null) {
- return new HashSet<Node>();
- }
-
- int length = xpathNodeSet.getLength();
- Set<Node> set = new HashSet<Node>(length);
+ Element documentElement = doc.getDocumentElement();
- for (int i = 0; i < length; i++) {
- set.add(xpathNodeSet.item(i));
- }
-
- return set;
- }
-
+ // 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 <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">Namespace axis resolution is not XPath compliant </A>
- */
- public static void circumventBug2650(Document doc) {
+ if (xmlnsAttr == null) {
+ documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
+ }
- Element documentElement = doc.getDocumentElement();
-
- // if the document element has no xmlns definition, we add xmlns=""
- Attr xmlnsAttr =
- documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");
+ XMLUtils.circumventBug2650internal(doc);
+ }
- if (xmlnsAttr == null) {
- documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
- }
-
- XMLUtils.circumventBug2650internal(doc);
- }
-
- /**
- * This is the work horse for {@link #circumventBug2650}.
- *
- * @param node
- * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">Namespace axis resolution is not XPath compliant </A>
- */
- @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 <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
+ * Namespace axis resolution is not XPath compliant </A>
+ */
+ @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 (Node child = element.getFirstChild(); child!=null;
+ child = child.getNextSibling()) {
- for (int i = 0; i < attributesLength; i++) {
- Attr currentAttr = (Attr) attributes.item(i);
- if (namespaceNs!=currentAttr.getNamespaceURI())
+ if (child.getNodeType() != Node.ELEMENT_NODE) {
+ continue;
+ }
+ Element childElement = (Element) child;
+
+ for (int i = 0; i < attributesLength; i++) {
+ Attr currentAttr = (Attr) attributes.item(i);
+ if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
continue;
- if (childElement.hasAttributeNS(namespaceNs,
- currentAttr.getLocalName())) {
- continue;
+ }
+ if (childElement.hasAttributeNS(namespaceNs,
+ currentAttr.getLocalName())) {
+ continue;
+ }
+ childElement.setAttributeNS(namespaceNs,
+ currentAttr.getName(),
+ currentAttr.getNodeValue());
}
- 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) {
@@ -558,6 +657,26 @@
* @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
+ * @param number
* @return nodes with the constrain
*/
public static Element selectXencNode(Node sibling, String nodeName, int number) {
@@ -574,42 +693,61 @@
return null;
}
- /**
- * @param sibling
- * @param nodeName
- * @param number
- * @return nodes with the constrain
- */
- public static Text selectDsNodeText(Node sibling, String nodeName, int number) {
- Node n=selectDsNode(sibling,nodeName,number);
- if (n==null) {
- return null;
+
+ /**
+ * @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 @@
* @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<Element> list = new ArrayList<Element>();
while (sibling != null) {
if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
@@ -659,73 +806,117 @@
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<Node> excludeNodeFromSet(Node signatureElement, Set<Node> inputSet) {
- Set<Node> resultSet = new HashSet<Node>();
- Iterator<Node> iterator = inputSet.iterator();
+ Set<Node> resultSet = new HashSet<Node>();
+ Iterator<Node> 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();
+
+ 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();
+ }
- if (ctx == descendantOrSelf) {
- return true;
- }
+ return null;
+ }
- Node parent = descendantOrSelf;
-
- while (true) {
- if (parent == null) {
- return false;
- }
+ /**
+ * 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 == ctx) {
- return true;
- }
+ Node parent = descendantOrSelf;
+
+ while (true) {
+ if (parent == null) {
+ return false;
+ }
- if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
- parent = ((Attr) parent).getOwnerElement();
- } else {
- parent = parent.getParentNode();
- }
- }
- }
+ if (parent == ctx) {
+ return true;
+ }
+
+ if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
+ parent = ((Attr) parent).getOwnerElement();
+ } else {
+ parent = parent.getParentNode();
+ }
+ }
+ }
public static boolean ignoreLineBreaks() {
return ignoreLineBreaks;
}
/**
- * This method is a tree-search to help prevent against wrapping attacks.
- * It checks that no two Elements have ID Attributes that match the "value"
- * argument, if this is the case then "false" is returned. Note that a
- * return value of "true" does not necessarily mean that a matching Element
- * has been found, just that no wrapping attack has been detected.
+ * 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.
+ *
+ * <p>This works around a limitation of the DOM
+ * <code>Element.getAttributeNode</code> 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 @@
}
/**
- * 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 @@
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;
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,66 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import javax.xml.transform.TransformerException;
+
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * An interface to abstract XPath evaluation
+ */
+public interface XPathAPI {
+
+ /**
+ * Use an XPath string to select a nodelist.
+ * XPath namespace prefixes are resolved from the namespaceNode.
+ *
+ * @param contextNode The node to start searching from.
+ * @param xpathnode
+ * @param str
+ * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+ * @return A NodeIterator, should never be null.
+ *
+ * @throws TransformerException
+ */
+ NodeList selectNodeList(
+ Node contextNode, Node xpathnode, String str, Node namespaceNode
+ ) throws TransformerException;
+
+ /**
+ * Evaluate an XPath string and return true if the output is to be included or not.
+ * @param contextNode The node to start searching from.
+ * @param xpathnode The XPath node
+ * @param str The XPath expression
+ * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+ */
+ boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+ throws TransformerException;
+
+ /**
+ * Clear any context information from this object
+ */
+ void clear();
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java Fri Jul 05 14:37:41 2013 -0700
@@ -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();
+
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java Fri Jul 05 13:28:17 2013 -0700
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -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 <CODE>here()</CODE> function.
- * <BR>
- * 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 <a href="http://www.w3.org/TR/xpath">XPath Specification</a>
- */
-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 "";
- }
-}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java Fri Jul 05 14:37:41 2013 -0700
@@ -0,0 +1,210 @@
+/*
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
+ */
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package com.sun.org.apache.xml.internal.security.utils;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.SourceLocator;
+import javax.xml.transform.TransformerException;
+
+import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere;
+import com.sun.org.apache.xml.internal.utils.PrefixResolver;
+import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;
+import com.sun.org.apache.xpath.internal.Expression;
+import com.sun.org.apache.xpath.internal.XPath;
+import com.sun.org.apache.xpath.internal.XPathContext;
+import com.sun.org.apache.xpath.internal.compiler.FunctionTable;
+import com.sun.org.apache.xpath.internal.objects.XObject;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * An implementation of XPathAPI using Xalan. This supports the "here()" function defined in the digital
+ * signature spec.
+ */
+public class XalanXPathAPI implements XPathAPI {
+
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName());
+
+ private String xpathStr = null;
+
+ private XPath xpath = null;
+
+ private static FunctionTable funcTable = null;
+
+ private static boolean installed;
+
+ private XPathContext context;
+
+ static {
+ fixupFunctionTable();
+ }
+
+
+ /**
+ * Use an XPath string to select a nodelist.
+ * XPath namespace prefixes are resolved from the namespaceNode.
+ *
+ * @param contextNode The node to start searching from.
+ * @param xpathnode
+ * @param str
+ * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+ * @return A NodeIterator, should never be null.
+ *
+ * @throws TransformerException
+ */
+ public NodeList selectNodeList(
+ Node contextNode, Node xpathnode, String str, Node namespaceNode
+ ) throws TransformerException {
+
+ // Execute the XPath, and have it return the result
+ XObject list = eval(contextNode, xpathnode, str, namespaceNode);
+
+ // Return a NodeList.
+ return list.nodelist();
+ }
+
+ /**
+ * Evaluate an XPath string and return true if the output is to be included or not.
+ * @param contextNode The node to start searching from.
+ * @param xpathnode The XPath node
+ * @param str The XPath expression
+ * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces.
+ */
+ public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+ throws TransformerException {
+ XObject object = eval(contextNode, xpathnode, str, namespaceNode);
+ return object.bool();
+ }
+
+ /**
+ * Clear any context information from this object
+ */
+ public void clear() {
+ xpathStr = null;
+ xpath = null;
+ context = null;
+ }
+
+ public synchronized static boolean isInstalled() {
+ return installed;
+ }
+
+ private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode)
+ throws TransformerException {
+ if (context == null) {
+ context = new XPathContext(xpathnode);
+ context.setSecureProcessing(true);
+ }
+
+ // Create an object to resolve namespace prefixes.
+ // XPath namespaces are resolved from the input context node's document element
+ // if it is a root node, or else the current context node (for lack of a better
+ // resolution space, given the simplicity of this sample code).
+ Node resolverNode =
+ (namespaceNode.getNodeType() == Node.DOCUMENT_NODE)
+ ? ((Document) namespaceNode).getDocumentElement() : namespaceNode;
+ PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode);
+
+ if (!str.equals(xpathStr)) {
+ if (str.indexOf("here()") > 0) {
+ context.reset();
+ }
+ xpath = createXPath(str, prefixResolver);
+ xpathStr = str;
+ }
+
+ // Execute the XPath, and have it return the result
+ int ctxtNode = context.getDTMHandleFromNode(contextNode);
+
+ return xpath.execute(context, ctxtNode, prefixResolver);
+ }
+
+ private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException {
+ XPath xpath = null;
+ Class<?>[] classes = new Class<?>[]{String.class, SourceLocator.class, PrefixResolver.class, int.class,
+ ErrorListener.class, FunctionTable.class};
+ Object[] objects =
+ new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable};
+ try {
+ Constructor<?> constructor = XPath.class.getConstructor(classes);
+ xpath = (XPath) constructor.newInstance(objects);
+ } catch (Exception ex) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, ex.getMessage(), ex);
+ }
+ }
+ if (xpath == null) {
+ xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null);
+ }
+ return xpath;
+ }
+
+ private synchronized static void fixupFunctionTable() {
+ installed = false;
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Registering Here function");
+ }
+ /**
+ * Try to register our here() implementation as internal function.
+ */
+ try {
+ Class<?>[] args = {String.class, Expression.class};
+ Method installFunction = FunctionTable.class.getMethod("installFunction", args);
+ if ((installFunction.getModifiers() & Modifier.STATIC) != 0) {
+ Object[] params = {"here", new FuncHere()};
+ installFunction.invoke(null, params);
+ installed = true;
+ }
+ } catch (Exception ex) {
+ log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex);
+ }
+ if (!installed) {
+ try {
+ funcTable = new FunctionTable();
+ Class<?>[] args = {String.class, Class.class};
+ Method installFunction = FunctionTable.class.getMethod("installFunction", args);
+ Object[] params = {"here", FuncHere.class};
+ installFunction.invoke(funcTable, params);
+ installed = true;
+ } catch (Exception ex) {
+ log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex);
+ }
+ }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ if (installed) {
+ log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName()
+ + " for XPath function 'here()' function in internal table");
+ } else {
+ log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName()
+ + " for XPath function 'here()' function in internal table");
+ }
+ }
+ }
+
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java Fri Jul 05 14:37:41 2013 -0700
@@ -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();
+ }
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java Fri Jul 05 14:37:41 2013 -0700
@@ -85,8 +85,14 @@
* @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 <N> ResourceResolver internalGetInstance(ResourceResolverContext context)
+ throws ResourceResolverException {
synchronized (resolverList) {
for (ResourceResolver resolver : resolverList) {
ResourceResolver resolverTmp = resolver;
@@ -95,9 +101,9 @@
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 @@
);
}
- 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 @@
}
}
- 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 @@
);
}
+ ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation);
+
// first check the individual Resolvers
if (individualResolvers != null) {
for (int i = 0; i < individualResolvers.size(); i++) {
@@ -176,15 +184,14 @@
log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass);
}
- resolver.resolverSpi.secureValidation = secureValidation;
- if (resolver.canResolve(uri, baseURI)) {
+ if (resolver.canResolve(context)) {
return resolver;
}
}
}
}
- return getInstance(uri, baseURI, secureValidation);
+ return internalGetInstance(context);
}
/**
@@ -270,6 +277,15 @@
}
/**
+ * @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
*
* @param uri
@@ -278,9 +294,10 @@
*
* @throws ResourceResolverException
*/
- public XMLSignatureInput resolve(Attr uri, String baseURI)
+ public XMLSignatureInput resolve(Attr uri, String baseURI, boolean secureValidation)
throws ResourceResolverException {
- return resolverSpi.engineResolve(uri, baseURI);
+ ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation);
+ return resolverSpi.engineResolveURI(context);
}
/**
@@ -338,7 +355,7 @@
* @param baseURI
* @return true if it can resolve the uri
*/
- private boolean canResolve(Attr uri, String baseURI) {
- return resolverSpi.engineCanResolve(uri, baseURI);
+ private boolean canResolve(ResourceResolverContext context) {
+ return this.resolverSpi.engineCanResolveURI(context);
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java Fri Jul 05 14:37:41 2013 -0700
@@ -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;
+}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,144 +2,137 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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;
+
+ private Attr uri = null;
+
+ private String baseURI = null;
- super(_msgID);
+ /**
+ * Constructor ResourceResolverException
+ *
+ * @param msgID
+ * @param uri
+ * @param baseURI
+ */
+ public ResourceResolverException(String msgID, Attr uri, String baseURI) {
+ super(msgID);
- 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) {
+ /**
+ * Constructor ResourceResolverException
+ *
+ * @param msgID
+ * @param exArgs
+ * @param uri
+ * @param baseURI
+ */
+ public ResourceResolverException(String msgID, Object exArgs[], Attr uri,
+ String baseURI) {
+ super(msgID, exArgs);
- super(_msgID, exArgs);
-
- this._uri = uri;
- this._BaseURI = BaseURI;
- }
+ this.uri = uri;
+ this.baseURI = baseURI;
+ }
- /**
- * Constructor ResourceResolverException
- *
- * @param _msgID
- * @param _originalException
- * @param uri
- * @param BaseURI
- */
- public ResourceResolverException(String _msgID, Exception _originalException,
- Attr uri, String BaseURI) {
+ /**
+ * Constructor ResourceResolverException
+ *
+ * @param msgID
+ * @param originalException
+ * @param uri
+ * @param baseURI
+ */
+ public ResourceResolverException(String msgID, Exception originalException,
+ Attr uri, String baseURI) {
+ super(msgID, originalException);
- 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;
+ }
- String _BaseURI;
-
- /**
- *
- * @param BaseURI
- */
- public void setBaseURI(String BaseURI) {
- this._BaseURI = BaseURI;
- }
+ /**
+ *
+ * @param baseURI
+ */
+ public void setbaseURI(String baseURI) {
+ this.baseURI = baseURI;
+ }
- /**
- *
- * @return the basUri
- */
- public String getBaseURI() {
- return this._BaseURI;
- }
- //J+
+ /**
+ *
+ * @return the baseURI
+ */
+ public String getbaseURI() {
+ return this.baseURI;
+ }
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,192 +2,239 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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<String, String> properties = null;
- /** Field _properties */
- protected java.util.Map<String,String> _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<String,String>();
- }
- 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<String, String>();
+ }
+ properties.put(key, value);
+ }
+
+ /**
+ * Method engineGetProperty
+ *
+ * @param key
+ * @return the value of the property
+ */
+ public String engineGetProperty(String key) {
+ if (properties == null) {
+ return null;
+ }
+ return properties.get(key);
+ }
- /**
- *
- * @param properties
- */
- public void engineAddProperies(Map<String,String> properties) {
- if (properties!=null) {
- if (_properties==null) {
- _properties=new HashMap<String,String>();
- }
- 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);
+ /**
+ *
+ * @param newProperties
+ */
+ public void engineAddProperies(Map<String, String> newProperties) {
+ if (newProperties != null && !newProperties.isEmpty()) {
+ if (properties == null) {
+ properties = new HashMap<String, String>();
+ }
+ properties.putAll(newProperties);
+ }
+ }
+
+ /**
+ * Tells if the implementation does can be reused by several threads safely.
+ * It normally means that the implementation does not have any member, or there is
+ * member change between engineCanResolve & engineResolve invocations. Or it maintains all
+ * member info in ThreadLocal methods.
+ */
+ public boolean engineIsThreadSafe() {
+ return false;
+ }
+
+ /**
+ * This method helps the {@link ResourceResolver} to decide whether a
+ * {@link ResourceResolverSpi} is able to perform the requested action.
+ *
+ * @param uri
+ * @param BaseURI
+ * @return true if the engine can resolve the uri
+ *
+ * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)}
+ */
+ @Deprecated
+ public boolean engineCanResolve(Attr uri, String BaseURI) {
+ // This method used to be abstract, so any calls to "super" are bogus.
+ throw new UnsupportedOperationException();
+ }
- /**
- * Method engineGetPropertyKeys
- *
- * @return the property keys
- */
- public String[] engineGetPropertyKeys() {
- return new String[0];
- }
+ /**
+ * This method helps the {@link ResourceResolver} to decide whether a
+ * {@link ResourceResolverSpi} is able to perform the requested action.
+ *
+ * <p>New clients should override this method, and not override {@link #engineCanResolve(Attr, String)}
+ * </p>
+ * @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 understandsProperty
- *
- * @param propertyToTest
- * @return true if understands the property
- */
- public boolean understandsProperty(String propertyToTest) {
-
- String[] understood = this.engineGetPropertyKeys();
+ /**
+ * Method engineGetPropertyKeys
+ *
+ * @return the property keys
+ */
+ public String[] engineGetPropertyKeys() {
+ return new String[0];
+ }
- if (understood != null) {
- for (int i = 0; i < understood.length; i++) {
- if (understood[i].equals(propertyToTest)) {
- return true;
+ /**
+ * Method understandsProperty
+ *
+ * @param propertyToTest
+ * @return true if understands the property
+ */
+ public boolean understandsProperty(String propertyToTest) {
+ String[] understood = this.engineGetPropertyKeys();
+
+ if (understood != null) {
+ for (int i = 0; i < understood.length; i++) {
+ if (understood[i].equals(propertyToTest)) {
+ return true;
+ }
}
- }
- }
+ }
- return false;
- }
+ return false;
+ }
- /**
- * Fixes a platform dependent filename to standard URI form.
- *
- * @param str The string to fix.
- *
- * @return Returns the fixed URI string.
- */
- public static String fixURI(String str) {
+ /**
+ * 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 != '/'));
+ // 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))
+ if (isDosFilename && 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);
+ // Windows fix
+ if (str.length() >= 2) {
+ char ch1 = str.charAt(1);
- if (ch1 == ':') {
- char ch0 = Character.toUpperCase(str.charAt(0));
+ if (ch1 == ':') {
+ char ch0 = Character.toUpperCase(str.charAt(0));
- if (('A' <= ch0) && (ch0 <= 'Z')) {
- str = "/" + str;
+ if (('A' <= ch0) && (ch0 <= 'Z')) {
+ str = "/" + str;
+ }
}
- }
- }
+ }
- // done
- return str;
- }
+ // done
+ return str;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java Fri Jul 05 14:37:41 2013 -0700
@@ -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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.utils.resolver.implementations;
@@ -27,51 +29,56 @@
import java.io.InputStream;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
/**
- *
- * @author $Author: mullan $
+ * @author $Author: coheigea $
*/
-
public class ResolverAnonymous extends ResourceResolverSpi {
- private XMLSignatureInput _input = null;
+ private InputStream inStream = null;
- /**
- * @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];
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,38 +2,42 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.utils.resolver.implementations;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.net.InetSocketAddress;
import java.net.MalformedURLException;
+import java.net.Proxy;
+import java.net.URISyntaxException;
+import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
-import com.sun.org.apache.xml.internal.utils.URI;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.Base64;
+import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi;
-import org.w3c.dom.Attr;
-
/**
* A simple ResourceResolver for HTTP requests. This class handles only 'pure'
@@ -51,253 +55,219 @@
* resourceResolver.setProperty("http.proxy.password", "secretca");
* </PRE>
*
- *
- * @author $Author: mullan $
* @see <A HREF="http://www.javaworld.com/javaworld/javatips/jw-javatip42_p.html">Java Tip 42: Write Java apps that work with proxy-based firewalls</A>
* @see <A HREF="http://java.sun.com/j2se/1.4/docs/guide/net/properties.html">SUN J2SE docs for network properties</A>
* @see <A HREF="http://metalab.unc.edu/javafaq/javafaq.html#proxy">The JAVA FAQ Question 9.5: How do I make Java work with a proxy server?</A>
- * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!?
*/
public class ResolverDirectHTTP extends ResourceResolverSpi {
- /** {@link java.util.logging} logging facility */
- static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(
- ResolverDirectHTTP.class.getName());
-
- /** Field properties[] */
- private static final String properties[] =
- { "http.proxy.host", "http.proxy.port",
- "http.proxy.username",
- "http.proxy.password",
- "http.basic.username",
- "http.basic.password" };
+ /** {@link org.apache.commons.logging} logging facility */
+ private static java.util.logging.Logger log =
+ java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName());
- /** Field HttpProxyHost */
- private static final int HttpProxyHost = 0;
-
- /** Field HttpProxyPort */
- private static final int HttpProxyPort = 1;
-
- /** Field HttpProxyUser */
- private static final int HttpProxyUser = 2;
-
- /** Field HttpProxyPass */
- private static final int HttpProxyPass = 3;
-
- /** Field HttpProxyUser */
- private static final int HttpBasicUser = 4;
+ /** Field 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 HttpProxyPass */
- private static final int HttpBasicPass = 5;
+ /** Field HttpProxyHost */
+ private static final int HttpProxyHost = 0;
+
+ /** Field HttpProxyPort */
+ private static final int HttpProxyPort = 1;
- 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 {
+ /** Field HttpProxyUser */
+ private static final int HttpProxyUser = 2;
- try {
- boolean useProxy = false;
- String proxyHost =
- engineGetProperty(ResolverDirectHTTP
- .properties[ResolverDirectHTTP.HttpProxyHost]);
- String proxyPort =
- engineGetProperty(ResolverDirectHTTP
- .properties[ResolverDirectHTTP.HttpProxyPort]);
+ /** Field HttpProxyPass */
+ private static final int HttpProxyPass = 3;
+
+ /** Field HttpProxyUser */
+ private static final int HttpBasicUser = 4;
- if ((proxyHost != null) && (proxyPort != null)) {
- useProxy = true;
- }
+ /** Field HttpProxyPass */
+ private static final int HttpBasicPass = 5;
- 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);
+ @Override
+ public boolean engineIsThreadSafe() {
+ return true;
+ }
- // 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();
-
- {
+ /**
+ * 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 {
- // 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);
+
+ String password = user + ":" + pass;
+ String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1"));
- if ((user != null) && (pass != null)) {
- urlConnection = url.openConnection();
-
- String password = user + ":" + pass;
- String encodedPassword =
- Base64.encode(password.getBytes());
+ // set authentication property in the http header
+ urlConnection.setRequestProperty("Authorization",
+ "Basic " + encodedPassword);
+ }
+ }
- // set authentication property in the http header
- urlConnection.setRequestProperty("Authorization",
- "Basic "
- + encodedPassword);
- }
- }
+ String mimeType = urlConnection.getHeaderField("Content-Type");
+ InputStream inputStream = urlConnection.getInputStream();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ byte buf[] = new byte[4096];
+ int read = 0;
+ int summarized = 0;
+
+ while ((read = inputStream.read(buf)) >= 0) {
+ baos.write(buf, 0, read);
+ summarized += read;
}
- }
+
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString());
+ }
- 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;
+ XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
+
+ result.setSourceURI(uriNew.toString());
+ result.setMIMEType(mimeType);
- while ((read = inputStream.read(buf)) >= 0) {
- baos.write(buf, 0, read);
+ 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);
+ }
+ }
- summarized += read;
- }
+ private URLConnection openConnection(URL url) throws IOException {
- log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI "
- + uriNew.toString());
-
- XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray());
+ 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]);
- // XMLSignatureInput result = new XMLSignatureInput(inputStream);
- result.setSourceURI(uriNew.toString());
- result.setMIMEType(mimeType);
+ Proxy proxy = null;
+ if ((proxyHostProp != null) && (proxyPortProp != null)) {
+ int port = Integer.parseInt(proxyPortProp);
+ proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port));
+ }
- // switch off proxy usage
- if (useProxy && switchBackProxy) {
- System.setProperty("http.proxySet", oldProxySet);
- System.setProperty("http.proxyHost", oldProxyHost);
- System.setProperty("http.proxyPort", oldProxyPort);
- }
+ URLConnection urlConnection;
+ if (proxy != null) {
+ urlConnection = url.openConnection(proxy);
- return result;
- } catch (MalformedURLException ex) {
- throw new ResourceResolverException("generic.EmptyMessage", ex, uri,
- BaseURI);
- } catch (IOException ex) {
- throw new ResourceResolverException("generic.EmptyMessage", ex, uri,
- BaseURI);
- }
- }
+ if ((proxyUser != null) && (proxyPass != null)) {
+ String password = proxyUser + ":" + proxyPass;
+ String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1"));
+
+ urlConnection.setRequestProperty("Proxy-Authorization", authString);
+ }
+ } else {
+ urlConnection = url.openConnection();
+ }
+
+ return urlConnection;
+ }
- /**
- * We resolve http URIs <I>without</I> 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");
+ /**
+ * We resolve http URIs <I>without</I> 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;
+ }
- return false;
- }
-
- String uriNodeValue = uri.getNodeValue();
+ if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones");
+ }
+ return false;
+ }
- if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) {
- log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones");
-
- return false;
- }
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve);
+ }
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "I was asked whether I can 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;
+ }
- 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 (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve);
+ }
- return true;
- }
-
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue);
- }
+ return false;
+ }
- return false;
- }
-
- /**
- * @inheritDoc
- */
- public String[] engineGetPropertyKeys() {
- return ResolverDirectHTTP.properties.clone();
- }
+ /**
+ * @inheritDoc
+ */
+ public String[] engineGetPropertyKeys() {
+ return ResolverDirectHTTP.properties.clone();
+ }
- private URI getNewURI(String uri, String BaseURI)
- throws URI.MalformedURIException {
+ 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 ((BaseURI == null) || "".equals(BaseURI)) {
- return new URI(uri);
- }
- return new URI(new URI(BaseURI), 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;
+ }
+
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,148 +2,148 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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 <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel">The Reference processing model in the XML Signature spec</A>
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#sec-Same-Document">Same-Document URI-References in the XML Signature spec</A>
* @see <A HREF="http://www.ietf.org/rfc/rfc2396.txt">Section 4.2 of RFC 2396</A>
*/
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) {
-
- if (uri == null) {
- log.log(java.util.logging.Level.FINE, "Quick fail for null uri");
- return false;
- }
+ /**
+ * Method engineCanResolve
+ * @inheritDoc
+ * @param uri
+ * @param baseURI
+ */
+ public boolean engineCanResolveURI(ResourceResolverContext context) {
+ if (context.uriToResolve == null) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Quick fail for null uri");
+ }
+ return false;
+ }
- 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,156 +2,160 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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;
+ }
+
+ /**
+ * @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();
+ }
- try {
- URI uriNew = getNewURI(uri.getNodeValue(), BaseURI);
+ 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;
+ }
}
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,36 +2,35 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2004 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package com.sun.org.apache.xml.internal.security.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.
* <BR />
@@ -45,15 +44,18 @@
* 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 @@
/**
* @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) {
+ /**
+ * @inheritDoc
+ */
+ public boolean engineCanResolveURI(ResourceResolverContext context) {
+ if (context.uriToResolve == null) {
+ return false;
+ }
+ if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) {
+ return true;
+ }
- if (uri == null) {
- return false;
- }
- String uriStr =uri.getNodeValue();
- if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) {
- return true;
- }
-
- return false;
- }
+ return false;
+ }
- /**
- * Method isXPointerSlash
- *
- * @param uri
- * @return true if begins with xpointer
- */
- private static boolean isXPointerSlash(String uri) {
-
- if (uri.equals("#xpointer(/)")) {
- return true;
- }
+ /**
+ * 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) {
-
+ return false;
+ }
- if (uri.startsWith(XP)
- && uri.endsWith("))")) {
- String idPlusDelim = uri.substring(XP_LENGTH,
- uri.length()
- - 2);
+ /**
+ * 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);
- // 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));
-
- return true;
- }
- }
-
- return false;
- }
+ 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;
+ }
+ }
- /**
- * Method getXPointerId
- *
- * @param uri
- * @return xpointerId to search.
- */
- private static String getXPointerId(String uri) {
-
+ 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 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);
- return null;
- }
+ 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;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/DigesterOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,36 +2,37 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
* @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 @@
}
}
- /** @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 @@
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 @@
return null;
}
}
+
+ @Override
+ public void close() throws IOException {
+ if (buffer) {
+ bos.close();
+ }
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/MacOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.jcp.xml.dsig.internal;
@@ -38,19 +40,13 @@
this.mac = mac;
}
- /** @inheritDoc */
- public void write(byte[] arg0) {
- super.write(arg0, 0, arg0.length);
- mac.update(arg0);
- }
-
- /** @inheritDoc */
+ @Override
public void write(int arg0) {
super.write(arg0);
mac.update((byte) arg0);
}
- /** @inheritDoc */
+ @Override
public void write(byte[] arg0, int arg1, int arg2) {
super.write(arg0, arg1, arg2);
mac.update(arg0, arg1, arg2);
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/SignerOutputStream.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 1999-2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
/**
* 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 @@
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);
}
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/AbstractDOMSignatureMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -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 <code>true</code> if the signature verified successfully,
+ * <code>false</code> if not
+ * @throws NullPointerException if <code>key</code>, <code>si</code> or
+ * <code>sig</code> are <code>null</code>
+ * @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 <code>key</code> or
+ * <code>si</code> are <code>null</code>
+ * @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 <code>SignatureMethodParameterSpec</code> from the specified
+ * <code>Element</code>. 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 <code>Element</code> holding the input params
+ * @return the algorithm-specific <code>SignatureMethodParameterSpec</code>
+ * @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 <code>null</code>)
+ * @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);
+ }
+}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheCanonicalizer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,44 +2,42 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: ApacheCanonicalizer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheCanonicalizer.java 1333869 2012-05-04 10:42:44Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.IOException;
import java.io.OutputStream;
import java.security.spec.AlgorithmParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.util.Set;
-import java.util.logging.Logger;
-import java.util.logging.Level;
import javax.xml.crypto.*;
import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dsig.TransformException;
import javax.xml.crypto.dsig.TransformService;
-import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
@@ -48,7 +46,7 @@
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
public abstract class ApacheCanonicalizer extends TransformService {
@@ -56,7 +54,8 @@
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 @@
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 @@
}
try {
- Set nodeSet = null;
+ Set<Node> 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 @@
Utils.readBytesFromStream(in.getOctetStream()))));
}
} else if (data instanceof DOMSubTreeData) {
- DOMSubTreeData subTree = (DOMSubTreeData) data;
+ DOMSubTreeData subTree = (DOMSubTreeData)data;
if (inclusiveNamespaces != null) {
return new OctetStreamData(new ByteArrayInputStream
(apacheCanonicalizer.canonicalizeSubtree
@@ -152,12 +160,13 @@
(subTree.getRoot())));
}
} else if (data instanceof NodeSetData) {
- NodeSetData nsd = (NodeSetData) data;
+ NodeSetData nsd = (NodeSetData)data;
// convert Iterator to Set
- nodeSet = Utils.toNodeSet(nsd.iterator());
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Canonicalizing " + nodeSet.size()
- + " nodes");
+ @SuppressWarnings("unchecked")
+ Set<Node> ns = Utils.toNodeSet(nsd.iterator());
+ nodeSet = ns;
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Canonicalizing " + nodeSet.size() + " nodes");
}
} else {
return new OctetStreamData(new ByteArrayInputStream(
@@ -179,7 +188,8 @@
}
public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
- throws TransformException {
+ throws TransformException
+ {
if (data == null) {
throw new NullPointerException("data must not be null");
}
@@ -193,12 +203,11 @@
if (apacheTransform == null) {
try {
- apacheTransform = new Transform
- (ownerDoc, getAlgorithm(), transformElem.getChildNodes());
+ apacheTransform =
+ new Transform(ownerDoc, getAlgorithm(), transformElem.getChildNodes());
apacheTransform.setElement(transformElem, xc.getBaseURI());
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Created transform for algorithm: "
- + getAlgorithm());
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Created transform for algorithm: " + getAlgorithm());
}
} catch (Exception ex) {
throw new TransformException
@@ -208,26 +217,27 @@
XMLSignatureInput in;
if (data instanceof ApacheData) {
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "ApacheData = true");
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "ApacheData = true");
}
- in = ((ApacheData) data).getXMLSignatureInput();
+ in = ((ApacheData)data).getXMLSignatureInput();
} else if (data instanceof NodeSetData) {
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "isNodeSet() = true");
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "isNodeSet() = true");
}
if (data instanceof DOMSubTreeData) {
- DOMSubTreeData subTree = (DOMSubTreeData) data;
+ DOMSubTreeData subTree = (DOMSubTreeData)data;
in = new XMLSignatureInput(subTree.getRoot());
in.setExcludeComments(subTree.excludeComments());
} else {
- Set nodeSet =
- Utils.toNodeSet(((NodeSetData) data).iterator());
+ @SuppressWarnings("unchecked")
+ Set<Node> 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
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
/**
* Returns the XMLSignatureInput.
*/
- public XMLSignatureInput getXMLSignatureInput();
+ XMLSignatureInput getXMLSignatureInput();
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheNodeSetData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,32 +2,33 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: ApacheNodeSetData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheNodeSetData.java 1203890 2011-11-18 22:47:56Z mullan $
*/
package org.jcp.xml.dsig.internal.dom;
import java.util.Collections;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
@@ -65,24 +66,22 @@
return xi;
}
- private Set getNodeSet(List nodeFilters) {
+ private Set<Node> getNodeSet(List<NodeFilter> 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<Node> inputSet = new LinkedHashSet<Node>();
+ XMLUtils.getSet(xi.getSubNode(), inputSet,
+ null, !xi.isExcludeComments());
+ Set<Node> nodeSet = new LinkedHashSet<Node>();
+ for (Node currentNode : inputSet) {
+ Iterator<NodeFilter> 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;
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheOctetStreamData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
private XMLSignatureInput xi;
public ApacheOctetStreamData(XMLSignatureInput xi)
- throws CanonicalizationException, IOException {
+ throws CanonicalizationException, IOException
+ {
super(xi.getOctetStream(), xi.getSourceURI(), xi.getMIMEType());
this.xi = xi;
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/ApacheTransform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: ApacheTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -30,11 +32,9 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
@@ -58,7 +58,8 @@
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 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 @@
}
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 @@
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<Node> 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
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMBase64Transform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,33 +2,34 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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;
/**
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14N11Method.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2008 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalXMLC14NMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCanonicalizationMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,33 +2,36 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
* @param spi TransformService
*/
public DOMCanonicalizationMethod(TransformService spi)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
super(spi);
if (!(spi instanceof ApacheCanonicalizer) &&
!isC14Nalg(spi.getAlgorithm())) {
@@ -66,7 +70,9 @@
* @param cmElem a CanonicalizationMethod element
*/
public DOMCanonicalizationMethod(Element cmElem, XMLCryptoContext context,
- Provider provider) throws MarshalException {
+ Provider provider)
+ throws MarshalException
+ {
super(cmElem, context, provider);
if (!(spi instanceof ApacheCanonicalizer) &&
!isC14Nalg(spi.getAlgorithm())) {
@@ -88,15 +94,18 @@
* canonicalizing the data
*/
public Data canonicalize(Data data, XMLCryptoContext xc)
- throws TransformException {
+ throws TransformException
+ {
return transform(data, xc);
}
public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os)
- throws TransformException {
+ throws TransformException
+ {
return transform(data, xc, os);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -105,12 +114,24 @@
if (!(o instanceof CanonicalizationMethod)) {
return false;
}
- CanonicalizationMethod ocm = (CanonicalizationMethod) o;
+ CanonicalizationMethod ocm = (CanonicalizationMethod)o;
return (getAlgorithm().equals(ocm.getAlgorithm()) &&
DOMUtils.paramsEqual(getParameterSpec(), ocm.getParameterSpec()));
}
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + getAlgorithm().hashCode();
+ AlgorithmParameterSpec spec = getParameterSpec();
+ if (spec != null) {
+ result = 31 * result + spec.hashCode();
+ }
+
+ return result;
+ }
+
private static boolean isC14Nalg(String alg) {
return (alg.equals(CanonicalizationMethod.INCLUSIVE) ||
alg.equals(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) ||
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMCryptoBinary.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,34 +2,35 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.
*/
/*
* 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;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMDigestMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
public abstract class DOMDigestMethod extends DOMStructure
implements DigestMethod {
- final static String SHA384 =
+ static final String SHA384 =
"http://www.w3.org/2001/04/xmldsig-more#sha384"; // see RFC 4051
private DigestMethodParameterSpec params;
@@ -57,13 +59,14 @@
* appropriate for this digest method
*/
DOMDigestMethod(AlgorithmParameterSpec params)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
if (params != null && !(params instanceof DigestMethodParameterSpec)) {
throw new InvalidAlgorithmParameterException
("params must be of type DigestMethodParameterSpec");
}
- checkParams((DigestMethodParameterSpec) params);
- this.params = (DigestMethodParameterSpec) params;
+ checkParams((DigestMethodParameterSpec)params);
+ this.params = (DigestMethodParameterSpec)params;
}
/**
@@ -96,8 +99,8 @@
} else if (alg.equals(DigestMethod.SHA512)) {
return new SHA512(dmElem);
} else {
- throw new MarshalException
- ("unsupported DigestMethod algorithm: " + alg);
+ throw new MarshalException("unsupported DigestMethod algorithm: " +
+ alg);
}
}
@@ -112,11 +115,12 @@
* appropriate for this digest method
*/
void checkParams(DigestMethodParameterSpec params)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
if (params != null) {
throw new InvalidAlgorithmParameterException("no parameters " +
- "should be specified for the " + getMessageDigestAlgorithm()
- + " DigestMethod algorithm");
+ "should be specified for the " + getMessageDigestAlgorithm() +
+ " DigestMethod algorithm");
}
}
@@ -134,11 +138,13 @@
* @return the algorithm-specific <code>DigestMethodParameterSpec</code>
* @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 @@
* method to marshal any algorithm-specific parameters.
*/
public void marshal(Node parent, String prefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
- Element dmElem = DOMUtils.createElement
- (ownerDoc, "DigestMethod", XMLSignature.XMLNS, prefix);
+ Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod",
+ XMLSignature.XMLNS, prefix);
DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm());
if (params != null) {
@@ -160,6 +167,7 @@
parent.appendChild(dmElem);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -168,7 +176,7 @@
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 @@
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 @@
* @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");
}
/**
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMEnvelopedTransform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMExcC14NMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMExcC14NMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMExcC14NMethod.java 1197150 2011-11-03 14:34:57Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -50,18 +52,20 @@
public final class DOMExcC14NMethod extends ApacheCanonicalizer {
public void init(TransformParameterSpec params)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
if (params != null) {
if (!(params instanceof ExcC14NParameterSpec)) {
throw new InvalidAlgorithmParameterException
("params must be of type ExcC14NParameterSpec");
}
- this.params = (C14NMethodParameterSpec) params;
+ this.params = (C14NMethodParameterSpec)params;
}
}
public void init(XMLStructure parent, XMLCryptoContext context)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
super.init(parent, context);
Element paramsElem = DOMUtils.getFirstChildElement(transformElem);
if (paramsElem == null) {
@@ -77,7 +81,7 @@
this.inclusiveNamespaces = prefixListAttr;
int begin = 0;
int end = prefixListAttr.indexOf(' ');
- List prefixList = new ArrayList();
+ List<String> prefixList = new ArrayList<String>();
while (end != -1) {
prefixList.add(prefixListAttr.substring(begin, end));
begin = end + 1;
@@ -90,39 +94,42 @@
}
public void marshalParams(XMLStructure parent, XMLCryptoContext context)
- throws MarshalException {
-
+ throws MarshalException
+ {
super.marshalParams(parent, context);
AlgorithmParameterSpec spec = getParameterSpec();
if (spec == null) {
return;
}
- String prefix =
- DOMUtils.getNSPrefix(context, CanonicalizationMethod.EXCLUSIVE);
- Element excElem = DOMUtils.createElement
- (ownerDoc, "InclusiveNamespaces",
- CanonicalizationMethod.EXCLUSIVE, prefix);
+ String prefix = DOMUtils.getNSPrefix(context,
+ CanonicalizationMethod.EXCLUSIVE);
+ Element eElem = DOMUtils.createElement(ownerDoc,
+ "InclusiveNamespaces",
+ CanonicalizationMethod.EXCLUSIVE,
+ prefix);
if (prefix == null || prefix.length() == 0) {
- excElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
- CanonicalizationMethod.EXCLUSIVE);
+ eElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns",
+ CanonicalizationMethod.EXCLUSIVE);
} else {
- excElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
- "xmlns:" + prefix, CanonicalizationMethod.EXCLUSIVE);
+ eElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+ "xmlns:" + prefix,
+ CanonicalizationMethod.EXCLUSIVE);
}
- ExcC14NParameterSpec params = (ExcC14NParameterSpec) spec;
+ ExcC14NParameterSpec params = (ExcC14NParameterSpec)spec;
StringBuffer prefixListAttr = new StringBuffer("");
- List prefixList = params.getPrefixList();
+ @SuppressWarnings("unchecked")
+ List<String> prefixList = params.getPrefixList();
for (int i = 0, size = prefixList.size(); i < size; i++) {
- prefixListAttr.append((String) prefixList.get(i));
+ prefixListAttr.append(prefixList.get(i));
if (i < size - 1) {
prefixListAttr.append(" ");
}
}
- DOMUtils.setAttribute(excElem, "PrefixList", prefixListAttr.toString());
+ DOMUtils.setAttribute(eElem, "PrefixList", prefixListAttr.toString());
this.inclusiveNamespaces = prefixListAttr.toString();
- transformElem.appendChild(excElem);
+ transformElem.appendChild(eElem);
}
public String getParamsNSURI() {
@@ -130,13 +137,13 @@
}
public Data transform(Data data, XMLCryptoContext xc)
- throws TransformException {
-
+ throws TransformException
+ {
// ignore comments if dereferencing same-document URI that require
// you to omit comments, even if the Transform says otherwise -
// this is to be compliant with section 4.3.3.3 of W3C Rec.
if (data instanceof DOMSubTreeData) {
- DOMSubTreeData subTree = (DOMSubTreeData) data;
+ DOMSubTreeData subTree = (DOMSubTreeData)data;
if (subTree.excludeComments()) {
try {
apacheCanonicalizer = Canonicalizer.getInstance
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMHMACSignatureMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2009, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMHMACSignatureMethod.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMHMACSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -38,8 +40,6 @@
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.AlgorithmParameterSpec;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import org.w3c.dom.Document;
@@ -52,13 +52,23 @@
*
* @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");
- private static Logger log =
- 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 Mac hmac;
private int outputLength;
private boolean outputLengthSet;
+ private SignatureMethodParameterSpec params;
/**
* Creates a <code>DOMHMACSignatureMethod</code> with the specified params
@@ -67,8 +77,10 @@
* @throws InvalidAlgorithmParameterException if params are inappropriate
*/
DOMHMACSignatureMethod(AlgorithmParameterSpec params)
- throws InvalidAlgorithmParameterException {
- super(params);
+ throws InvalidAlgorithmParameterException
+ {
+ checkParams((SignatureMethodParameterSpec)params);
+ this.params = (SignatureMethodParameterSpec)params;
}
/**
@@ -77,54 +89,64 @@
* @param smElem a SignatureMethod element
*/
DOMHMACSignatureMethod(Element smElem) throws MarshalException {
- super(smElem);
+ Element paramsElem = DOMUtils.getFirstChildElement(smElem);
+ if (paramsElem != null) {
+ params = unmarshalParams(paramsElem);
+ }
+ try {
+ checkParams(params);
+ } catch (InvalidAlgorithmParameterException iape) {
+ throw new MarshalException(iape);
+ }
}
void checkParams(SignatureMethodParameterSpec params)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
if (params != null) {
if (!(params instanceof HMACParameterSpec)) {
throw new InvalidAlgorithmParameterException
("params must be of type HMACParameterSpec");
}
- outputLength = ((HMACParameterSpec) params).getOutputLength();
+ outputLength = ((HMACParameterSpec)params).getOutputLength();
outputLengthSet = true;
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE,
- "Setting outputLength from HMACParameterSpec to: "
- + outputLength);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Setting outputLength from HMACParameterSpec to: " + outputLength);
}
- } else {
- outputLength = -1;
}
}
+ public final AlgorithmParameterSpec getParameterSpec() {
+ return params;
+ }
+
SignatureMethodParameterSpec unmarshalParams(Element paramsElem)
- throws MarshalException {
- outputLength = new Integer
- (paramsElem.getFirstChild().getNodeValue()).intValue();
+ throws MarshalException
+ {
+ outputLength = Integer.valueOf(paramsElem.getFirstChild().getNodeValue()).intValue();
outputLengthSet = true;
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "unmarshalled outputLength: " + outputLength);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "unmarshalled outputLength: " + outputLength);
}
return new HMACParameterSpec(outputLength);
}
void marshalParams(Element parent, String prefix)
- throws MarshalException {
-
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
Element hmacElem = DOMUtils.createElement(ownerDoc, "HMACOutputLength",
- XMLSignature.XMLNS, prefix);
+ XMLSignature.XMLNS, prefix);
hmacElem.appendChild(ownerDoc.createTextNode
(String.valueOf(outputLength)));
parent.appendChild(hmacElem);
}
- boolean verify(Key key, DOMSignedInfo si, byte[] sig,
- XMLValidateContext context)
- throws InvalidKeyException, SignatureException, XMLSignatureException {
+ boolean verify(Key key, SignedInfo si, byte[] sig,
+ XMLValidateContext context)
+ throws InvalidKeyException, SignatureException, XMLSignatureException
+ {
if (key == null || si == null || sig == null) {
throw new NullPointerException();
}
@@ -133,7 +155,7 @@
}
if (hmac == null) {
try {
- hmac = Mac.getInstance(getSignatureAlgorithm());
+ hmac = Mac.getInstance(getJCAAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
@@ -142,15 +164,16 @@
throw new XMLSignatureException
("HMACOutputLength must not be less than " + getDigestLength());
}
- hmac.init((SecretKey) key);
- si.canonicalize(context, new MacOutputStream(hmac));
+ hmac.init((SecretKey)key);
+ ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
byte[] result = hmac.doFinal();
return MessageDigest.isEqual(sig, result);
}
- byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
- throws InvalidKeyException, XMLSignatureException {
+ byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+ throws InvalidKeyException, XMLSignatureException
+ {
if (key == null || si == null) {
throw new NullPointerException();
}
@@ -159,7 +182,7 @@
}
if (hmac == null) {
try {
- hmac = Mac.getInstance(getSignatureAlgorithm());
+ hmac = Mac.getInstance(getJCAAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
@@ -168,8 +191,8 @@
throw new XMLSignatureException
("HMACOutputLength must not be less than " + getDigestLength());
}
- hmac.init((SecretKey) key);
- si.canonicalize(context, new MacOutputStream(hmac));
+ hmac.init((SecretKey)key);
+ ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
return hmac.doFinal();
}
@@ -180,11 +203,15 @@
if (!(spec instanceof HMACParameterSpec)) {
return false;
}
- HMACParameterSpec ospec = (HMACParameterSpec) spec;
+ HMACParameterSpec ospec = (HMACParameterSpec)spec;
return (outputLength == ospec.getOutputLength());
}
+ Type getAlgorithmType() {
+ return Type.HMAC;
+ }
+
/**
* Returns the output length of the hash/digest.
*/
@@ -201,7 +228,7 @@
public String getAlgorithm() {
return SignatureMethod.HMAC_SHA1;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "HmacSHA1";
}
int getDigestLength() {
@@ -220,7 +247,7 @@
public String getAlgorithm() {
return HMAC_SHA256;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "HmacSHA256";
}
int getDigestLength() {
@@ -239,7 +266,7 @@
public String getAlgorithm() {
return HMAC_SHA384;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "HmacSHA384";
}
int getDigestLength() {
@@ -258,7 +285,7 @@
public String getAlgorithm() {
return HMAC_SHA512;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "HmacSHA512";
}
int getDigestLength() {
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,38 +2,40 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMKeyInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyInfo.java 1333869 2012-05-04 10:42:44Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dom.*;
import java.security.Provider;
import java.util.*;
+
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -48,7 +50,7 @@
public final class DOMKeyInfo extends DOMStructure implements KeyInfo {
private final String id;
- private final List keyInfoTypes;
+ private final List<XMLStructure> keyInfoTypes;
/**
* Creates a <code>DOMKeyInfo</code>.
@@ -62,21 +64,21 @@
* @throws ClassCastException if <code>content</code> contains any entries
* that are not of type {@link XMLStructure}
*/
- public DOMKeyInfo(List content, String id) {
+ public DOMKeyInfo(List<? extends XMLStructure> 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<XMLStructure>(content));
+ if (this.keyInfoTypes.isEmpty()) {
throw new IllegalArgumentException("content cannot be empty");
}
- for (int i = 0, size = typesCopy.size(); i < size; i++) {
- if (!(typesCopy.get(i) instanceof XMLStructure)) {
+ for (int i = 0, size = this.keyInfoTypes.size(); i < size; i++) {
+ if (!(this.keyInfoTypes.get(i) instanceof XMLStructure)) {
throw new ClassCastException
("content["+i+"] is not a valid KeyInfo type");
}
}
- this.keyInfoTypes = Collections.unmodifiableList(typesCopy);
this.id = id;
}
@@ -86,7 +88,9 @@
* @param kiElem KeyInfo element
*/
public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
- Provider provider) throws MarshalException {
+ Provider provider)
+ throws MarshalException
+ {
// get Id attribute, if specified
Attr attr = kiElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
@@ -103,24 +107,24 @@
throw new MarshalException
("KeyInfo must contain at least one type");
}
- List content = new ArrayList(length);
+ List<XMLStructure> content = new ArrayList<XMLStructure>(length);
for (int i = 0; i < length; i++) {
Node child = nl.item(i);
// ignore all non-Element nodes
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
- Element childElem = (Element) child;
+ Element childElem = (Element)child;
String localName = childElem.getLocalName();
if (localName.equals("X509Data")) {
content.add(new DOMX509Data(childElem));
} else if (localName.equals("KeyName")) {
content.add(new DOMKeyName(childElem));
} else if (localName.equals("KeyValue")) {
- content.add(new DOMKeyValue(childElem));
+ content.add(DOMKeyValue.unmarshal(childElem));
} else if (localName.equals("RetrievalMethod")) {
- content.add
- (new DOMRetrievalMethod(childElem, context, provider));
+ content.add(new DOMRetrievalMethod(childElem,
+ context, provider));
} else if (localName.equals("PGPData")) {
content.add(new DOMPGPData(childElem));
} else { //may be MgmtData, SPKIData or element from other namespace
@@ -139,51 +143,58 @@
}
public void marshal(XMLStructure parent, XMLCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
if (parent == null) {
throw new NullPointerException("parent is null");
}
+ if (!(parent instanceof javax.xml.crypto.dom.DOMStructure)) {
+ throw new ClassCastException("parent must be of type DOMStructure");
+ }
- Node pNode = ((javax.xml.crypto.dom.DOMStructure) parent).getNode();
+ Node pNode = ((javax.xml.crypto.dom.DOMStructure)parent).getNode();
String dsPrefix = DOMUtils.getSignaturePrefix(context);
Element kiElem = DOMUtils.createElement
(DOMUtils.getOwnerDocument(pNode), "KeyInfo",
XMLSignature.XMLNS, dsPrefix);
if (dsPrefix == null || dsPrefix.length() == 0) {
- kiElem.setAttributeNS
- ("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS);
+ kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+ "xmlns", XMLSignature.XMLNS);
} else {
- kiElem.setAttributeNS
- ("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix,
- XMLSignature.XMLNS);
+ kiElem.setAttributeNS("http://www.w3.org/2000/xmlns/",
+ "xmlns:" + dsPrefix, XMLSignature.XMLNS);
}
- marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext) context);
+ marshal(pNode, kiElem, null, dsPrefix, (DOMCryptoContext)context);
}
public void marshal(Node parent, String dsPrefix,
- DOMCryptoContext context) throws MarshalException {
+ DOMCryptoContext context)
+ throws MarshalException
+ {
marshal(parent, null, dsPrefix, context);
}
public void marshal(Node parent, Node nextSibling, String dsPrefix,
- DOMCryptoContext context) throws MarshalException {
+ DOMCryptoContext context)
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
- Element kiElem = DOMUtils.createElement
- (ownerDoc, "KeyInfo", XMLSignature.XMLNS, dsPrefix);
+ Element kiElem = DOMUtils.createElement(ownerDoc, "KeyInfo",
+ XMLSignature.XMLNS, dsPrefix);
marshal(parent, kiElem, nextSibling, dsPrefix, context);
}
private void marshal(Node parent, Element kiElem, Node nextSibling,
- String dsPrefix, DOMCryptoContext context) throws MarshalException {
+ String dsPrefix, DOMCryptoContext context)
+ throws MarshalException
+ {
// create and append KeyInfoType elements
- for (int i = 0, size = keyInfoTypes.size(); i < size; i++) {
- XMLStructure kiType = (XMLStructure) keyInfoTypes.get(i);
+ for (XMLStructure kiType : keyInfoTypes) {
if (kiType instanceof DOMStructure) {
- ((DOMStructure) kiType).marshal(kiElem, dsPrefix, context);
+ ((DOMStructure)kiType).marshal(kiElem, dsPrefix, context);
} else {
DOMUtils.appendChild(kiElem,
- ((javax.xml.crypto.dom.DOMStructure) kiType).getNode());
+ ((javax.xml.crypto.dom.DOMStructure)kiType).getNode());
}
}
@@ -193,6 +204,7 @@
parent.insertBefore(kiElem, nextSibling);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -201,11 +213,22 @@
if (!(o instanceof KeyInfo)) {
return false;
}
- KeyInfo oki = (KeyInfo) o;
+ KeyInfo oki = (KeyInfo)o;
- boolean idsEqual = (id == null ? oki.getId() == null :
- id.equals(oki.getId()));
+ boolean idsEqual = (id == null ? oki.getId() == null
+ : id.equals(oki.getId()));
return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
}
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (id != null) {
+ result = 31 * result + id.hashCode();
+ }
+ result = 31 * result + keyInfoTypes.hashCode();
+
+ return result;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfoFactory.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMKeyInfoFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyInfoFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -31,8 +33,7 @@
import java.security.PublicKey;
import java.util.List;
import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
-import javax.xml.crypto.dom.*;
+import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dsig.keyinfo.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -51,6 +52,7 @@
return newKeyInfo(content, null);
}
+ @SuppressWarnings("unchecked")
public KeyInfo newKeyInfo(List content, String id) {
return new DOMKeyInfo(content, id);
}
@@ -60,17 +62,28 @@
}
public KeyValue newKeyValue(PublicKey key) throws KeyException {
- return new DOMKeyValue(key);
+ String algorithm = key.getAlgorithm();
+ if (algorithm.equals("DSA")) {
+ return new DOMKeyValue.DSA(key);
+ } else if (algorithm.equals("RSA")) {
+ return new DOMKeyValue.RSA(key);
+ } else if (algorithm.equals("EC")) {
+ return new DOMKeyValue.EC(key);
+ } else {
+ throw new KeyException("unsupported key algorithm: " + algorithm);
+ }
}
public PGPData newPGPData(byte[] keyId) {
return newPGPData(keyId, null, null);
}
+ @SuppressWarnings("unchecked")
public PGPData newPGPData(byte[] keyId, byte[] keyPacket, List other) {
return new DOMPGPData(keyId, keyPacket, other);
}
+ @SuppressWarnings("unchecked")
public PGPData newPGPData(byte[] keyPacket, List other) {
return new DOMPGPData(keyPacket, other);
}
@@ -79,6 +92,7 @@
return newRetrievalMethod(uri, null, null);
}
+ @SuppressWarnings("unchecked")
public RetrievalMethod newRetrievalMethod(String uri, String type,
List transforms) {
if (uri == null) {
@@ -87,6 +101,7 @@
return new DOMRetrievalMethod(uri, type, transforms);
}
+ @SuppressWarnings("unchecked")
public X509Data newX509Data(List content) {
return new DOMX509Data(content);
}
@@ -113,6 +128,9 @@
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 @@
"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() {}
+ }
+
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyName.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
// prepend namespace prefix, if necessary
- Element knElem = DOMUtils.createElement
- (ownerDoc, "KeyName", XMLSignature.XMLNS, dsPrefix);
+ Element knElem = DOMUtils.createElement(ownerDoc, "KeyName",
+ XMLSignature.XMLNS, dsPrefix);
knElem.appendChild(ownerDoc.createTextNode(name));
parent.appendChild(knElem);
}
+ @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
@@ -87,7 +91,15 @@
if (!(obj instanceof KeyName)) {
return false;
}
- KeyName okn = (KeyName) obj;
+ KeyName okn = (KeyName)obj;
return name.equals(okn.getName());
}
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + name.hashCode();
+
+ return result;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMKeyValue.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMKeyValue.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -31,14 +33,25 @@
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
+// import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.security.AccessController;
import java.security.KeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
import java.security.PublicKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
+import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
+import java.security.spec.ECParameterSpec;
+import java.security.spec.ECPoint;
+import java.security.spec.ECPublicKeySpec;
+import java.security.spec.EllipticCurve;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPublicKeySpec;
@@ -46,59 +59,46 @@
import org.w3c.dom.Element;
import org.w3c.dom.Node;
+import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
+import com.sun.org.apache.xml.internal.security.utils.Base64;
+
/**
* DOM-based implementation of KeyValue.
*
* @author Sean Mullan
*/
-public final class DOMKeyValue extends DOMStructure implements KeyValue {
-
- private KeyFactory rsakf, dsakf;
- private PublicKey publicKey;
- private javax.xml.crypto.dom.DOMStructure externalPublicKey;
+public abstract class DOMKeyValue extends DOMStructure implements KeyValue {
- // DSAKeyValue CryptoBinaries
- private DOMCryptoBinary p, q, g, y, j, seed, pgen;
+ private static final String XMLDSIG_11_XMLNS
+ = "http://www.w3.org/2009/xmldsig11#";
+ private final PublicKey publicKey;
- // 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 <code>DOMKeyValue</code> from an element.
*
- * @param kvElem a KeyValue element
+ * @param kvtElem a KeyValue child element
*/
- public DOMKeyValue(Element kvElem) throws MarshalException {
+ public DOMKeyValue(Element kvtElem) throws MarshalException {
+ this.publicKey = unmarshalKeyValue(kvtElem);
+ }
+
+ static KeyValue unmarshal(Element kvElem) throws MarshalException {
Element kvtElem = DOMUtils.getFirstChildElement(kvElem);
if (kvtElem.getLocalName().equals("DSAKeyValue")) {
- publicKey = unmarshalDSAKeyValue(kvtElem);
+ return new DSA(kvtElem);
} else if (kvtElem.getLocalName().equals("RSAKeyValue")) {
- publicKey = unmarshalRSAKeyValue(kvtElem);
+ return new RSA(kvtElem);
+ } else if (kvtElem.getLocalName().equals("ECKeyValue")) {
+ return new EC(kvtElem);
} else {
- publicKey = null;
- externalPublicKey = new javax.xml.crypto.dom.DOMStructure(kvtElem);
+ return new Unknown(kvtElem);
}
}
@@ -111,133 +111,25 @@
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
// create KeyValue element
- Element kvElem = DOMUtils.createElement
- (ownerDoc, "KeyValue", XMLSignature.XMLNS, dsPrefix);
+ Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue",
+ XMLSignature.XMLNS, dsPrefix);
marshalPublicKey(kvElem, ownerDoc, dsPrefix, context);
parent.appendChild(kvElem);
}
- private void marshalPublicKey(Node parent, Document doc, String dsPrefix,
- DOMCryptoContext context) throws MarshalException {
- if (publicKey != null) {
- if (publicKey instanceof DSAPublicKey) {
- // create and append DSAKeyValue element
- marshalDSAPublicKey(parent, doc, dsPrefix, context);
- } else if (publicKey instanceof RSAPublicKey) {
- // create and append RSAKeyValue element
- marshalRSAPublicKey(parent, doc, dsPrefix, context);
- } else {
- throw new MarshalException(publicKey.getAlgorithm() +
- " public key algorithm not supported");
- }
- } else {
- parent.appendChild(externalPublicKey.getNode());
- }
- }
-
- private void marshalDSAPublicKey(Node parent, Document doc,
- String dsPrefix, DOMCryptoContext context) throws MarshalException {
- Element dsaElem = DOMUtils.createElement
- (doc, "DSAKeyValue", XMLSignature.XMLNS, dsPrefix);
- // parameters J, Seed & PgenCounter are not included
- Element pElem = DOMUtils.createElement
- (doc, "P", XMLSignature.XMLNS, dsPrefix);
- Element qElem = DOMUtils.createElement
- (doc, "Q", XMLSignature.XMLNS, dsPrefix);
- Element gElem = DOMUtils.createElement
- (doc, "G", XMLSignature.XMLNS, dsPrefix);
- Element yElem = DOMUtils.createElement
- (doc, "Y", XMLSignature.XMLNS, dsPrefix);
- p.marshal(pElem, dsPrefix, context);
- q.marshal(qElem, dsPrefix, context);
- g.marshal(gElem, dsPrefix, context);
- y.marshal(yElem, dsPrefix, context);
- dsaElem.appendChild(pElem);
- dsaElem.appendChild(qElem);
- dsaElem.appendChild(gElem);
- dsaElem.appendChild(yElem);
- parent.appendChild(dsaElem);
- }
-
- private void marshalRSAPublicKey(Node parent, Document doc,
- String dsPrefix, DOMCryptoContext context) throws MarshalException {
- Element rsaElem = DOMUtils.createElement
- (doc, "RSAKeyValue", XMLSignature.XMLNS, dsPrefix);
- Element modulusElem = DOMUtils.createElement
- (doc, "Modulus", XMLSignature.XMLNS, dsPrefix);
- Element exponentElem = DOMUtils.createElement
- (doc, "Exponent", XMLSignature.XMLNS, dsPrefix);
- modulus.marshal(modulusElem, dsPrefix, context);
- exponent.marshal(exponentElem, dsPrefix, context);
- rsaElem.appendChild(modulusElem);
- rsaElem.appendChild(exponentElem);
- parent.appendChild(rsaElem);
- }
+ abstract void marshalPublicKey(Node parent, Document doc, String dsPrefix,
+ DOMCryptoContext context) throws MarshalException;
- 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);
- }
+ abstract PublicKey unmarshalKeyValue(Element kvtElem)
+ throws MarshalException;
- 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 @@
}
}
+ @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
@@ -254,7 +147,7 @@
return false;
}
try {
- KeyValue kv = (KeyValue) obj;
+ KeyValue kv = (KeyValue)obj;
if (publicKey == null ) {
if (kv.getPublicKey() != null) {
return false;
@@ -269,4 +162,340 @@
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<Void>() {
+ 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<Void>() {
+ 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());
+ }
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMManifest.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMManifest.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -32,6 +34,7 @@
import java.security.Provider;
import java.util.*;
+
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -44,7 +47,7 @@
*/
public final class DOMManifest extends DOMStructure implements Manifest {
- private final List references;
+ private final List<Reference> references;
private final String id;
/**
@@ -60,22 +63,22 @@
* @throws ClassCastException if <code>references</code> contains any
* entries that are not of type {@link Reference}
*/
- public DOMManifest(List references, String id) {
+ public DOMManifest(List<? extends Reference> 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<Reference>(references));
+ if (this.references.isEmpty()) {
throw new IllegalArgumentException("list of references must " +
"contain at least one entry");
}
- for (int i = 0, size = refCopy.size(); i < size; i++) {
- if (!(refCopy.get(i) instanceof Reference)) {
+ for (int i = 0, size = this.references.size(); i < size; i++) {
+ if (!(this.references.get(i) instanceof Reference)) {
throw new ClassCastException
("references["+i+"] is not a valid type");
}
}
- this.references = Collections.unmodifiableList(refCopy);
this.id = id;
}
@@ -85,7 +88,9 @@
* @param manElem a Manifest element
*/
public DOMManifest(Element manElem, XMLCryptoContext context,
- Provider provider) throws MarshalException {
+ Provider provider)
+ throws MarshalException
+ {
Attr attr = manElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
this.id = attr.getValue();
@@ -95,8 +100,10 @@
}
boolean secVal = Utils.secureValidation(context);
+
Element refElem = DOMUtils.getFirstChildElement(manElem);
- List refs = new ArrayList();
+ List<Reference> refs = new ArrayList<Reference>();
+
int refCount = 0;
while (refElem != null) {
refs.add(new DOMReference(refElem, context, provider));
@@ -104,10 +111,8 @@
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 void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
- Element manElem = DOMUtils.createElement
- (ownerDoc, "Manifest", XMLSignature.XMLNS, dsPrefix);
+ Element manElem = DOMUtils.createElement(ownerDoc, "Manifest",
+ XMLSignature.XMLNS, dsPrefix);
DOMUtils.setAttributeID(manElem, "Id", id);
// add references
- for (int i = 0, size = references.size(); i < size; i++) {
- DOMReference ref = (DOMReference) references.get(i);
- ref.marshal(manElem, dsPrefix, context);
+ for (Reference ref : references) {
+ ((DOMReference)ref).marshal(manElem, dsPrefix, context);
}
parent.appendChild(manElem);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -147,11 +152,22 @@
if (!(o instanceof Manifest)) {
return false;
}
- Manifest oman = (Manifest) o;
+ Manifest oman = (Manifest)o;
- boolean idsEqual = (id == null ? oman.getId() == null :
- id.equals(oman.getId()));
+ boolean idsEqual = (id == null ? oman.getId() == null
+ : id.equals(oman.getId()));
return (idsEqual && references.equals(oman.getReferences()));
}
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (id != null) {
+ result = 31 * result + id.hashCode();
+ }
+ result = 31 * result + references.hashCode();
+
+ return result;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMPGPData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 @@
private final byte[] keyId;
private final byte[] keyPacket;
- private final List externalElements;
+ private final List<XMLStructure> externalElements;
/**
* Creates a <code>DOMPGPData</code> containing the specified key packet.
@@ -67,23 +69,23 @@
* @throws ClassCastException if <code>other</code> contains any
* entries that are not of type {@link XMLStructure}
*/
- public DOMPGPData(byte[] keyPacket, List other) {
+ public DOMPGPData(byte[] keyPacket, List<? extends XMLStructure> 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<XMLStructure>(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 @@
* @throws ClassCastException if <code>other</code> 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<? extends XMLStructure> other)
+ {
if (keyId == null) {
throw new NullPointerException("keyId cannot be null");
}
@@ -117,19 +121,20 @@
throw new IllegalArgumentException("keyId must be 8 bytes long");
}
if (other == null || other.isEmpty()) {
- this.externalElements = Collections.EMPTY_LIST;
+ this.externalElements = Collections.emptyList();
} else {
- List otherCopy = new ArrayList(other);
- for (int i = 0, size = otherCopy.size(); i < size; i++) {
- if (!(otherCopy.get(i) instanceof XMLStructure)) {
+ this.externalElements =
+ Collections.unmodifiableList(new ArrayList<XMLStructure>(other));
+ for (int i = 0, size = this.externalElements.size(); i < size; i++) {
+ if (!(this.externalElements.get(i) instanceof XMLStructure)) {
throw new ClassCastException
("other["+i+"] is not a valid PGPData type");
}
}
- this.externalElements = Collections.unmodifiableList(otherCopy);
}
- this.keyId = (byte []) keyId.clone();
- this.keyPacket = keyPacket == null ? null : (byte []) keyPacket.clone();
+ this.keyId = (byte[])keyId.clone();
+ this.keyPacket = keyPacket == null ? null
+ : (byte[])keyPacket.clone();
if (keyPacket != null) {
checkKeyPacket(keyPacket);
}
@@ -146,11 +151,11 @@
byte[] keyPacket = null;
NodeList nl = pdElem.getChildNodes();
int length = nl.getLength();
- List other = new ArrayList(length);
+ List<XMLStructure> other = new ArrayList<XMLStructure>(length);
for (int x = 0; x < length; x++) {
Node n = nl.item(x);
if (n.getNodeType() == Node.ELEMENT_NODE) {
- Element childElem = (Element) n;
+ Element childElem = (Element)n;
String localName = childElem.getLocalName();
try {
if (localName.equals("PGPKeyID")) {
@@ -172,11 +177,11 @@
}
public byte[] getKeyId() {
- return (keyId == null ? null : (byte []) keyId.clone());
+ return (keyId == null ? null : (byte[])keyId.clone());
}
public byte[] getKeyPacket() {
- return (keyPacket == null ? null : (byte []) keyPacket.clone());
+ return (keyPacket == null ? null : (byte[])keyPacket.clone());
}
public List getExternalElements() {
@@ -184,16 +189,17 @@
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
- Element pdElem = DOMUtils.createElement
- (ownerDoc, "PGPData", XMLSignature.XMLNS, dsPrefix);
+ Element pdElem = DOMUtils.createElement(ownerDoc, "PGPData",
+ XMLSignature.XMLNS, dsPrefix);
// create and append PGPKeyID element
if (keyId != null) {
- Element keyIdElem = DOMUtils.createElement
- (ownerDoc, "PGPKeyID", XMLSignature.XMLNS, dsPrefix);
+ Element keyIdElem = DOMUtils.createElement(ownerDoc, "PGPKeyID",
+ XMLSignature.XMLNS,
+ dsPrefix);
keyIdElem.appendChild
(ownerDoc.createTextNode(Base64.encode(keyId)));
pdElem.appendChild(keyIdElem);
@@ -201,17 +207,19 @@
// create and append PGPKeyPacket element
if (keyPacket != null) {
- Element keyPktElem = DOMUtils.createElement
- (ownerDoc, "PGPKeyPacket", XMLSignature.XMLNS, dsPrefix);
+ Element keyPktElem = DOMUtils.createElement(ownerDoc,
+ "PGPKeyPacket",
+ XMLSignature.XMLNS,
+ dsPrefix);
keyPktElem.appendChild
(ownerDoc.createTextNode(Base64.encode(keyPacket)));
pdElem.appendChild(keyPktElem);
}
// create and append any elements
- for (int i = 0, size = externalElements.size(); i < size; i++) {
+ 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 @@
// 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");
}
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMReference.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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.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 @@
public final class DOMReference extends DOMStructure
implements Reference, DOMURIReference {
- /**
- * The maximum number of transforms per reference, if secure validation
- * is enabled.
- */
- public static final int MAXIMUM_TRANSFORM_COUNT = 5;
+ /**
+ * The maximum number of transforms per reference, if secure validation is enabled.
+ */
+ public static final int MAXIMUM_TRANSFORM_COUNT = 5;
/**
* Look up useC14N11 system property. If true, an explicit C14N11 transform
@@ -82,17 +81,18 @@
private static boolean useC14N11 =
AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
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<Transform> transforms;
+ private List<Transform> allTransforms;
private final Data appliedTransformData;
private Attr here;
private final String uri;
@@ -124,46 +124,51 @@
* not of type <code>Transform</code>
*/
public DOMReference(String uri, String type, DigestMethod dm,
- List transforms, String id, Provider provider) {
+ List<? extends Transform> 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<? extends Transform> appliedTransforms,
+ Data result, List<? extends Transform> 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<? extends Transform> appliedTransforms,
+ Data result, List<? extends Transform> 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<Transform>();
+ } else {
+ this.allTransforms = new ArrayList<Transform>(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<Transform>(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 @@
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 @@
* @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<Transform> transforms = new ArrayList<Transform>(5);
if (nextSibling.getLocalName().equals("Transforms")) {
Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
@@ -207,9 +214,8 @@
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 @@
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 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 @@
// 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 void digest(XMLSignContext signContext)
- throws XMLSignatureException {
+ throws XMLSignatureException
+ {
Data data = null;
if (appliedTransformData == null) {
data = dereference(signContext);
@@ -343,8 +353,8 @@
// insert digestValue into DigestValue element
String encodedDV = Base64.encode(digestValue);
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Reference object uri = " + uri);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Reference object uri = " + uri);
}
Element digestElem = DOMUtils.getLastChildElement(refElem);
if (digestElem == null) {
@@ -355,13 +365,14 @@
(refElem.getOwnerDocument().createTextNode(encodedDV));
digested = true;
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Reference digesting completed");
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Reference digesting completed");
}
}
public boolean validate(XMLValidateContext validateContext)
- throws XMLSignatureException {
+ throws XMLSignatureException
+ {
if (validateContext == null) {
throw new NullPointerException("validateContext cannot be null");
}
@@ -371,11 +382,9 @@
Data data = dereference(validateContext);
calcDigestValue = transform(data, validateContext);
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Expected digest: "
- + Base64.encode(digestValue));
- log.log(Level.FINE, "Actual digest: "
- + Base64.encode(calcDigestValue));
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Expected digest: " + Base64.encode(digestValue));
+ log.log(java.util.logging.Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue));
}
validationStatus = Arrays.equals(digestValue, calcDigestValue);
@@ -392,7 +401,8 @@
}
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 @@
}
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 @@
}
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 @@
DigesterOutputStream dos;
Boolean cache = (Boolean)
context.getProperty("javax.xml.crypto.dsig.cacheReference");
- if (cache != null && cache.booleanValue() == true) {
+ if (cache != null && cache.booleanValue()) {
this.derefData = copyDerefData(dereferencedData);
dos = new DigesterOutputStream(md, true);
} else {
dos = new DigesterOutputStream(md);
}
- OutputStream os = new UnsyncBufferedOutputStream(dos);
+ OutputStream os = null;
Data data = dereferencedData;
- for (int i = 0, size = transforms.size(); i < size; i++) {
- DOMTransform transform = (DOMTransform) transforms.get(i);
- try {
+ try {
+ os = new UnsyncBufferedOutputStream(dos);
+ for (int i = 0, size = transforms.size(); i < size; i++) {
+ DOMTransform transform = (DOMTransform)transforms.get(i);
if (i < size - 1) {
data = transform.transform(data, context);
} else {
data = transform.transform(data, context, os);
}
- } catch (TransformException te) {
- throw new XMLSignatureException(te);
}
- }
- try {
if (data != null) {
XMLSignatureInput xi;
// explicitly use C14N 1.1 when generating signature
@@ -460,9 +466,9 @@
String c14nalg = CanonicalizationMethod.INCLUSIVE;
if (context instanceof XMLSignContext) {
if (!c14n11) {
- Boolean prop = (Boolean) context.getProperty
+ Boolean prop = (Boolean)context.getProperty
("com.sun.org.apache.xml.internal.security.useC14N11");
- c14n11 = (prop != null && prop.booleanValue() == true);
+ c14n11 = (prop != null && prop.booleanValue());
if (c14n11) {
c14nalg = "http://www.w3.org/2006/12/xml-c14n11";
}
@@ -471,17 +477,20 @@
}
}
if (data instanceof ApacheData) {
- xi = ((ApacheData) data).getXMLSignatureInput();
+ xi = ((ApacheData)data).getXMLSignatureInput();
} else if (data instanceof OctetStreamData) {
xi = new XMLSignatureInput
(((OctetStreamData)data).getOctetStream());
} else if (data instanceof NodeSetData) {
TransformService spi = null;
- try {
+ if (provider == null) {
spi = TransformService.getInstance(c14nalg, "DOM");
- } catch (NoSuchAlgorithmException nsae) {
- spi = TransformService.getInstance
- (c14nalg, "DOM", provider);
+ } else {
+ try {
+ spi = TransformService.getInstance(c14nalg, "DOM", provider);
+ } catch (NoSuchAlgorithmException nsae) {
+ spi = TransformService.getInstance(c14nalg, "DOM");
+ }
}
data = spi.transform(data, context);
xi = new XMLSignatureInput
@@ -491,8 +500,18 @@
}
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 @@
} else {
transformsElem = DOMUtils.getFirstChildElement(refElem);
}
- t.marshal(transformsElem, dsPrefix, (DOMCryptoContext) context);
+ t.marshal(transformsElem, dsPrefix,
+ (DOMCryptoContext)context);
allTransforms.add(t);
xi.updateOutputStream(os, true);
} else {
@@ -512,12 +532,35 @@
}
}
os.flush();
- if (cache != null && cache.booleanValue() == true) {
+ if (cache != null && cache.booleanValue()) {
this.dis = dos.getInputStream();
}
return dos.getDigestValue();
- } catch (Exception e) {
+ } catch (NoSuchAlgorithmException e) {
+ throw new XMLSignatureException(e);
+ } catch (TransformException e) {
+ throw new XMLSignatureException(e);
+ } catch (MarshalException e) {
+ throw new XMLSignatureException(e);
+ } catch (IOException e) {
+ throw new XMLSignatureException(e);
+ } catch (com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException e) {
throw new XMLSignatureException(e);
+ } finally {
+ if (os != null) {
+ try {
+ os.close();
+ } catch (IOException e) {
+ throw new XMLSignatureException(e);
+ }
+ }
+ if (dos != null) {
+ try {
+ dos.close();
+ } catch (IOException e) {
+ throw new XMLSignatureException(e);
+ }
+ }
}
}
@@ -525,6 +568,7 @@
return here;
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -533,19 +577,41 @@
if (!(o instanceof Reference)) {
return false;
}
- Reference oref = (Reference) o;
+ Reference oref = (Reference)o;
- boolean idsEqual = (id == null ? oref.getId() == null :
- id.equals(oref.getId()));
- boolean urisEqual = (uri == null ? oref.getURI() == null :
- uri.equals(oref.getURI()));
- boolean typesEqual = (type == null ? oref.getType() == null :
- type.equals(oref.getType()));
+ boolean idsEqual = (id == null ? oref.getId() == null
+ : id.equals(oref.getId()));
+ boolean urisEqual = (uri == null ? oref.getURI() == null
+ : uri.equals(oref.getURI()));
+ boolean typesEqual = (type == null ? oref.getType() == null
+ : type.equals(oref.getType()));
boolean digestValuesEqual =
Arrays.equals(digestValue, oref.getDigestValue());
- return (digestMethod.equals(oref.getDigestMethod()) && idsEqual &&
- urisEqual && typesEqual && allTransforms.equals(oref.getTransforms()));
+ return digestMethod.equals(oref.getDigestMethod()) && idsEqual &&
+ urisEqual && typesEqual &&
+ allTransforms.equals(oref.getTransforms()) && digestValuesEqual;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (id != null) {
+ result = 31 * result + id.hashCode();
+ }
+ if (uri != null) {
+ result = 31 * result + uri.hashCode();
+ }
+ if (type != null) {
+ result = 31 * result + type.hashCode();
+ }
+ if (digestValue != null) {
+ result = 31 * result + Arrays.hashCode(digestValue);
+ }
+ result = 31 * result + digestMethod.hashCode();
+ result = 31 * result + allTransforms.hashCode();
+
+ return result;
}
boolean isDigested() {
@@ -555,18 +621,17 @@
private static Data copyDerefData(Data dereferencedData) {
if (dereferencedData instanceof ApacheData) {
// need to make a copy of the Data
- ApacheData ad = (ApacheData) dereferencedData;
+ ApacheData ad = (ApacheData)dereferencedData;
XMLSignatureInput xsi = ad.getXMLSignatureInput();
if (xsi.isNodeSet()) {
try {
- final Set s = xsi.getNodeSet();
+ final Set<Node> s = xsi.getNodeSet();
return new NodeSetData() {
public Iterator iterator() { return s.iterator(); }
};
} catch (Exception e) {
// log a warning
- log.log(Level.WARNING,
- "cannot cache dereferenced data: " + e);
+ log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
return null;
}
} else if (xsi.isElement()) {
@@ -574,12 +639,12 @@
(xsi.getSubNode(), xsi.isExcludeComments());
} else if (xsi.isOctetStream() || xsi.isByteArray()) {
try {
- return new OctetStreamData
- (xsi.getOctetStream(), xsi.getSourceURI(), xsi.getMIMEType());
+ return new OctetStreamData
+ (xsi.getOctetStream(), xsi.getSourceURI(),
+ xsi.getMIMEType());
} catch (IOException ioe) {
// log a warning
- log.log(Level.WARNING,
- "cannot cache dereferenced data: " + ioe);
+ log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
return null;
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMRetrievalMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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.URISyntaxException;
import java.security.Provider;
import java.util.*;
+
import javax.xml.XMLConstants;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
@@ -50,8 +53,6 @@
import org.w3c.dom.Element;
import org.w3c.dom.Node;
-import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
-
/**
* DOM-based implementation of RetrievalMethod.
*
@@ -61,7 +62,7 @@
public final class DOMRetrievalMethod extends DOMStructure
implements RetrievalMethod, DOMURIReference {
- private final List transforms;
+ private final List<Transform> transforms;
private String uri;
private String type;
private Attr here;
@@ -83,24 +84,26 @@
* @throws ClassCastException if <code>transforms</code> 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<? extends Transform> 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<Transform>(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 @@
* @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 @@
boolean secVal = Utils.secureValidation(context);
// get Transforms, if specified
- List transforms = new ArrayList();
+ List<Transform> transforms = new ArrayList<Transform>();
Element transformsElem = DOMUtils.getFirstChildElement(rmElem);
int transformCount = 0;
@@ -141,19 +146,15 @@
transformElem = DOMUtils.getNextSiblingElement(transformElem);
transformCount++;
- if (secVal &&
- (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT))
- {
- String error = "A maxiumum of " +
- DOMReference.MAXIMUM_TRANSFORM_COUNT +
- " transforms per Reference are allowed" +
- " with secure validation";
+ if (secVal && (transformCount > DOMReference.MAXIMUM_TRANSFORM_COUNT)) {
+ String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " "
+ + "transforms per Reference are allowed with secure validation";
throw new MarshalException(error);
}
}
}
if (transforms.isEmpty()) {
- this.transforms = Collections.EMPTY_LIST;
+ this.transforms = Collections.emptyList();
} else {
this.transforms = Collections.unmodifiableList(transforms);
}
@@ -172,11 +173,11 @@
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
- Element rmElem = DOMUtils.createElement
- (ownerDoc, "RetrievalMethod", XMLSignature.XMLNS, dsPrefix);
+ Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod",
+ XMLSignature.XMLNS, dsPrefix);
// add URI and Type attributes
DOMUtils.setAttribute(rmElem, "URI", uri);
@@ -184,12 +185,14 @@
// add Transforms elements
if (!transforms.isEmpty()) {
- Element transformsElem = DOMUtils.createElement
- (ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
+ Element transformsElem = DOMUtils.createElement(ownerDoc,
+ "Transforms",
+ XMLSignature.XMLNS,
+ dsPrefix);
rmElem.appendChild(transformsElem);
- for (int i = 0, size = transforms.size(); i < size; i++) {
- ((DOMTransform) transforms.get(i)).marshal
- (transformsElem, dsPrefix, context);
+ for (Transform transform : transforms) {
+ ((DOMTransform)transform).marshal(transformsElem,
+ dsPrefix, context);
}
}
@@ -204,8 +207,8 @@
}
public Data dereference(XMLCryptoContext context)
- throws URIReferenceException {
-
+ throws URIReferenceException
+ {
if (context == null) {
throw new NullPointerException("context cannot be null");
}
@@ -223,9 +226,8 @@
// pass dereferenced data through Transforms
try {
- for (int i = 0, size = transforms.size(); i < size; i++) {
- Transform transform = (Transform) transforms.get(i);
- data = ((DOMTransform) transform).transform(data, context);
+ for (Transform transform : transforms) {
+ data = ((DOMTransform)transform).transform(data, context);
}
} catch (Exception e) {
throw new URIReferenceException(e);
@@ -249,14 +251,13 @@
}
public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context)
- throws URIReferenceException {
-
+ throws URIReferenceException
+ {
try {
- ApacheData data = (ApacheData) dereference(context);
+ ApacheData data = (ApacheData)dereference(context);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
- dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
- Boolean.TRUE);
+ dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream
(data.getXMLSignatureInput().getBytes()));
@@ -271,6 +272,7 @@
}
}
+ @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
@@ -278,12 +280,24 @@
if (!(obj instanceof RetrievalMethod)) {
return false;
}
- RetrievalMethod orm = (RetrievalMethod) obj;
+ RetrievalMethod orm = (RetrievalMethod)obj;
- boolean typesEqual = (type == null ? orm.getType() == null :
- type.equals(orm.getType()));
+ boolean typesEqual = (type == null ? orm.getType() == null
+ : type.equals(orm.getType()));
return (uri.equals(orm.getURI()) &&
transforms.equals(orm.getTransforms()) && typesEqual);
}
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (type != null) {
+ result = 31 * result + type.hashCode();
+ }
+ result = 31 * result + uri.hashCode();
+ result = 31 * result + transforms.hashCode();
+
+ return result;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureMethod.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,44 +2,42 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.
*/
/*
* 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 @@
*
* @author Sean Mullan
*/
-public abstract class DOMSignatureMethod extends DOMStructure
- implements SignatureMethod {
-
- private static Logger log =
- Logger.getLogger("org.jcp.xml.dsig.internal.dom");
+public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
- // 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 <code>DOMSignatureMethod</code>.
*
@@ -78,19 +77,20 @@
* 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 <code>DOMSignatureMethod</code> from an element. This ctor
- * invokes the abstract {@link #unmarshalParams unmarshalParams} method to
+ * invokes the {@link #unmarshalParams unmarshalParams} method to
* unmarshal any algorithm-specific input parameters.
*
* @param smElem a SignatureMethod element
@@ -119,13 +119,21 @@
return new SHA512withRSA(smElem);
} else if (alg.equals(SignatureMethod.DSA_SHA1)) {
return new SHA1withDSA(smElem);
+ } else if (alg.equals(ECDSA_SHA1)) {
+ return new SHA1withECDSA(smElem);
+ } else if (alg.equals(ECDSA_SHA256)) {
+ return new SHA256withECDSA(smElem);
+ } else if (alg.equals(ECDSA_SHA384)) {
+ return new SHA384withECDSA(smElem);
+ } else if (alg.equals(ECDSA_SHA512)) {
+ return new SHA512withECDSA(smElem);
} else if (alg.equals(SignatureMethod.HMAC_SHA1)) {
return new DOMHMACSignatureMethod.SHA1(smElem);
- } else if (alg.equals(HMAC_SHA256)) {
+ } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
return new DOMHMACSignatureMethod.SHA256(smElem);
- } else if (alg.equals(HMAC_SHA384)) {
+ } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
return new DOMHMACSignatureMethod.SHA384(smElem);
- } else if (alg.equals(HMAC_SHA512)) {
+ } else if (alg.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
return new DOMHMACSignatureMethod.SHA512(smElem);
} else {
throw new MarshalException
@@ -133,86 +141,14 @@
}
}
- /**
- * Checks if the specified parameters are valid for this algorithm. By
- * default, this method throws an exception if parameters are specified
- * since most SignatureMethod algorithms do not have parameters. Subclasses
- * should override it if they have parameters.
- *
- * @param params the algorithm-specific params (may be <code>null</code>)
- * @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 <code>SignatureMethodParameterSpec</code> from the specified
- * <code>Element</code>. 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 <code>Element</code> holding the input params
- * @return the algorithm-specific <code>SignatureMethodParameterSpec</code>
- * @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 <code>true</code> if the signature verified successfully,
- * <code>false</code> if not
- * @throws NullPointerException if <code>key</code>, <code>si</code> or
- * <code>signature</code> are <code>null</code>
- * @throws InvalidKeyException if the key is improperly encoded, of
- * the wrong type, or parameters are missing, etc
- * @throws SignatureException if an unexpected error occurs, such
- * as the passed in signature is improperly encoded
- * @throws XMLSignatureException if an unexpected error occurs
- */
- boolean verify(Key key, DOMSignedInfo si, byte[] sig,
- XMLValidateContext context) throws InvalidKeyException,
- SignatureException, XMLSignatureException {
+ boolean verify(Key key, SignedInfo si, byte[] sig,
+ XMLValidateContext context)
+ throws InvalidKeyException, SignatureException, XMLSignatureException
+ {
if (key == null || si == null || sig == null) {
throw new NullPointerException();
}
@@ -222,49 +158,40 @@
}
if (signature == null) {
try {
- Provider p = (Provider) context.getProperty
+ Provider p = (Provider)context.getProperty
("org.jcp.xml.dsig.internal.dom.SignatureProvider");
signature = (p == null)
- ? Signature.getInstance(getSignatureAlgorithm())
- : Signature.getInstance(getSignatureAlgorithm(), p);
+ ? Signature.getInstance(getJCAAlgorithm())
+ : Signature.getInstance(getJCAAlgorithm(), p);
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
}
- signature.initVerify((PublicKey) key);
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Signature provider:"+ signature.getProvider());
- log.log(Level.FINE, "verifying with key: " + key);
+ signature.initVerify((PublicKey)key);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider());
+ log.log(java.util.logging.Level.FINE, "verifying with key: " + key);
}
- si.canonicalize(context, new SignerOutputStream(signature));
+ ((DOMSignedInfo)si).canonicalize(context,
+ new SignerOutputStream(signature));
- if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) {
- try {
+ try {
+ Type type = getAlgorithmType();
+ if (type == Type.DSA) {
return signature.verify(convertXMLDSIGtoASN1(sig));
- } catch (IOException ioe) {
- throw new XMLSignatureException(ioe);
+ } else if (type == Type.ECDSA) {
+ return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig));
+ } else {
+ return signature.verify(sig);
}
- } else {
- return signature.verify(sig);
+ } catch (IOException ioe) {
+ throw new XMLSignatureException(ioe);
}
}
- /**
- * Signs the bytes with the specified key, using the underlying
- * signature or MAC algorithm.
- *
- * @param key the signing key
- * @param si the DOMSignedInfo
- * @param context the XMLSignContext
- * @return the signature
- * @throws NullPointerException if <code>key</code> or
- * <code>si</code> are <code>null</code>
- * @throws InvalidKeyException if the key is improperly encoded, of
- * the wrong type, or parameters are missing, etc
- * @throws XMLSignatureException if an unexpected error occurs
- */
- byte[] sign(Key key, DOMSignedInfo si, XMLSignContext context)
- throws InvalidKeyException, XMLSignatureException {
+ byte[] sign(Key key, SignedInfo si, XMLSignContext context)
+ throws InvalidKeyException, XMLSignatureException
+ {
if (key == null || si == null) {
throw new NullPointerException();
}
@@ -274,26 +201,30 @@
}
if (signature == null) {
try {
- Provider p = (Provider) context.getProperty
+ Provider p = (Provider)context.getProperty
("org.jcp.xml.dsig.internal.dom.SignatureProvider");
signature = (p == null)
- ? Signature.getInstance(getSignatureAlgorithm())
- : Signature.getInstance(getSignatureAlgorithm(), p);
+ ? Signature.getInstance(getJCAAlgorithm())
+ : Signature.getInstance(getJCAAlgorithm(), p);
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
}
- signature.initSign((PrivateKey) key);
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Signature provider:" +signature.getProvider());
- log.log(Level.FINE, "Signing with key: " + key);
+ signature.initSign((PrivateKey)key);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Signature provider:" + signature.getProvider());
+ log.log(java.util.logging.Level.FINE, "Signing with key: " + key);
}
- si.canonicalize(context, new SignerOutputStream(signature));
+ ((DOMSignedInfo)si).canonicalize(context,
+ new SignerOutputStream(signature));
try {
- if (getAlgorithm().equals(SignatureMethod.DSA_SHA1)) {
+ Type type = getAlgorithmType();
+ if (type == Type.DSA) {
return convertASN1toXMLDSIG(signature.sign());
+ } else if (type == Type.ECDSA) {
+ return SignatureECDSA.convertASN1toXMLDSIG(signature.sign());
} else {
return signature.sign();
}
@@ -305,52 +236,6 @@
}
/**
- * Marshals the algorithm-specific parameters to an Element and
- * appends it to the specified parent element. By default, this method
- * throws an exception since most SignatureMethod algorithms do not have
- * parameters. Subclasses should override it if they have parameters.
- *
- * @param parent the parent element to append the parameters to
- * @param paramsPrefix the algorithm parameters prefix to use
- * @throws MarshalException if the parameters cannot be marshalled
- */
- void marshalParams(Element parent, String paramsPrefix)
- throws MarshalException {
- throw new MarshalException("no parameters should " +
- "be specified for the " + getSignatureAlgorithm() +
- " SignatureMethod algorithm");
- }
-
- /**
- * Returns the java.security.Signature standard algorithm name.
- */
- abstract String getSignatureAlgorithm();
-
- /**
- * Returns true if parameters are equal; false otherwise.
- *
- * Subclasses should override this method to compare algorithm-specific
- * parameters.
- */
- boolean paramsEqual(AlgorithmParameterSpec spec) {
- return (getParameterSpec() == spec);
- }
-
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof SignatureMethod)) {
- return false;
- }
- SignatureMethod osm = (SignatureMethod) o;
-
- return (getAlgorithm().equals(osm.getAlgorithm()) &&
- paramsEqual(osm.getParameterSpec()));
- }
-
- /**
* Converts an ASN.1 DSA value to a XML Signature DSA Value.
*
* The JAVA JCE DSA Signature algorithm creates ASN.1 encoded (r,s) value
@@ -362,8 +247,8 @@
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
- throws IOException {
-
+ throws IOException
+ {
byte rLength = asn1Bytes[3];
int i;
@@ -384,7 +269,7 @@
System.arraycopy(asn1Bytes, (4+rLength)-i, xmldsigBytes, 20-i, i);
System.arraycopy(asn1Bytes, (6+rLength+sLength)-j, xmldsigBytes,
- 40 - j, j);
+ 40 - j, j);
return xmldsigBytes;
}
@@ -402,8 +287,8 @@
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
*/
private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
- throws IOException {
-
+ throws IOException
+ {
if (xmldsigBytes.length != 40) {
throw new IOException("Invalid XMLDSIG format of DSA signature");
}
@@ -431,9 +316,9 @@
byte asn1Bytes[] = new byte[6 + j + l];
asn1Bytes[0] = 48;
- asn1Bytes[1] = (byte) (4 + j + l);
+ asn1Bytes[1] = (byte)(4 + j + l);
asn1Bytes[2] = 2;
- asn1Bytes[3] = (byte) j;
+ asn1Bytes[3] = (byte)j;
System.arraycopy(xmldsigBytes, 20 - i, asn1Bytes, (4 + j) - i, i);
@@ -456,9 +341,12 @@
public String getAlgorithm() {
return SignatureMethod.RSA_SHA1;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "SHA1withRSA";
}
+ Type getAlgorithmType() {
+ return Type.RSA;
+ }
}
static final class SHA256withRSA extends DOMSignatureMethod {
@@ -472,9 +360,12 @@
public String getAlgorithm() {
return RSA_SHA256;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "SHA256withRSA";
}
+ Type getAlgorithmType() {
+ return Type.RSA;
+ }
}
static final class SHA384withRSA extends DOMSignatureMethod {
@@ -488,9 +379,12 @@
public String getAlgorithm() {
return RSA_SHA384;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "SHA384withRSA";
}
+ Type getAlgorithmType() {
+ return Type.RSA;
+ }
}
static final class SHA512withRSA extends DOMSignatureMethod {
@@ -504,9 +398,12 @@
public String getAlgorithm() {
return RSA_SHA512;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "SHA512withRSA";
}
+ Type getAlgorithmType() {
+ return Type.RSA;
+ }
}
static final class SHA1withDSA extends DOMSignatureMethod {
@@ -520,8 +417,87 @@
public String getAlgorithm() {
return SignatureMethod.DSA_SHA1;
}
- String getSignatureAlgorithm() {
+ String getJCAAlgorithm() {
return "SHA1withDSA";
}
+ Type getAlgorithmType() {
+ return Type.DSA;
+ }
+ }
+
+ static final class SHA1withECDSA extends DOMSignatureMethod {
+ SHA1withECDSA(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException {
+ super(params);
+ }
+ SHA1withECDSA(Element dmElem) throws MarshalException {
+ super(dmElem);
+ }
+ public String getAlgorithm() {
+ return ECDSA_SHA1;
+ }
+ String getJCAAlgorithm() {
+ return "SHA1withECDSA";
+ }
+ Type getAlgorithmType() {
+ return Type.ECDSA;
+ }
+ }
+
+ static final class SHA256withECDSA extends DOMSignatureMethod {
+ SHA256withECDSA(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException {
+ super(params);
+ }
+ SHA256withECDSA(Element dmElem) throws MarshalException {
+ super(dmElem);
+ }
+ public String getAlgorithm() {
+ return ECDSA_SHA256;
+ }
+ String getJCAAlgorithm() {
+ return "SHA256withECDSA";
+ }
+ Type getAlgorithmType() {
+ return Type.ECDSA;
+ }
+ }
+
+ static final class SHA384withECDSA extends DOMSignatureMethod {
+ SHA384withECDSA(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException {
+ super(params);
+ }
+ SHA384withECDSA(Element dmElem) throws MarshalException {
+ super(dmElem);
+ }
+ public String getAlgorithm() {
+ return ECDSA_SHA384;
+ }
+ String getJCAAlgorithm() {
+ return "SHA384withECDSA";
+ }
+ Type getAlgorithmType() {
+ return Type.ECDSA;
+ }
+ }
+
+ static final class SHA512withECDSA extends DOMSignatureMethod {
+ SHA512withECDSA(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException {
+ super(params);
+ }
+ SHA512withECDSA(Element dmElem) throws MarshalException {
+ super(dmElem);
+ }
+ public String getAlgorithm() {
+ return ECDSA_SHA512;
+ }
+ String getJCAAlgorithm() {
+ return "SHA512withECDSA";
+ }
+ Type getAlgorithmType() {
+ return Type.ECDSA;
+ }
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperties.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMSignatureProperties.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignatureProperties.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -31,6 +33,7 @@
import javax.xml.crypto.dsig.*;
import java.util.*;
+
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -46,7 +49,7 @@
implements SignatureProperties {
private final String id;
- private final List properties;
+ private final List<SignatureProperty> properties;
/**
* Creates a <code>DOMSignatureProperties</code> from the specified
@@ -61,20 +64,22 @@
* @throws IllegalArgumentException if <code>properties</code> is empty
* @throws NullPointerException if <code>properties</code>
*/
- public DOMSignatureProperties(List properties, String id) {
+ public DOMSignatureProperties(List<? extends SignatureProperty> 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<SignatureProperty>(properties));
+ for (int i = 0, size = this.properties.size(); i < size; i++) {
+ if (!(this.properties.get(i) instanceof SignatureProperty)) {
throw new ClassCastException
("properties["+i+"] is not a valid type");
}
}
- this.properties = Collections.unmodifiableList(propsCopy);
}
this.id = id;
}
@@ -85,7 +90,9 @@
* @param propsElem a SignatureProperties element
* @throws MarshalException if a marshalling error occurs
*/
- public DOMSignatureProperties(Element propsElem) throws MarshalException{
+ public DOMSignatureProperties(Element propsElem, XMLCryptoContext context)
+ throws MarshalException
+ {
// unmarshal attributes
Attr attr = propsElem.getAttributeNodeNS(null, "Id");
if (attr != null) {
@@ -97,11 +104,13 @@
NodeList nodes = propsElem.getChildNodes();
int length = nodes.getLength();
- List properties = new ArrayList(length);
+ List<SignatureProperty> properties =
+ new ArrayList<SignatureProperty>(length);
for (int i = 0; i < length; i++) {
Node child = nodes.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
- properties.add(new DOMSignatureProperty((Element) child));
+ properties.add(new DOMSignatureProperty((Element)child,
+ context));
}
}
if (properties.isEmpty()) {
@@ -120,25 +129,27 @@
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
- Element propsElem = DOMUtils.createElement
- (ownerDoc, "SignatureProperties", XMLSignature.XMLNS, dsPrefix);
+ Element propsElem = DOMUtils.createElement(ownerDoc,
+ "SignatureProperties",
+ XMLSignature.XMLNS,
+ dsPrefix);
// set attributes
DOMUtils.setAttributeID(propsElem, "Id", id);
// create and append any properties
- for (int i = 0, size = properties.size(); i < size; i++) {
- DOMSignatureProperty property =
- (DOMSignatureProperty) properties.get(i);
- property.marshal(propsElem, dsPrefix, context);
+ for (SignatureProperty property : properties) {
+ ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix,
+ context);
}
parent.appendChild(propsElem);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -147,11 +158,22 @@
if (!(o instanceof SignatureProperties)) {
return false;
}
- SignatureProperties osp = (SignatureProperties) o;
+ SignatureProperties osp = (SignatureProperties)o;
- boolean idsEqual = (id == null ? osp.getId() == null :
- id.equals(osp.getId()));
+ boolean idsEqual = (id == null ? osp.getId() == null
+ : id.equals(osp.getId()));
return (properties.equals(osp.getProperties()) && idsEqual);
}
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (id != null) {
+ result = 31 * result + id.hashCode();
+ }
+ result = 31 * result + properties.hashCode();
+
+ return result;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignatureProperty.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMSignatureProperty.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignatureProperty.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -31,6 +33,7 @@
import javax.xml.crypto.dsig.*;
import java.util.*;
+
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -47,7 +50,7 @@
private final String id;
private final String target;
- private final List content;
+ private final List<XMLStructure> content;
/**
* Creates a <code>SignatureProperty</code> from the specified parameters.
@@ -63,7 +66,9 @@
* @throws NullPointerException if <code>content</code> or
* <code>target</code> is <code>null</code>
*/
- public DOMSignatureProperty(List content, String target, String id) {
+ public DOMSignatureProperty(List<? extends XMLStructure> content,
+ String target, String id)
+ {
if (target == null) {
throw new NullPointerException("target cannot be null");
} else if (content == null) {
@@ -71,14 +76,14 @@
} else if (content.isEmpty()) {
throw new IllegalArgumentException("content cannot be empty");
} else {
- List contentCopy = new ArrayList(content);
- for (int i = 0, size = contentCopy.size(); i < size; i++) {
- if (!(contentCopy.get(i) instanceof XMLStructure)) {
+ this.content = Collections.unmodifiableList(
+ new ArrayList<XMLStructure>(content));
+ for (int i = 0, size = this.content.size(); i < size; i++) {
+ if (!(this.content.get(i) instanceof XMLStructure)) {
throw new ClassCastException
("content["+i+"] is not a valid type");
}
}
- this.content = Collections.unmodifiableList(contentCopy);
}
this.target = target;
this.id = id;
@@ -89,7 +94,9 @@
*
* @param propElem a SignatureProperty element
*/
- public DOMSignatureProperty(Element propElem) throws MarshalException {
+ public DOMSignatureProperty(Element propElem, XMLCryptoContext context)
+ throws MarshalException
+ {
// unmarshal attributes
target = DOMUtils.getAttributeValue(propElem, "Target");
if (target == null) {
@@ -105,7 +112,7 @@
NodeList nodes = propElem.getChildNodes();
int length = nodes.getLength();
- List content = new ArrayList(length);
+ List<XMLStructure> content = new ArrayList<XMLStructure>(length);
for (int i = 0; i < length; i++) {
content.add(new javax.xml.crypto.dom.DOMStructure(nodes.item(i)));
}
@@ -129,26 +136,26 @@
}
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
-
- Element propElem = DOMUtils.createElement
- (ownerDoc, "SignatureProperty", XMLSignature.XMLNS, dsPrefix);
+ Element propElem = DOMUtils.createElement(ownerDoc, "SignatureProperty",
+ XMLSignature.XMLNS, dsPrefix);
// set attributes
DOMUtils.setAttributeID(propElem, "Id", id);
DOMUtils.setAttribute(propElem, "Target", target);
// create and append any elements and mixed content
- for (int i = 0, size = content.size(); i < size; i++) {
- javax.xml.crypto.dom.DOMStructure property =
- (javax.xml.crypto.dom.DOMStructure) content.get(i);
- DOMUtils.appendChild(propElem, property.getNode());
+ for (XMLStructure property : content) {
+ DOMUtils.appendChild(propElem,
+ ((javax.xml.crypto.dom.DOMStructure)property).getNode());
}
parent.appendChild(propElem);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -157,31 +164,43 @@
if (!(o instanceof SignatureProperty)) {
return false;
}
- SignatureProperty osp = (SignatureProperty) o;
+ SignatureProperty osp = (SignatureProperty)o;
+
+ boolean idsEqual = (id == null ? osp.getId() == null
+ : id.equals(osp.getId()));
- boolean idsEqual = (id == null ? osp.getId() == null :
- id.equals(osp.getId()));
-
- return (equalsContent(osp.getContent()) &&
- target.equals(osp.getTarget()) && idsEqual);
+ @SuppressWarnings("unchecked")
+ List<XMLStructure> 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<XMLStructure> 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;
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSignedInfo.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMSignedInfo.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -33,13 +35,11 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
+import java.io.OutputStream;
import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
import java.security.Provider;
import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -47,7 +47,6 @@
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
/**
* DOM-based implementation of SignedInfo.
@@ -57,12 +56,12 @@
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 @@
private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
Constants.MoreAlgorithmsSpecNS + "hmac-md5";
- private List references;
+ private List<Reference> references;
private CanonicalizationMethod canonicalizationMethod;
private SignatureMethod signatureMethod;
private String id;
@@ -95,14 +94,14 @@
* type <code>Reference</code>
*/
public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm,
- List references) {
+ List<? extends Reference> 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<Reference>(references));
if (this.references.isEmpty()) {
throw new IllegalArgumentException("list of references must " +
"contain at least one entry");
@@ -132,7 +131,7 @@
* type <code>Reference</code>
*/
public DOMSignedInfo(CanonicalizationMethod cm, SignatureMethod sm,
- List references, String id) {
+ List<? extends Reference> references, String id) {
this(cm, sm, references);
this.id = id;
}
@@ -142,8 +141,8 @@
*
* @param siElem a SignedInfo element
*/
- public DOMSignedInfo(Element siElem, XMLCryptoContext context,
- Provider provider) throws MarshalException {
+ public DOMSignedInfo(Element siElem, XMLCryptoContext context, Provider provider)
+ throws MarshalException {
localSiElem = siElem;
ownerDoc = siElem.getOwnerDocument();
@@ -152,26 +151,26 @@
// 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<Reference> refList = new ArrayList<Reference>(5);
Element refElem = DOMUtils.getNextSiblingElement(smElem);
+
int refCount = 0;
while (refElem != null) {
refList.add(new DOMReference(refElem, context, provider));
@@ -179,9 +178,8 @@
refCount++;
if (secVal && (refCount > MAXIMUM_REFERENCE_COUNT)) {
- String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT +
- " references per SignedInfo are allowed with" +
- " secure validation";
+ String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " "
+ + "references per Manifest are allowed with secure validation";
throw new MarshalException(error);
}
}
@@ -208,9 +206,8 @@
return canonData;
}
- public void canonicalize(XMLCryptoContext context,ByteArrayOutputStream bos)
+ public void canonicalize(XMLCryptoContext context, ByteArrayOutputStream bos)
throws XMLSignatureException {
-
if (context == null) {
throw new NullPointerException("context cannot be null");
}
@@ -219,14 +216,17 @@
try {
os.close();
} catch (IOException e) {
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, e.getMessage(), e);
+ }
// Impossible
}
DOMSubTreeData subTree = new DOMSubTreeData(localSiElem, true);
try {
- Data data = ((DOMCanonicalizationMethod)
- canonicalizationMethod).canonicalize(subTree, context, os);
+ ((DOMCanonicalizationMethod)
+ canonicalizationMethod).canonicalize(subTree, context, bos);
} catch (TransformException te) {
throw new XMLSignatureException(te);
}
@@ -234,44 +234,37 @@
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 @@
localSiElem = siElem;
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -289,13 +283,26 @@
if (!(o instanceof SignedInfo)) {
return false;
}
- SignedInfo osi = (SignedInfo) o;
+ SignedInfo osi = (SignedInfo)o;
- boolean idEqual = (id == null ? osi.getId() == null :
- id.equals(osi.getId()));
+ boolean idEqual = (id == null ? osi.getId() == null
+ : id.equals(osi.getId()));
return (canonicalizationMethod.equals(osi.getCanonicalizationMethod())
- && signatureMethod.equals(osi.getSignatureMethod()) &&
- references.equals(osi.getReferences()) && idEqual);
+ && 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;
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMStructure.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMSubTreeData.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2006 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMSubTreeData.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id$
*/
package org.jcp.xml.dsig.internal.dom;
@@ -45,17 +47,15 @@
public class DOMSubTreeData implements NodeSetData {
private boolean excludeComments;
- private Iterator ni;
private Node root;
public DOMSubTreeData(Node root, boolean excludeComments) {
this.root = root;
- this.ni = new DelayedNodeIterator(root, excludeComments);
this.excludeComments = excludeComments;
}
public Iterator iterator() {
- return ni;
+ return new DelayedNodeIterator(root, excludeComments);
}
public Node getRoot() {
@@ -70,10 +70,10 @@
* This is an Iterator that contains a backing node-set that is
* not populated until the caller first attempts to advance the iterator.
*/
- static class DelayedNodeIterator implements Iterator {
+ static class DelayedNodeIterator implements Iterator<Node> {
private Node root;
- private List nodeSet;
- private ListIterator li;
+ private List<Node> nodeSet;
+ private ListIterator<Node> li;
private boolean withComments;
DelayedNodeIterator(Node root, boolean excludeComments) {
@@ -89,13 +89,13 @@
return li.hasNext();
}
- public Object next() {
+ public Node next() {
if (nodeSet == null) {
nodeSet = dereferenceSameDocumentURI(root);
li = nodeSet.listIterator();
}
if (li.hasNext()) {
- return (Node) li.next();
+ return li.next();
} else {
throw new NoSuchElementException();
}
@@ -109,11 +109,11 @@
* Dereferences a same-document URI fragment.
*
* @param node the node (document or element) referenced by the
- * URI fragment. If null, returns an empty set.
+ * URI fragment. If null, returns an empty set.
* @return a set of nodes (minus any comment nodes)
*/
- private List dereferenceSameDocumentURI(Node node) {
- List nodeSet = new ArrayList();
+ private List<Node> dereferenceSameDocumentURI(Node node) {
+ List<Node> nodeSet = new ArrayList<Node>();
if (node != null) {
nodeSetMinusCommentNodes(node, nodeSet, null);
}
@@ -129,8 +129,10 @@
* @param nodeSet the set of nodes traversed so far
* @param the previous sibling node
*/
- private void nodeSetMinusCommentNodes(Node node, List nodeSet,
- Node prevSibling) {
+ @SuppressWarnings("fallthrough")
+ private void nodeSetMinusCommentNodes(Node node, List<Node> nodeSet,
+ Node prevSibling)
+ {
switch (node.getNodeType()) {
case Node.ELEMENT_NODE :
NamedNodeMap attrs = node.getAttributes();
@@ -140,8 +142,15 @@
}
}
nodeSet.add(node);
+ Node pSibling = null;
+ for (Node child = node.getFirstChild(); child != null;
+ child = child.getNextSibling()) {
+ nodeSetMinusCommentNodes(child, nodeSet, pSibling);
+ pSibling = child;
+ }
+ break;
case Node.DOCUMENT_NODE :
- Node pSibling = null;
+ pSibling = null;
for (Node child = node.getFirstChild(); child != null;
child = child.getNextSibling()) {
nodeSetMinusCommentNodes(child, nodeSet, pSibling);
@@ -154,8 +163,11 @@
// 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;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMTransform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMTransform.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -35,13 +37,11 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dsig.dom.DOMSignContext;
-import javax.xml.crypto.dsig.spec.TransformParameterSpec;
/**
* DOM-based abstract implementation of Transform.
@@ -69,15 +69,26 @@
* @param transElem a Transform element
*/
public DOMTransform(Element transElem, XMLCryptoContext context,
- Provider provider) throws MarshalException {
+ Provider provider)
+ throws MarshalException
+ {
String algorithm = DOMUtils.getAttributeValue(transElem, "Algorithm");
- try {
- spi = TransformService.getInstance(algorithm, "DOM");
- } catch (NoSuchAlgorithmException e1) {
+
+ if (provider == null) {
+ try {
+ spi = TransformService.getInstance(algorithm, "DOM");
+ } catch (NoSuchAlgorithmException e1) {
+ throw new MarshalException(e1);
+ }
+ } else {
try {
spi = TransformService.getInstance(algorithm, "DOM", provider);
- } catch (NoSuchAlgorithmException e2) {
- throw new MarshalException(e2);
+ } catch (NoSuchAlgorithmException nsae) {
+ try {
+ spi = TransformService.getInstance(algorithm, "DOM");
+ } catch (NoSuchAlgorithmException e2) {
+ throw new MarshalException(e2);
+ }
}
}
try {
@@ -100,21 +111,25 @@
* method to marshal any algorithm-specific parameters.
*/
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
Element transformElem = null;
if (parent.getLocalName().equals("Transforms")) {
- transformElem = DOMUtils.createElement
- (ownerDoc, "Transform", XMLSignature.XMLNS, dsPrefix);
+ transformElem = DOMUtils.createElement(ownerDoc, "Transform",
+ XMLSignature.XMLNS,
+ dsPrefix);
} else {
- transformElem = DOMUtils.createElement
- (ownerDoc, "CanonicalizationMethod", XMLSignature.XMLNS, dsPrefix);
+ transformElem = DOMUtils.createElement(ownerDoc,
+ "CanonicalizationMethod",
+ XMLSignature.XMLNS,
+ dsPrefix);
}
DOMUtils.setAttribute(transformElem, "Algorithm", getAlgorithm());
- spi.marshalParams
- (new javax.xml.crypto.dom.DOMStructure(transformElem), context);
+ spi.marshalParams(new javax.xml.crypto.dom.DOMStructure(transformElem),
+ context);
parent.appendChild(transformElem);
}
@@ -131,7 +146,8 @@
* executing the transform
*/
public Data transform(Data data, XMLCryptoContext xc)
- throws TransformException {
+ throws TransformException
+ {
return spi.transform(data, xc);
}
@@ -149,10 +165,12 @@
* executing the transform
*/
public Data transform(Data data, XMLCryptoContext xc, OutputStream os)
- throws TransformException {
+ throws TransformException
+ {
return spi.transform(data, xc, os);
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -161,11 +179,23 @@
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 @@
* 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);
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMURIDereferencer.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMURIDereferencer.java 1231033 2012-01-13 12:12:12Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -37,7 +39,6 @@
import javax.xml.crypto.*;
import javax.xml.crypto.dom.*;
-import javax.xml.crypto.dsig.*;
/**
* DOM-based implementation of URIDereferencer.
@@ -82,21 +83,17 @@
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);
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMUtils.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMUtils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMUtils.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -34,7 +36,6 @@
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.spec.*;
@@ -56,7 +57,7 @@
*/
public static Document getOwnerDocument(Node node) {
if (node.getNodeType() == Node.DOCUMENT_NODE) {
- return (Document) node;
+ return (Document)node;
} else {
return node.getOwnerDocument();
}
@@ -72,8 +73,9 @@
* @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 @@
* @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 @@
* @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 @@
while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
child = child.getNextSibling();
}
- return (Element) child;
+ return (Element)child;
}
/**
@@ -139,7 +145,7 @@
while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
child = child.getPreviousSibling();
}
- return (Element) child;
+ return (Element)child;
}
/**
@@ -156,7 +162,7 @@
while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
sibling = sibling.getNextSibling();
}
- return (Element) sibling;
+ return (Element)sibling;
}
/**
@@ -185,25 +191,25 @@
* @param nl the NodeList
* @return a Set of Nodes
*/
- public static Set nodeSet(NodeList nl) {
+ public static Set<Node> nodeSet(NodeList nl) {
return new NodeSet(nl);
}
- static class NodeSet extends AbstractSet {
+ static class NodeSet extends AbstractSet<Node> {
private NodeList nl;
public NodeSet(NodeList nl) {
this.nl = nl;
}
public int size() { return nl.getLength(); }
- public Iterator iterator() {
- return new Iterator() {
+ public Iterator<Node> iterator() {
+ return new Iterator<Node>() {
int index = 0;
public void remove() {
throw new UnsupportedOperationException();
}
- public Object next() {
+ public Node next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
@@ -291,39 +297,41 @@
}
if (spec1 instanceof XPathFilter2ParameterSpec &&
spec2 instanceof XPathFilter2ParameterSpec) {
- return paramsEqual((XPathFilter2ParameterSpec) spec1,
- (XPathFilter2ParameterSpec) spec2);
+ return paramsEqual((XPathFilter2ParameterSpec)spec1,
+ (XPathFilter2ParameterSpec)spec2);
}
if (spec1 instanceof ExcC14NParameterSpec &&
spec2 instanceof ExcC14NParameterSpec) {
return paramsEqual((ExcC14NParameterSpec) spec1,
- (ExcC14NParameterSpec) spec2);
+ (ExcC14NParameterSpec)spec2);
}
if (spec1 instanceof XPathFilterParameterSpec &&
spec2 instanceof XPathFilterParameterSpec) {
- return paramsEqual((XPathFilterParameterSpec) spec1,
- (XPathFilterParameterSpec) spec2);
+ return paramsEqual((XPathFilterParameterSpec)spec1,
+ (XPathFilterParameterSpec)spec2);
}
if (spec1 instanceof XSLTTransformParameterSpec &&
spec2 instanceof XSLTTransformParameterSpec) {
- return paramsEqual((XSLTTransformParameterSpec) spec1,
- (XSLTTransformParameterSpec) spec2);
+ return paramsEqual((XSLTTransformParameterSpec)spec1,
+ (XSLTTransformParameterSpec)spec2);
}
return false;
}
private static boolean paramsEqual(XPathFilter2ParameterSpec spec1,
- XPathFilter2ParameterSpec spec2) {
-
- List types = spec1.getXPathList();
- List otypes = spec2.getXPathList();
+ XPathFilter2ParameterSpec spec2)
+ {
+ @SuppressWarnings("unchecked")
+ List<XPathType> types = spec1.getXPathList();
+ @SuppressWarnings("unchecked")
+ List<XPathType> otypes = spec2.getXPathList();
int size = types.size();
if (size != otypes.size()) {
return false;
}
for (int i = 0; i < size; i++) {
- XPathType type = (XPathType) types.get(i);
- XPathType otype = (XPathType) otypes.get(i);
+ XPathType type = types.get(i);
+ XPathType otype = otypes.get(i);
if (!type.getExpression().equals(otype.getExpression()) ||
!type.getNamespaceMap().equals(otype.getNamespaceMap()) ||
type.getFilter() != otype.getFilter()) {
@@ -334,18 +342,21 @@
}
private static boolean paramsEqual(ExcC14NParameterSpec spec1,
- ExcC14NParameterSpec spec2) {
+ ExcC14NParameterSpec spec2)
+ {
return spec1.getPrefixList().equals(spec2.getPrefixList());
}
private static boolean paramsEqual(XPathFilterParameterSpec spec1,
- XPathFilterParameterSpec spec2) {
+ 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)) {
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509Data.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMX509Data.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMX509Data.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -51,7 +53,7 @@
//@@@ check for illegal combinations of data violating MUSTs in W3c spec
public final class DOMX509Data extends DOMStructure implements X509Data {
- private final List content;
+ private final List<Object> content;
private CertificateFactory cf;
/**
@@ -69,18 +71,18 @@
* @throws ClassCastException if <code>content</code> 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<Object> contentCopy = new ArrayList<Object>(content);
if (contentCopy.isEmpty()) {
throw new IllegalArgumentException("content cannot be empty");
}
for (int i = 0, size = contentCopy.size(); i < size; i++) {
Object x509Type = contentCopy.get(i);
if (x509Type instanceof String) {
- new X500Principal((String) x509Type);
+ new X500Principal((String)x509Type);
} else if (!(x509Type instanceof byte[]) &&
!(x509Type instanceof X509Certificate) &&
!(x509Type instanceof X509CRL) &&
@@ -102,7 +104,7 @@
// get all children nodes
NodeList nl = xdElem.getChildNodes();
int length = nl.getLength();
- List content = new ArrayList(length);
+ List<Object> content = new ArrayList<Object>(length);
for (int i = 0; i < length; i++) {
Node child = nl.item(i);
// ignore all non-Element nodes
@@ -110,7 +112,7 @@
continue;
}
- Element childElem = (Element) child;
+ Element childElem = (Element)child;
String localName = childElem.getLocalName();
if (localName.equals("X509Certificate")) {
content.add(unmarshalX509Certificate(childElem));
@@ -138,32 +140,32 @@
}
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 @@
}
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 @@
}
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 @@
}
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 @@
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 @@
}
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -257,9 +263,9 @@
if (!(o instanceof X509Data)) {
return false;
}
- X509Data oxd = (X509Data) o;
+ X509Data oxd = (X509Data)o;
- List ocontent = oxd.getContent();
+ @SuppressWarnings("unchecked") List<Object> ocontent = oxd.getContent();
int size = content.size();
if (size != ocontent.size()) {
return false;
@@ -270,7 +276,7 @@
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 @@
return true;
}
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + content.hashCode();
+
+ return result;
+ }
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMX509IssuerSerial.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* 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 void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
- throws MarshalException {
+ throws MarshalException
+ {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
- Element isElem = DOMUtils.createElement
- (ownerDoc, "X509IssuerSerial", XMLSignature.XMLNS, dsPrefix);
- Element inElem = DOMUtils.createElement
- (ownerDoc, "X509IssuerName", XMLSignature.XMLNS, dsPrefix);
- Element snElem = DOMUtils.createElement
- (ownerDoc, "X509SerialNumber", XMLSignature.XMLNS, dsPrefix);
+ Element isElem = DOMUtils.createElement(ownerDoc, "X509IssuerSerial",
+ XMLSignature.XMLNS, dsPrefix);
+ Element inElem = DOMUtils.createElement(ownerDoc, "X509IssuerName",
+ XMLSignature.XMLNS, dsPrefix);
+ Element snElem = DOMUtils.createElement(ownerDoc, "X509SerialNumber",
+ XMLSignature.XMLNS, dsPrefix);
inElem.appendChild(ownerDoc.createTextNode(issuerName));
snElem.appendChild(ownerDoc.createTextNode(serialNumber.toString()));
isElem.appendChild(inElem);
@@ -110,6 +113,7 @@
parent.appendChild(isElem);
}
+ @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
@@ -117,8 +121,17 @@
if (!(obj instanceof X509IssuerSerial)) {
return false;
}
- X509IssuerSerial ois = (X509IssuerSerial) obj;
+ X509IssuerSerial ois = (X509IssuerSerial)obj;
return (issuerName.equals(ois.getIssuerName()) &&
- serialNumber.equals(ois.getSerialNumber()));
+ serialNumber.equals(ois.getSerialNumber()));
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + issuerName.hashCode();
+ result = 31 * result + serialNumber.hashCode();
+
+ return result;
}
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLObject.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMXMLObject.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXMLObject.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -32,6 +34,7 @@
import java.security.Provider;
import java.util.*;
+
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -48,7 +51,8 @@
private final String id;
private final String mimeType;
private final String encoding;
- private final List content;
+ private final List<XMLStructure> content;
+ private Element objectElem;
/**
* Creates an <code>XMLObject</code> from the specified parameters.
@@ -63,19 +67,20 @@
* @throws ClassCastException if <code>content</code> contains any
* entries that are not of type {@link XMLStructure}
*/
- public DOMXMLObject(List content, String id, String mimeType,
- String encoding) {
+ public DOMXMLObject(List<? extends XMLStructure> 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<XMLStructure>(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 @@
* @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 @@
NodeList nodes = objElem.getChildNodes();
int length = nodes.getLength();
- List content = new ArrayList(length);
+ List<XMLStructure> content = new ArrayList<XMLStructure>(length);
for (int i = 0; i < length; i++) {
Node child = nodes.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
- Element childElem = (Element) child;
+ Element childElem = (Element)child;
String tag = childElem.getLocalName();
if (tag.equals("Manifest")) {
content.add(new DOMManifest(childElem, context, provider));
continue;
} else if (tag.equals("SignatureProperties")) {
- content.add(new DOMSignatureProperties(childElem));
+ content.add(new DOMSignatureProperties(childElem, context));
continue;
} else if (tag.equals("X509Data")) {
content.add(new DOMX509Data(childElem));
@@ -125,10 +132,11 @@
content.add(new javax.xml.crypto.dom.DOMStructure(child));
}
if (content.isEmpty()) {
- this.content = Collections.EMPTY_LIST;
+ this.content = Collections.emptyList();
} else {
this.content = Collections.unmodifiableList(content);
}
+ this.objectElem = objElem;
}
public List getContent() {
@@ -151,29 +159,32 @@
throws MarshalException {
Document ownerDoc = DOMUtils.getOwnerDocument(parent);
- Element objElem = DOMUtils.createElement
- (ownerDoc, "Object", XMLSignature.XMLNS, dsPrefix);
+ 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 @@
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<XMLStructure> 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<XMLStructure> 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;
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignature.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
@@ -29,7 +31,7 @@
* ===========================================================================
*/
/*
- * $Id: DOMXMLSignature.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXMLSignature.java 1333415 2012-05-03 12:03:51Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -40,7 +42,6 @@
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
-import java.io.*;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.Provider;
@@ -48,8 +49,7 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -67,11 +67,12 @@
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<XMLObject> objects;
private SignedInfo si;
private Document ownerDoc = null;
private Element localSigElem = null;
@@ -79,7 +80,7 @@
private boolean validationStatus;
private boolean validated = false;
private KeySelectorResult ksr;
- private HashMap signatureIdMap;
+ private HashMap<String, XMLStructure> signatureIdMap;
static {
com.sun.org.apache.xml.internal.security.Init.init();
@@ -98,8 +99,9 @@
* omit)
* @throws NullPointerException if <code>si</code> is <code>null</code>
*/
- public DOMXMLSignature(SignedInfo si, KeyInfo ki, List objs, String id,
- String signatureValueId)
+ public DOMXMLSignature(SignedInfo si, KeyInfo ki,
+ List<? extends XMLObject> objs,
+ String id, String signatureValueId)
{
if (si == null) {
throw new NullPointerException("signedInfo cannot be null");
@@ -108,16 +110,16 @@
this.id = id;
this.sv = new DOMSignatureValue(signatureValueId);
if (objs == null) {
- this.objects = Collections.EMPTY_LIST;
+ this.objects = Collections.emptyList();
} else {
- List objsCopy = new ArrayList(objs);
- for (int i = 0, size = objsCopy.size(); i < size; i++) {
- if (!(objsCopy.get(i) instanceof XMLObject)) {
+ this.objects =
+ Collections.unmodifiableList(new ArrayList<XMLObject>(objs));
+ for (int i = 0, size = this.objects.size(); i < size; i++) {
+ if (!(this.objects.get(i) instanceof XMLObject)) {
throw new ClassCastException
("objs["+i+"] is not an XMLObject");
}
}
- this.objects = Collections.unmodifiableList(objsCopy);
}
this.ki = ki;
}
@@ -129,7 +131,9 @@
* @throws MarshalException if XMLSignature cannot be unmarshalled
*/
public DOMXMLSignature(Element sigElem, XMLCryptoContext context,
- Provider provider) throws MarshalException {
+ Provider provider)
+ throws MarshalException
+ {
localSigElem = sigElem;
ownerDoc = localSigElem.getOwnerDocument();
@@ -142,7 +146,7 @@
// 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 @@
// unmarshal Objects, if specified
if (nextSibling == null) {
- objects = Collections.EMPTY_LIST;
+ objects = Collections.emptyList();
} else {
- List tempObjects = new ArrayList();
+ List<XMLObject> tempObjects = new ArrayList<XMLObject>();
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 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 boolean validate(XMLValidateContext vc)
- throws XMLSignatureException {
-
+ throws XMLSignatureException
+ {
if (vc == null) {
throw new NullPointerException("validateContext is null");
}
@@ -258,20 +263,20 @@
}
// validate all References
- List refs = this.si.getReferences();
+ @SuppressWarnings("unchecked")
+ List<Reference> refs = this.si.getReferences();
boolean validateRefs = true;
for (int i = 0, size = refs.size(); validateRefs && i < size; i++) {
- Reference ref = (Reference) refs.get(i);
+ Reference ref = refs.get(i);
boolean refValid = ref.validate(vc);
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Reference[" + ref.getURI() + "] is valid: "
- + refValid);
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Reference[" + ref.getURI() + "] is valid: " + refValid);
}
validateRefs &= refValid;
}
if (!validateRefs) {
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "Couldn't validate the References");
+ if (log.isLoggable(java.util.logging.Level.FINE)) {
+ log.log(java.util.logging.Level.FINE, "Couldn't validate the References");
}
validationStatus = false;
validated = true;
@@ -281,27 +286,30 @@
// validate Manifests, if property set
boolean validateMans = true;
if (Boolean.TRUE.equals(vc.getProperty
- ("org.jcp.xml.dsig.validateManifests"))) {
-
+ ("org.jcp.xml.dsig.validateManifests")))
+ {
for (int i=0, size=objects.size(); validateMans && i < size; i++) {
- XMLObject xo = (XMLObject) objects.get(i);
- List content = xo.getContent();
+ XMLObject xo = objects.get(i);
+ @SuppressWarnings("unchecked")
+ List<XMLStructure> 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<Reference> 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 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<Reference> allReferences = new ArrayList<Reference>();
// traverse the Signature and register all objects with IDs that
// may contain References
- signatureIdMap = new HashMap();
+ signatureIdMap = new HashMap<String, XMLStructure>();
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<Reference> 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<XMLStructure> 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<Reference> manRefs = man.getReferences();
+ for (Reference ref : manRefs) {
allReferences.add(ref);
signatureIdMap.put(ref.getId(), ref);
}
@@ -359,56 +365,51 @@
}
// always add SignedInfo references after Manifest references so
// that Manifest reference are digested first
- allReferences.addAll(si.getReferences());
+ allReferences.addAll(refs);
// generate/digest each reference
- for (int i = 0, size = allReferences.size(); i < size; i++) {
- DOMReference ref = (DOMReference) allReferences.get(i);
- digestReference(ref, signContext);
+ for (Reference ref : allReferences) {
+ digestReference((DOMReference)ref, signContext);
}
// do final sweep to digest any references that were skipped or missed
- for (int i = 0, size = allReferences.size(); i < size; i++) {
- DOMReference ref = (DOMReference) allReferences.get(i);
- if (ref.isDigested()) {
+ for (Reference ref : allReferences) {
+ if (((DOMReference)ref).isDigested()) {
continue;
}
- ref.digest(signContext);
+ ((DOMReference)ref).digest(signContext);
}
Key signingKey = null;
KeySelectorResult ksr = null;
try {
- ksr = signContext.getKeySelector().select
- (ki, KeySelector.Purpose.SIGN,
- si.getSignatureMethod(), signContext);
+ ksr = signContext.getKeySelector().select(ki,
+ KeySelector.Purpose.SIGN,
+ si.getSignatureMethod(),
+ signContext);
signingKey = ksr.getKey();
if (signingKey == null) {
throw new XMLSignatureException("the keySelector did not " +
- "find a signing key");
+ "find a signing key");
}
} catch (KeySelectorException kse) {
throw new XMLSignatureException("cannot find signing key", kse);
}
// calculate signature value
- byte[] val = null;
try {
- val = ((DOMSignatureMethod) si.getSignatureMethod()).sign
- (signingKey, (DOMSignedInfo) si, signContext);
+ byte[] val = ((AbstractDOMSignatureMethod)
+ si.getSignatureMethod()).sign(signingKey, si, signContext);
+ ((DOMSignatureValue)sv).setValue(val);
} catch (InvalidKeyException ike) {
throw new XMLSignatureException(ike);
}
- if (log.isLoggable(Level.FINE)) {
- log.log(Level.FINE, "SignatureValue = " + val);
- }
- ((DOMSignatureValue) sv).setValue(val);
-
this.localSigElem = sigElem;
this.ksr = ksr;
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -417,22 +418,39 @@
if (!(o instanceof XMLSignature)) {
return false;
}
- XMLSignature osig = (XMLSignature) o;
+ XMLSignature osig = (XMLSignature)o;
boolean idEqual =
(id == null ? osig.getId() == null : id.equals(osig.getId()));
boolean keyInfoEqual =
- (ki == null ? osig.getKeyInfo() == null :
- ki.equals(osig.getKeyInfo()));
+ (ki == null ? osig.getKeyInfo() == null
+ : ki.equals(osig.getKeyInfo()));
return (idEqual && keyInfoEqual &&
- sv.equals(osig.getSignatureValue()) &&
- si.equals(osig.getSignedInfo()) &&
- objects.equals(osig.getObjects()));
+ sv.equals(osig.getSignatureValue()) &&
+ si.equals(osig.getSignedInfo()) &&
+ objects.equals(osig.getObjects()));
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (id != null) {
+ result = 31 * result + id.hashCode();
+ }
+ if (ki != null) {
+ result = 31 * result + ki.hashCode();
+ }
+ result = 31 * result + sv.hashCode();
+ result = 31 * result + si.hashCode();
+ result = 31 * result + objects.hashCode();
+
+ return result;
}
private void digestReference(DOMReference ref, XMLSignContext signContext)
- throws XMLSignatureException {
+ throws XMLSignatureException
+ {
if (ref.isDigested()) {
return;
}
@@ -441,15 +459,15 @@
if (Utils.sameDocumentURI(uri)) {
String id = Utils.parseIdFromSameDocumentURI(uri);
if (id != null && signatureIdMap.containsKey(id)) {
- Object obj = signatureIdMap.get(id);
- if (obj instanceof DOMReference) {
- digestReference((DOMReference) obj, signContext);
- } else if (obj instanceof Manifest) {
- Manifest man = (Manifest) obj;
+ XMLStructure xs = signatureIdMap.get(id);
+ if (xs instanceof DOMReference) {
+ digestReference((DOMReference)xs, signContext);
+ } else if (xs instanceof Manifest) {
+ Manifest man = (Manifest)xs;
List manRefs = man.getReferences();
for (int i = 0, size = manRefs.size(); i < size; i++) {
- digestReference
- ((DOMReference) manRefs.get(i), signContext);
+ digestReference((DOMReference)manRefs.get(i),
+ signContext);
}
}
}
@@ -457,9 +475,9 @@
// reference dependencies in the XPath Transform - so be on
// the safe side, and skip and do at end in the final sweep
if (uri.length() == 0) {
- List transforms = ref.getTransforms();
- for (int i = 0, size = transforms.size(); i < size; i++) {
- Transform transform = (Transform) transforms.get(i);
+ @SuppressWarnings("unchecked")
+ List<Transform> 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 class DOMSignatureValue extends DOMStructure
- implements SignatureValue {
-
+ implements SignatureValue
+ {
private String id;
private byte[] value;
private String valueBase64;
@@ -485,7 +503,9 @@
this.id = id;
}
- DOMSignatureValue(Element sigValueElem) throws MarshalException {
+ DOMSignatureValue(Element sigValueElem, XMLCryptoContext context)
+ throws MarshalException
+ {
try {
// base64 decode signatureValue
value = Base64.decode(sigValueElem);
@@ -508,12 +528,12 @@
}
public byte[] getValue() {
- return (value == null) ? null : (byte[]) value.clone();
+ return (value == null) ? null : (byte[])value.clone();
}
public boolean validate(XMLValidateContext validateContext)
- throws XMLSignatureException {
-
+ throws XMLSignatureException
+ {
if (validateContext == null) {
throw new NullPointerException("context cannot be null");
}
@@ -531,18 +551,18 @@
(ki, KeySelector.Purpose.VERIFY, sm, validateContext);
validationKey = ksResult.getKey();
if (validationKey == null) {
- throw new XMLSignatureException("the keyselector did " +
- "not find a validation key");
+ throw new XMLSignatureException("the keyselector did not " +
+ "find a validation key");
}
} catch (KeySelectorException kse) {
throw new XMLSignatureException("cannot find validation " +
- "key", kse);
+ "key", kse);
}
// canonicalize SignedInfo and verify signature
try {
- validationStatus = ((DOMSignatureMethod) sm).verify
- (validationKey, (DOMSignedInfo) si, value, validateContext);
+ validationStatus = ((AbstractDOMSignatureMethod)sm).verify
+ (validationKey, si, value, validateContext);
} catch (Exception e) {
throw new XMLSignatureException(e);
}
@@ -552,6 +572,7 @@
return validationStatus;
}
+ @Override
public boolean equals(Object o) {
if (this == o) {
return true;
@@ -560,7 +581,7 @@
if (!(o instanceof SignatureValue)) {
return false;
}
- SignatureValue osv = (SignatureValue) o;
+ SignatureValue osv = (SignatureValue)o;
boolean idEqual =
(id == null ? osv.getId() == null : id.equals(osv.getId()));
@@ -569,12 +590,23 @@
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));
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXMLSignatureFactory.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,31 +2,34 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMXMLSignatureFactory.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXMLSignatureFactory.java 1333869 2012-05-04 10:42:44Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
import javax.xml.crypto.*;
+import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.*;
@@ -34,7 +37,6 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
-import java.security.spec.AlgorithmParameterSpec;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -56,6 +58,7 @@
return new DOMXMLSignature(si, ki, null, null, null);
}
+ @SuppressWarnings("unchecked")
public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki,
List objects, String id, String signatureValueId) {
return new DOMXMLSignature(si, ki, objects, id, signatureValueId);
@@ -65,11 +68,13 @@
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 @@
(uri, type, dm, appliedTransforms, result, transforms, id, getProvider());
}
+ @SuppressWarnings("unchecked")
public Reference newReference(String uri, DigestMethod dm, List transforms,
String type, String id, byte[] digestValue) {
if (digestValue == null) {
@@ -95,34 +101,41 @@
(uri, type, dm, null, null, transforms, id, digestValue, getProvider());
}
+ @SuppressWarnings("unchecked")
public SignedInfo newSignedInfo(CanonicalizationMethod cm,
SignatureMethod sm, List references) {
return newSignedInfo(cm, sm, references, null);
}
+ @SuppressWarnings("unchecked")
public SignedInfo newSignedInfo(CanonicalizationMethod cm,
SignatureMethod sm, List references, String id) {
return new DOMSignedInfo(cm, sm, references, id);
}
// Object factory methods
+ @SuppressWarnings("unchecked")
public XMLObject newXMLObject(List content, String id, String mimeType,
String encoding) {
return new DOMXMLObject(content, id, mimeType, encoding);
}
+ @SuppressWarnings("unchecked")
public Manifest newManifest(List references) {
return newManifest(references, null);
}
+ @SuppressWarnings("unchecked")
public Manifest newManifest(List references, String id) {
return new DOMManifest(references, id);
}
+ @SuppressWarnings("unchecked")
public SignatureProperties newSignatureProperties(List props, String id) {
return new DOMSignatureProperties(props, id);
}
+ @SuppressWarnings("unchecked")
public SignatureProperty newSignatureProperty
(List info, String target, String id) {
return new DOMSignatureProperty(info, target, id);
@@ -143,12 +156,19 @@
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 @@
return new DOMSignatureMethod.SHA1withDSA(params);
} else if (algorithm.equals(SignatureMethod.HMAC_SHA1)) {
return new DOMHMACSignatureMethod.SHA1(params);
- } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA256)) {
+ } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA256)) {
return new DOMHMACSignatureMethod.SHA256(params);
- } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA384)) {
+ } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA384)) {
return new DOMHMACSignatureMethod.SHA384(params);
- } else if (algorithm.equals(DOMSignatureMethod.HMAC_SHA512)) {
+ } else if (algorithm.equals(DOMHMACSignatureMethod.HMAC_SHA512)) {
return new DOMHMACSignatureMethod.SHA512(params);
+ } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA1)) {
+ return new DOMSignatureMethod.SHA1withECDSA(params);
+ } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA256)) {
+ return new DOMSignatureMethod.SHA256withECDSA(params);
+ } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA384)) {
+ return new DOMSignatureMethod.SHA384withECDSA(params);
+ } else if (algorithm.equals(DOMSignatureMethod.ECDSA_SHA512)) {
+ return new DOMSignatureMethod.SHA512withECDSA(params);
} else {
throw new NoSuchAlgorithmException("unsupported algorithm");
}
@@ -235,12 +263,18 @@
public Transform newTransform(String algorithm,
TransformParameterSpec params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
+
TransformService spi;
- try {
+ if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
- } catch (NoSuchAlgorithmException nsae) {
- spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+ } else {
+ try {
+ spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+ } catch (NoSuchAlgorithmException nsae) {
+ spi = TransformService.getInstance(algorithm, "DOM");
+ }
}
+
spi.init(params);
return new DOMTransform(spi);
}
@@ -249,11 +283,16 @@
XMLStructure params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
TransformService spi;
- try {
+ if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
- } catch (NoSuchAlgorithmException nsae) {
- spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+ } else {
+ try {
+ spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+ } catch (NoSuchAlgorithmException nsae) {
+ spi = TransformService.getInstance(algorithm, "DOM");
+ }
}
+
if (params == null) {
spi.init(null);
} else {
@@ -266,11 +305,16 @@
C14NMethodParameterSpec params) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
TransformService spi;
- try {
+ if (getProvider() == null) {
spi = TransformService.getInstance(algorithm, "DOM");
- } catch (NoSuchAlgorithmException nsae) {
- spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+ } else {
+ try {
+ spi = TransformService.getInstance(algorithm, "DOM", getProvider());
+ } catch (NoSuchAlgorithmException nsae) {
+ spi = TransformService.getInstance(algorithm, "DOM");
+ }
}
+
spi.init(params);
return new DOMCanonicalizationMethod(spi);
}
@@ -279,16 +323,21 @@
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);
}
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathFilter2Transform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* ===========================================================================
@@ -29,7 +31,7 @@
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMXPathFilter2Transform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXPathFilter2Transform.java 1203789 2011-11-18 18:46:07Z mullan $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -40,10 +42,10 @@
import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.util.ArrayList;
-import java.util.Iterator;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.HashMap;
+import java.util.Set;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
@@ -57,7 +59,8 @@
public final class DOMXPathFilter2Transform extends ApacheTransform {
public void init(TransformParameterSpec params)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
if (params == null) {
throw new InvalidAlgorithmParameterException("params are required");
} else if (!(params instanceof XPathFilter2ParameterSpec)) {
@@ -68,23 +71,23 @@
}
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<XPathType> list = new ArrayList<XPathType>();
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 @@
} 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<String, String> namespaceMap =
+ new HashMap<String, String>(length);
for (int i = 0; i < length; i++) {
- Attr attr = (Attr) attributes.item(i);
+ Attr attr = (Attr)attributes.item(i);
String prefix = attr.getPrefix();
if (prefix != null && prefix.equals("xmlns")) {
namespaceMap.put(attr.getLocalName(), attr.getValue());
@@ -121,32 +125,34 @@
}
public void marshalParams(XMLStructure parent, XMLCryptoContext context)
- throws MarshalException {
-
+ throws MarshalException
+ {
super.marshalParams(parent, context);
XPathFilter2ParameterSpec xp =
- (XPathFilter2ParameterSpec) getParameterSpec();
+ (XPathFilter2ParameterSpec)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<XPathType> 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<Map.Entry<String, String>> entries =
+ xpathType.getNamespaceMap().entrySet();
+ for (Map.Entry<String, String> entry : entries) {
+ elem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
+ entry.getKey(),
+ entry.getValue());
}
transformElem.appendChild(elem);
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXPathTransform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMXPathTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXPathTransform.java 1203789 2011-11-18 18:46:07Z mullan $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -31,9 +33,9 @@
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
import java.security.InvalidAlgorithmParameterException;
-import java.util.Iterator;
+import java.util.HashMap;
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;
@@ -47,7 +49,8 @@
public final class DOMXPathTransform extends ApacheTransform {
public void init(TransformParameterSpec params)
- throws InvalidAlgorithmParameterException {
+ throws InvalidAlgorithmParameterException
+ {
if (params == null) {
throw new InvalidAlgorithmParameterException("params are required");
} else if (!(params instanceof XPathFilterParameterSpec)) {
@@ -58,8 +61,8 @@
}
public void init(XMLStructure parent, XMLCryptoContext context)
- throws InvalidAlgorithmParameterException {
-
+ throws InvalidAlgorithmParameterException
+ {
super.init(parent, context);
unmarshalParams(DOMUtils.getFirstChildElement(transformElem));
}
@@ -70,9 +73,10 @@
NamedNodeMap attributes = paramsElem.getAttributes();
if (attributes != null) {
int length = attributes.getLength();
- Map namespaceMap = new HashMap(length);
+ Map<String, String> namespaceMap =
+ new HashMap<String, String>(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 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<Map.Entry<String, String>> entries =
+ xp.getNamespaceMap().entrySet();
+ for (Map.Entry<String, String> entry : entries) {
+ xpathElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" +
+ entry.getKey(),
+ entry.getValue());
}
transformElem.appendChild(xpathElem);
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMXSLTTransform.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: DOMXSLTTransform.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: DOMXSLTTransform.java 1197150 2011-11-03 14:34:57Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -31,7 +33,6 @@
import org.w3c.dom.Node;
import javax.xml.crypto.*;
-import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec;
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/Utils.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,27 +2,29 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: Utils.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: Utils.java 1197150 2011-11-03 14:34:57Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -44,7 +46,8 @@
private Utils() {}
public static byte[] readBytesFromStream(InputStream is)
- throws IOException {
+ throws IOException
+ {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
while (true) {
@@ -67,10 +70,10 @@
* @param i the Iterator
* @return the Set of Nodes
*/
- static Set toNodeSet(Iterator i) {
- Set nodeSet = new HashSet();
+ static Set<Node> toNodeSet(Iterator<Node> i) {
+ Set<Node> nodeSet = new HashSet<Node>();
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) {
--- a/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java Fri Jul 05 13:28:17 2013 -0700
+++ b/jdk/src/share/classes/org/jcp/xml/dsig/internal/dom/XMLDSigRI.java Fri Jul 05 14:37:41 2013 -0700
@@ -2,21 +2,23 @@
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
-/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
/*
* ===========================================================================
@@ -29,7 +31,7 @@
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
*/
/*
- * $Id: XMLDSigRI.java,v 1.2 2008/07/24 15:20:32 mullan Exp $
+ * $Id: XMLDSigRI.java 1400021 2012-10-19 10:16:04Z coheigea $
*/
package org.jcp.xml.dsig.internal.dom;
@@ -53,13 +55,15 @@
static final long serialVersionUID = -5049765099299494554L;
private static final String INFO = "XMLDSig " +
- "(DOM XMLSignatureFactory; DOM KeyInfoFactory)";
+ "(DOM XMLSignatureFactory; DOM KeyInfoFactory; " +
+ "C14N 1.0, C14N 1.1, Exclusive C14N, Base64, Enveloped, XPath, " +
+ "XPath2, XSLT TransformServices)";
public XMLDSigRI() {
/* We are the XMLDSig provider */
- super("XMLDSig", 1.0, INFO);
+ super("XMLDSig", 1.8, INFO);
- final Map map = new HashMap();
+ final Map<Object, Object> map = new HashMap<Object, Object>();
map.put("XMLSignatureFactory.DOM",
"org.jcp.xml.dsig.internal.dom.DOMXMLSignatureFactory");
map.put("KeyInfoFactory.DOM",
@@ -67,94 +71,89 @@
// Inclusive C14N
- map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE,
+ map.put("TransformService." + CanonicalizationMethod.INCLUSIVE,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE",
CanonicalizationMethod.INCLUSIVE);
- map.put((String)"TransformService." + CanonicalizationMethod.INCLUSIVE +
+ map.put("TransformService." + CanonicalizationMethod.INCLUSIVE +
" MechanismType", "DOM");
// InclusiveWithComments C14N
- map.put((String) "TransformService." +
+ map.put("TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14NMethod");
map.put("Alg.Alias.TransformService.INCLUSIVE_WITH_COMMENTS",
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS);
- map.put((String) "TransformService." +
+ map.put("TransformService." +
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS +
" MechanismType", "DOM");
// Inclusive C14N 1.1
- map.put((String)"TransformService." +
- "http://www.w3.org/2006/12/xml-c14n11",
+ map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11",
"org.jcp.xml.dsig.internal.dom.DOMCanonicalXMLC14N11Method");
- map.put((String)"TransformService." +
- "http://www.w3.org/2006/12/xml-c14n11" +
+ map.put("TransformService.http://www.w3.org/2006/12/xml-c14n11" +
" MechanismType", "DOM");
// InclusiveWithComments C14N 1.1
- map.put((String)"TransformService." +
- "http://www.w3.org/2006/12/xml-c14n11#WithComments",
+ 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<Void>() {
+ public Void run() {
putAll(map);
return null;
}