* MessageDigestAlgorithm.getInstance() @@ -44,6 +44,9 @@ Constants.MoreAlgorithmsSpecNS + "md5"; /** Digest - Required SHA1*/ public static final String ALGO_ID_DIGEST_SHA1 = Constants.SignatureSpecNS + "sha1"; + /** Message Digest - OPTIONAL SHA224*/ + public static final String ALGO_ID_DIGEST_SHA224 = + Constants.MoreAlgorithmsSpecNS + "sha224"; /** Message Digest - RECOMMENDED SHA256*/ public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; @@ -121,7 +124,7 @@ * * @return the actual {@link java.security.MessageDigest} algorithm object */ - public java.security.MessageDigest getAlgorithm() { + public MessageDigest getAlgorithm() { return algorithm; } @@ -134,7 +137,7 @@ * @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); + return MessageDigest.isEqual(digesta, digestb); } /** @@ -243,12 +246,12 @@ algorithm.update(buf, offset, len); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String getBaseNamespace() { return Constants.SignatureSpecNS; } - /** @inheritDoc */ + /** {@inheritDoc} */ public String getBaseLocalName() { return Constants._TAG_DIGESTMETHOD; } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithm.java @@ -46,13 +46,11 @@ * Allows selection of digital signature's algorithm, private keys, other * security parameters, and algorithm's ID. * - * @author Christian Geuer-Pollmann */ public class SignatureAlgorithm extends Algorithm { - /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SignatureAlgorithm.class.getName()); + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureAlgorithm.class); /** All available algorithm classes are registered here */ private static Map> algorithmHash = @@ -75,7 +73,7 @@ this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this.constructionElement); + signatureAlgorithm.engineGetContextFromElement(getElement()); } /** @@ -93,10 +91,10 @@ this.algorithmURI = algorithmURI; signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this.constructionElement); + signatureAlgorithm.engineGetContextFromElement(getElement()); signatureAlgorithm.engineSetHMACOutputLength(hmacOutputLength); - ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(constructionElement); + ((IntegrityHmac)signatureAlgorithm).engineAddContextToElement(getElement()); } /** @@ -107,7 +105,7 @@ * @throws XMLSecurityException */ public SignatureAlgorithm(Element element, String baseURI) throws XMLSecurityException { - this(element, baseURI, false); + this(element, baseURI, true); } /** @@ -137,7 +135,7 @@ } signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI); - signatureAlgorithm.engineGetContextFromElement(this.constructionElement); + signatureAlgorithm.engineGetContextFromElement(getElement()); } /** @@ -148,20 +146,16 @@ try { Class extends SignatureAlgorithmSpi> implementingClass = algorithmHash.get(algorithmURI); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" - + implementingClass + "\""); + LOG.debug("Create URI \"{}\" class \"{}\"", algorithmURI, implementingClass); + if (implementingClass == null) { + Object exArgs[] = { algorithmURI }; + throw new XMLSignatureException("algorithms.NoSuchAlgorithmNoEx", exArgs); } - return implementingClass.newInstance(); - } catch (IllegalAccessException ex) { + SignatureAlgorithmSpi tmp = implementingClass.newInstance(); + return tmp; + } catch (IllegalAccessException | InstantiationException | NullPointerException ex) { Object exArgs[] = { algorithmURI, ex.getMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); - } catch (InstantiationException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); - } catch (NullPointerException ex) { - Object exArgs[] = { algorithmURI, ex.getMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); + throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs); } } @@ -311,14 +305,14 @@ * @return the URI representation of Transformation algorithm */ public final String getURI() { - return constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return getLocalAttribute(Constants._ATT_ALGORITHM); } /** * Registers implementing class of the SignatureAlgorithm with algorithmURI * - * @param algorithmURI algorithmURI URI representation of SignatureAlgorithm
. - * @param implementingClassimplementingClass
the implementing class of + * @param algorithmURI algorithmURI URI representation of {@code SignatureAlgorithm}. + * @param implementingClass {@code implementingClass} the implementing class of * {@link SignatureAlgorithmSpi} * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered * @throws XMLSignatureException @@ -330,9 +324,7 @@ throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, XMLSignatureException { JavaUtils.checkRegisterPermission(); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); - } + LOG.debug("Try to register {} {}", algorithmURI, implementingClass); // are we already registered? Class extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI); @@ -349,15 +341,15 @@ algorithmHash.put(algorithmURI, clazz); } catch (NullPointerException ex) { Object exArgs[] = { algorithmURI, ex.getMessage() }; - throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, ex); + throw new XMLSignatureException(ex, "algorithms.NoSuchAlgorithm", exArgs); } } /** - * Registers implementing class of the Transform algorithm with algorithmURI + * Registers implementing class of the SignatureAlgorithm with algorithmURI * - * @param algorithmURI algorithmURI URI representation ofSignatureAlgorithm
. - * @param implementingClassimplementingClass
the implementing class of + * @param algorithmURI algorithmURI URI representation of {@code SignatureAlgorithm}. + * @param implementingClass {@code implementingClass} the implementing class of * {@link SignatureAlgorithmSpi} * @throws AlgorithmAlreadyRegisteredException if specified algorithmURI is already registered * @throws XMLSignatureException @@ -368,9 +360,7 @@ throws AlgorithmAlreadyRegisteredException, ClassNotFoundException, XMLSignatureException { JavaUtils.checkRegisterPermission(); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); - } + LOG.debug("Try to register {} {}", algorithmURI, implementingClass); // are we already registered? Class extends SignatureAlgorithmSpi> registeredClass = algorithmHash.get(algorithmURI); @@ -408,6 +398,9 @@ SignatureBaseRSA.SignatureRSARIPEMD160.class ); algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224, SignatureBaseRSA.SignatureRSASHA224.class + ); + algorithmHash.put( XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256, SignatureBaseRSA.SignatureRSASHA256.class ); algorithmHash.put( @@ -417,9 +410,27 @@ XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512, SignatureBaseRSA.SignatureRSASHA512.class ); algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1, SignatureBaseRSA.SignatureRSASHA1MGF1.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1, SignatureBaseRSA.SignatureRSASHA224MGF1.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1, SignatureBaseRSA.SignatureRSASHA256MGF1.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1, SignatureBaseRSA.SignatureRSASHA384MGF1.class + ); + algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1, SignatureBaseRSA.SignatureRSASHA512MGF1.class + ); + algorithmHash.put( XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1, SignatureECDSA.SignatureECDSASHA1.class ); algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224, SignatureECDSA.SignatureECDSASHA224.class + ); + algorithmHash.put( XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256, SignatureECDSA.SignatureECDSASHA256.class ); algorithmHash.put( @@ -429,12 +440,18 @@ XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512, SignatureECDSA.SignatureECDSASHA512.class ); algorithmHash.put( + XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160, SignatureECDSA.SignatureECDSARIPEMD160.class + ); + algorithmHash.put( XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5, IntegrityHmac.IntegrityHmacMD5.class ); algorithmHash.put( XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160, IntegrityHmac.IntegrityHmacRIPEMD160.class ); algorithmHash.put( + XMLSignature.ALGO_ID_MAC_HMAC_SHA224, IntegrityHmac.IntegrityHmacSHA224.class + ); + algorithmHash.put( XMLSignature.ALGO_ID_MAC_HMAC_SHA256, IntegrityHmac.IntegrityHmacSHA256.class ); algorithmHash.put( diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/SignatureAlgorithmSpi.java @@ -32,9 +32,9 @@ public abstract class SignatureAlgorithmSpi { /** - * Returns the URI representation ofTransformation algorithm
+ * Returns the URI representation of {@code Transformation algorithm} * - * @return the URI representation ofTransformation algorithm
+ * @return the URI representation of {@code Transformation algorithm} */ protected abstract String engineGetURI(); diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java new file mode 100644 --- /dev/null +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/ECDSAUtils.java @@ -0,0 +1,918 @@ +/* + * 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.algorithms.implementations; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.interfaces.ECPublicKey; +import java.security.spec.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public final class ECDSAUtils { + + private ECDSAUtils() { + // complete + } + + /** + * Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param asn1Bytes + * @return the decode bytes + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { + + if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + int offset; + if (asn1Bytes[1] > 0) { + offset = 2; + } else if (asn1Bytes[1] == (byte) 0x81) { + offset = 3; + } else { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + + byte rLength = asn1Bytes[offset + 1]; + int i; + + for (i = rLength; i > 0 && asn1Bytes[offset + 2 + rLength - i] == 0; i--); //NOPMD + + byte sLength = asn1Bytes[offset + 2 + rLength + 1]; + int j; + + for (j = sLength; j > 0 && asn1Bytes[offset + 2 + rLength + 2 + sLength - j] == 0; j--); //NOPMD + + int rawLen = Math.max(i, j); + + if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset + || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength + || asn1Bytes[offset] != 2 + || asn1Bytes[offset + 2 + rLength] != 2) { + throw new IOException("Invalid ASN.1 format of ECDSA signature"); + } + byte xmldsigBytes[] = new byte[2 * rawLen]; + + System.arraycopy(asn1Bytes, offset + 2 + rLength - i, xmldsigBytes, rawLen - i, i); + System.arraycopy(asn1Bytes, offset + 2 + rLength + 2 + sLength - j, xmldsigBytes, + 2 * rawLen - j, j); + + return xmldsigBytes; + } + + /** + * Converts a XML Signature ECDSA Value to an ASN.1 DSA value. + * + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value + * pairs; the XML Signature requires the core BigInteger values. + * + * @param xmldsigBytes + * @return the encoded ASN.1 bytes + * @throws IOException + * @see 6.4.1 DSA + * @see 3.3. ECDSA Signatures + */ + public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { + + int rawLen = xmldsigBytes.length / 2; + + int i; + + for (i = rawLen; i > 0 && xmldsigBytes[rawLen - i] == 0; i--); //NOPMD + + int j = i; + + if (xmldsigBytes[rawLen - i] < 0) { + j += 1; + } + + int k; + + for (k = rawLen; k > 0 && xmldsigBytes[2 * rawLen - k] == 0; k--); //NOPMD + + int l = k; + + if (xmldsigBytes[2 * rawLen - k] < 0) { + l += 1; + } + + int len = 2 + j + 2 + l; + if (len > 255) { + throw new IOException("Invalid XMLDSIG format of ECDSA signature"); + } + int offset; + byte asn1Bytes[]; + if (len < 128) { + asn1Bytes = new byte[2 + 2 + j + 2 + l]; + offset = 1; + } else { + asn1Bytes = new byte[3 + 2 + j + 2 + l]; + asn1Bytes[1] = (byte) 0x81; + offset = 2; + } + asn1Bytes[0] = 48; + asn1Bytes[offset++] = (byte) len; + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) j; + + System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, offset + j - i, i); + + offset += j; + + asn1Bytes[offset++] = 2; + asn1Bytes[offset++] = (byte) l; + + System.arraycopy(xmldsigBytes, 2 * rawLen - k, asn1Bytes, offset + l - k, k); + + return asn1Bytes; + } + + private static final ListecCurveDefinitions = new ArrayList<>(); + + static { + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp112r1", + "1.3.132.0.6", + "db7c2abf62e35e668076bead208b", + "db7c2abf62e35e668076bead2088", + "659ef8ba043916eede8911702b22", + "09487239995a5ee76b55f9c2f098", + "a89ce5af8724c0a23e0e0ff77500", + "db7c2abf62e35e7628dfac6561c5", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp112r2", + "1.3.132.0.7", + "db7c2abf62e35e668076bead208b", + "6127c24c05f38a0aaaf65c0ef02c", + "51def1815db5ed74fcc34c85d709", + "4ba30ab5e892b4e1649dd0928643", + "adcd46f5882e3747def36e956e97", + "36df0aafd8b8d7597ca10520d04b", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp128r1", + "1.3.132.0.28", + "fffffffdffffffffffffffffffffffff", + "fffffffdfffffffffffffffffffffffc", + "e87579c11079f43dd824993c2cee5ed3", + "161ff7528b899b2d0c28607ca52c5b86", + "cf5ac8395bafeb13c02da292dded7a83", + "fffffffe0000000075a30d1b9038a115", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp128r2", + "1.3.132.0.29", + "fffffffdffffffffffffffffffffffff", + "d6031998d1b3bbfebf59cc9bbff9aee1", + "5eeefca380d02919dc2c6558bb6d8a5d", + "7b6aa5d85e572983e6fb32a7cdebc140", + "27b6916a894d3aee7106fe805fc34b44", + "3fffffff7fffffffbe0024720613b5a3", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp160k1", + "1.3.132.0.9", + "fffffffffffffffffffffffffffffffeffffac73", + "0000000000000000000000000000000000000000", + "0000000000000000000000000000000000000007", + "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb", + "938cf935318fdced6bc28286531733c3f03c4fee", + "0100000000000000000001b8fa16dfab9aca16b6b3", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp160r1", + "1.3.132.0.8", + "ffffffffffffffffffffffffffffffff7fffffff", + "ffffffffffffffffffffffffffffffff7ffffffc", + "1c97befc54bd7a8b65acf89f81d4d4adc565fa45", + "4a96b5688ef573284664698968c38bb913cbfc82", + "23a628553168947d59dcc912042351377ac5fb32", + "0100000000000000000001f4c8f927aed3ca752257", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp160r2", + "1.3.132.0.30", + "fffffffffffffffffffffffffffffffeffffac73", + "fffffffffffffffffffffffffffffffeffffac70", + "b4e134d3fb59eb8bab57274904664d5af50388ba", + "52dcb034293a117e1f4ff11b30f7199d3144ce6d", + "feaffef2e331f296e071fa0df9982cfea7d43f2e", + "0100000000000000000000351ee786a818f3a1a16b", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp192k1", + "1.3.132.0.31", + "fffffffffffffffffffffffffffffffffffffffeffffee37", + "000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000003", + "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d", + "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d", + "fffffffffffffffffffffffe26f2fc170f69466a74defd8d", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp192r1 [NIST P-192, X9.62 prime192v1]", + "1.2.840.10045.3.1.1", + "fffffffffffffffffffffffffffffffeffffffffffffffff", + "fffffffffffffffffffffffffffffffefffffffffffffffc", + "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", + "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", + "07192b95ffc8da78631011ed6b24cdd573f977a11e794811", + "ffffffffffffffffffffffff99def836146bc9b1b4d22831", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp224k1", + "1.3.132.0.32", + "fffffffffffffffffffffffffffffffffffffffffffffffeffffe56d", + "00000000000000000000000000000000000000000000000000000000", + "00000000000000000000000000000000000000000000000000000005", + "a1455b334df099df30fc28a169a467e9e47075a90f7e650eb6b7a45c", + "7e089fed7fba344282cafbd6f7e319f7c0b0bd59e2ca4bdb556d61a5", + "010000000000000000000000000001dce8d2ec6184caf0a971769fb1f7", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp224r1 [NIST P-224]", + "1.3.132.0.33", + "ffffffffffffffffffffffffffffffff000000000000000000000001", + "fffffffffffffffffffffffffffffffefffffffffffffffffffffffe", + "b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4", + "b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21", + "bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34", + "ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp256k1", + "1.3.132.0.10", + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", + "0000000000000000000000000000000000000000000000000000000000000000", + "0000000000000000000000000000000000000000000000000000000000000007", + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp256r1 [NIST P-256, X9.62 prime256v1]", + "1.2.840.10045.3.1.7", + "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", + "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", + "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", + "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", + "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", + "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp384r1 [NIST P-384]", + "1.3.132.0.34", + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff", + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc", + "b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef", + "aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7", + "3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f", + "ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "secp521r1 [NIST P-521]", + "1.3.132.0.35", + "01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + "01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc", + "0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00", + "00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", + "011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", + "01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 prime192v2", + "1.2.840.10045.3.1.2", + "fffffffffffffffffffffffffffffffeffffffffffffffff", + "fffffffffffffffffffffffffffffffefffffffffffffffc", + "cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953", + "eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a", + "6574d11d69b6ec7a672bb82a083df2f2b0847de970b2de15", + "fffffffffffffffffffffffe5fb1a724dc80418648d8dd31", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 prime192v3", + "1.2.840.10045.3.1.3", + "fffffffffffffffffffffffffffffffeffffffffffffffff", + "fffffffffffffffffffffffffffffffefffffffffffffffc", + "22123dc2395a05caa7423daeccc94760a7d462256bd56916", + "7d29778100c65a1da1783716588dce2b8b4aee8e228f1896", + "38a90f22637337334b49dcb66a6dc8f9978aca7648a943b0", + "ffffffffffffffffffffffff7a62d031c83f4294f640ec13", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 prime239v1", + "1.2.840.10045.3.1.4", + "7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff", + "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", + "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", + "0ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf", + "7debe8e4e90a5dae6e4054ca530ba04654b36818ce226b39fccb7b02f1ae", + "7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 prime239v2", + "1.2.840.10045.3.1.5", + "7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff", + "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", + "617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c", + "38af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7", + "5b0125e4dbea0ec7206da0fc01d9b081329fb555de6ef460237dff8be4ba", + "7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 prime239v3", + "1.2.840.10045.3.1.6", + "7fffffffffffffffffffffff7fffffffffff8000000000007fffffffffff", + "7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", + "255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e", + "6768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a", + "1607e6898f390c06bc1d552bad226f3b6fcfe48b6e818499af18e3ed6cf3", + "7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551", + 1) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect113r1", + "1.3.132.0.4", + "020000000000000000000000000201", + "003088250ca6e7c7fe649ce85820f7", + "00e8bee4d3e2260744188be0e9c723", + "009d73616f35f4ab1407d73562c10f", + "00a52830277958ee84d1315ed31886", + "0100000000000000d9ccec8a39e56f", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect113r2", + "1.3.132.0.5", + "020000000000000000000000000201", + "00689918dbec7e5a0dd6dfc0aa55c7", + "0095e9a9ec9b297bd4bf36e059184f", + "01a57a6a7b26ca5ef52fcdb8164797", + "00b3adc94ed1fe674c06e695baba1d", + "010000000000000108789b2496af93", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect131r1", + "1.3.132.0.22", + "080000000000000000000000000000010d", + "07a11b09a76b562144418ff3ff8c2570b8", + "0217c05610884b63b9c6c7291678f9d341", + "0081baf91fdf9833c40f9c181343638399", + "078c6e7ea38c001f73c8134b1b4ef9e150", + "0400000000000000023123953a9464b54d", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect131r2", + "1.3.132.0.23", + "080000000000000000000000000000010d", + "03e5a88919d7cafcbf415f07c2176573b2", + "04b8266a46c55657ac734ce38f018f2192", + "0356dcd8f2f95031ad652d23951bb366a8", + "0648f06d867940a5366d9e265de9eb240f", + "0400000000000000016954a233049ba98f", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect163k1 [NIST K-163]", + "1.3.132.0.1", + "0800000000000000000000000000000000000000c9", + "000000000000000000000000000000000000000001", + "000000000000000000000000000000000000000001", + "02fe13c0537bbc11acaa07d793de4e6d5e5c94eee8", + "0289070fb05d38ff58321f2e800536d538ccdaa3d9", + "04000000000000000000020108a2e0cc0d99f8a5ef", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect163r1", + "1.3.132.0.2", + "0800000000000000000000000000000000000000c9", + "07b6882caaefa84f9554ff8428bd88e246d2782ae2", + "0713612dcddcb40aab946bda29ca91f73af958afd9", + "0369979697ab43897789566789567f787a7876a654", + "00435edb42efafb2989d51fefce3c80988f41ff883", + "03ffffffffffffffffffff48aab689c29ca710279b", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect163r2 [NIST B-163]", + "1.3.132.0.15", + "0800000000000000000000000000000000000000c9", + "000000000000000000000000000000000000000001", + "020a601907b8c953ca1481eb10512f78744a3205fd", + "03f0eba16286a2d57ea0991168d4994637e8343e36", + "00d51fbc6c71a0094fa2cdd545b11c5c0c797324f1", + "040000000000000000000292fe77e70c12a4234c33", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect193r1", + "1.3.132.0.24", + "02000000000000000000000000000000000000000000008001", + "0017858feb7a98975169e171f77b4087de098ac8a911df7b01", + "00fdfb49bfe6c3a89facadaa7a1e5bbc7cc1c2e5d831478814", + "01f481bc5f0ff84a74ad6cdf6fdef4bf6179625372d8c0c5e1", + "0025e399f2903712ccf3ea9e3a1ad17fb0b3201b6af7ce1b05", + "01000000000000000000000000c7f34a778f443acc920eba49", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect193r2", + "1.3.132.0.25", + "02000000000000000000000000000000000000000000008001", + "0163f35a5137c2ce3ea6ed8667190b0bc43ecd69977702709b", + "00c9bb9e8927d4d64c377e2ab2856a5b16e3efb7f61d4316ae", + "00d9b67d192e0367c803f39e1a7e82ca14a651350aae617e8f", + "01ce94335607c304ac29e7defbd9ca01f596f927224cdecf6c", + "010000000000000000000000015aab561b005413ccd4ee99d5", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect233k1 [NIST K-233]", + "1.3.132.0.26", + "020000000000000000000000000000000000000004000000000000000001", + "000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000001", + "017232ba853a7e731af129f22ff4149563a419c26bf50a4c9d6eefad6126", + "01db537dece819b7f70f555a67c427a8cd9bf18aeb9b56e0c11056fae6a3", + "008000000000000000000000000000069d5bb915bcd46efb1ad5f173abdf", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect233r1 [NIST B-233]", + "1.3.132.0.27", + "020000000000000000000000000000000000000004000000000000000001", + "000000000000000000000000000000000000000000000000000000000001", + "0066647ede6c332c7f8c0923bb58213b333b20e9ce4281fe115f7d8f90ad", + "00fac9dfcbac8313bb2139f1bb755fef65bc391f8b36f8f8eb7371fd558b", + "01006a08a41903350678e58528bebf8a0beff867a7ca36716f7e01f81052", + "01000000000000000000000000000013e974e72f8a6922031d2603cfe0d7", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect239k1", + "1.3.132.0.3", + "800000000000000000004000000000000000000000000000000000000001", + "000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000001", + "29a0b6a887a983e9730988a68727a8b2d126c44cc2cc7b2a6555193035dc", + "76310804f12e549bdb011c103089e73510acb275fc312a5dc6b76553f0ca", + "2000000000000000000000000000005a79fec67cb6e91f1c1da800e478a5", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect283k1 [NIST K-283]", + "1.3.132.0.16", + "0800000000000000000000000000000000000000000000000000000000000000000010a1", + "000000000000000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000000000000000001", + "0503213f78ca44883f1a3b8162f188e553cd265f23c1567a16876913b0c2ac2458492836", + "01ccda380f1c9e318d90f95d07e5426fe87e45c0e8184698e45962364e34116177dd2259", + "01ffffffffffffffffffffffffffffffffffe9ae2ed07577265dff7f94451e061e163c61", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect283r1 [NIST B-283]", + "1.3.132.0.17", + "0800000000000000000000000000000000000000000000000000000000000000000010a1", + "000000000000000000000000000000000000000000000000000000000000000000000001", + "027b680ac8b8596da5a4af8a19a0303fca97fd7645309fa2a581485af6263e313b79a2f5", + "05f939258db7dd90e1934f8c70b0dfec2eed25b8557eac9c80e2e198f8cdbecd86b12053", + "03676854fe24141cb98fe6d4b20d02b4516ff702350eddb0826779c813f0df45be8112f4", + "03ffffffffffffffffffffffffffffffffffef90399660fc938a90165b042a7cefadb307", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect409k1 [NIST K-409]", + "1.3.132.0.36", + "02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001", + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "0060f05f658f49c1ad3ab1890f7184210efd0987e307c84c27accfb8f9f67cc2c460189eb5aaaa62ee222eb1b35540cfe9023746", + "01e369050b7c4e42acba1dacbf04299c3460782f918ea427e6325165e9ea10e3da5f6c42e9c55215aa9ca27a5863ec48d8e0286b", + "007ffffffffffffffffffffffffffffffffffffffffffffffffffe5f83b2d4ea20400ec4557d5ed3e3e7ca5b4b5c83b8e01e5fcf", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect409r1 [NIST B-409]", + "1.3.132.0.37", + "02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001", + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "0021a5c2c8ee9feb5c4b9a753b7b476b7fd6422ef1f3dd674761fa99d6ac27c8a9a197b272822f6cd57a55aa4f50ae317b13545f", + "015d4860d088ddb3496b0c6064756260441cde4af1771d4db01ffe5b34e59703dc255a868a1180515603aeab60794e54bb7996a7", + "0061b1cfab6be5f32bbfa78324ed106a7636b9c5a7bd198d0158aa4f5488d08f38514f1fdf4b4f40d2181b3681c364ba0273c706", + "010000000000000000000000000000000000000000000000000001e2aad6a612f33307be5fa47c3c9e052f838164cd37d9a21173", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect571k1 [NIST K-571]", + "1.3.132.0.38", + "080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "026eb7a859923fbc82189631f8103fe4ac9ca2970012d5d46024804801841ca44370958493b205e647da304db4ceb08cbbd1ba39494776fb988b47174dca88c7e2945283a01c8972", + "0349dc807f4fbf374f4aeade3bca95314dd58cec9f307a54ffc61efc006d8a2c9d4979c0ac44aea74fbebbb9f772aedcb620b01a7ba7af1b320430c8591984f601cd4c143ef1c7a3", + "020000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "sect571r1 [NIST B-571]", + "1.3.132.0.39", + "080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "02f40e7e2221f295de297117b7f3d62f5c6a97ffcb8ceff1cd6ba8ce4a9a18ad84ffabbd8efa59332be7ad6756a66e294afd185a78ff12aa520e4de739baca0c7ffeff7f2955727a", + "0303001d34b856296c16c0d40d3cd7750a93d1d2955fa80aa5f40fc8db7b2abdbde53950f4c0d293cdd711a35b67fb1499ae60038614f1394abfa3b4c850d927e1e7769c8eec2d19", + "037bf27342da639b6dccfffeb73d69d78c6c27a6009cbbca1980f8533921e8a684423e43bab08a576291af8f461bb2a8b3531d2f0485c19b16e2f1516e23dd3c1a4827af1b8ac15b", + "03ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe661ce18ff55987308059b186823851ec7dd9ca1161de93d5174d66e8382e9bb2fe84e47", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb191v1", + "1.2.840.10045.3.0.5", + "800000000000000000000000000000000000000000000201", + "2866537b676752636a68f56554e12640276b649ef7526267", + "2e45ef571f00786f67b0081b9495a3d95462f5de0aa185ec", + "36b3daf8a23206f9c4f299d7b21a9c369137f2c84ae1aa0d", + "765be73433b3f95e332932e70ea245ca2418ea0ef98018fb", + "40000000000000000000000004a20e90c39067c893bbb9a5", + 2) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb191v2", + "1.2.840.10045.3.0.6", + "800000000000000000000000000000000000000000000201", + "401028774d7777c7b7666d1366ea432071274f89ff01e718", + "0620048d28bcbd03b6249c99182b7c8cd19700c362c46a01", + "3809b2b7cc1b28cc5a87926aad83fd28789e81e2c9e3bf10", + "17434386626d14f3dbf01760d9213a3e1cf37aec437d668a", + "20000000000000000000000050508cb89f652824e06b8173", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb191v3", + "1.2.840.10045.3.0.7", + "800000000000000000000000000000000000000000000201", + "6c01074756099122221056911c77d77e77a777e7e7e77fcb", + "71fe1af926cf847989efef8db459f66394d90f32ad3f15e8", + "375d4ce24fde434489de8746e71786015009e66e38a926dd", + "545a39176196575d985999366e6ad34ce0a77cd7127b06be", + "155555555555555555555555610c0b196812bfb6288a3ea3", + 6) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb239v1", + "1.2.840.10045.3.0.11", + "800000000000000000000000000000000000000000000000001000000001", + "32010857077c5431123a46b808906756f543423e8d27877578125778ac76", + "790408f2eedaf392b012edefb3392f30f4327c0ca3f31fc383c422aa8c16", + "57927098fa932e7c0a96d3fd5b706ef7e5f5c156e16b7e7c86038552e91d", + "61d8ee5077c33fecf6f1a16b268de469c3c7744ea9a971649fc7a9616305", + "2000000000000000000000000000000f4d42ffe1492a4993f1cad666e447", + 4) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb239v2", + "1.2.840.10045.3.0.12", + "800000000000000000000000000000000000000000000000001000000001", + "4230017757a767fae42398569b746325d45313af0766266479b75654e65f", + "5037ea654196cff0cd82b2c14a2fcf2e3ff8775285b545722f03eacdb74b", + "28f9d04e900069c8dc47a08534fe76d2b900b7d7ef31f5709f200c4ca205", + "5667334c45aff3b5a03bad9dd75e2c71a99362567d5453f7fa6e227ec833", + "1555555555555555555555555555553c6f2885259c31e3fcdf154624522d", + 6) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb239v3", + "1.2.840.10045.3.0.13", + "800000000000000000000000000000000000000000000000001000000001", + "01238774666a67766d6676f778e676b66999176666e687666d8766c66a9f", + "6a941977ba9f6a435199acfc51067ed587f519c5ecb541b8e44111de1d40", + "70f6e9d04d289c4e89913ce3530bfde903977d42b146d539bf1bde4e9c92", + "2e5a0eaf6e5e1305b9004dce5c0ed7fe59a35608f33837c816d80b79f461", + "0cccccccccccccccccccccccccccccac4912d2d9df903ef9888b8a0e4cff", + 0xA) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb359v1", + "1.2.840.10045.3.0.18", + "800000000000000000000000000000000000000000000000000000000000000000000000100000000000000001", + "5667676a654b20754f356ea92017d946567c46675556f19556a04616b567d223a5e05656fb549016a96656a557", + "2472e2d0197c49363f1fe7f5b6db075d52b6947d135d8ca445805d39bc345626089687742b6329e70680231988", + "3c258ef3047767e7ede0f1fdaa79daee3841366a132e163aced4ed2401df9c6bdcde98e8e707c07a2239b1b097", + "53d7e08529547048121e9c95f3791dd804963948f34fae7bf44ea82365dc7868fe57e4ae2de211305a407104bd", + "01af286bca1af286bca1af286bca1af286bca1af286bc9fb8f6b85c556892c20a7eb964fe7719e74f490758d3b", + 0x4C) + ); + + ecCurveDefinitions.add( + new ECCurveDefinition( + "X9.62 c2tnb431r1", + "1.2.840.10045.3.0.20", + "800000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000001", + "1a827ef00dd6fc0e234caf046c6a5d8a85395b236cc4ad2cf32a0cadbdc9ddf620b0eb9906d0957f6c6feacd615468df104de296cd8f", + "10d9b4a3d9047d8b154359abfb1b7f5485b04ceb868237ddc9deda982a679a5a919b626d4e50a8dd731b107a9962381fb5d807bf2618", + "120fc05d3c67a99de161d2f4092622feca701be4f50f4758714e8a87bbf2a658ef8c21e7c5efe965361f6c2999c0c247b0dbd70ce6b7", + "20d0af8903a96f8d5fa2c255745d3c451b302c9346d9b7e485e7bce41f6b591f3e8f6addcbb0bc4c2f947a7de1a89b625d6a598b3760", + "0340340340340340340340340340340340340340340340340340340323c313fab50589703b5ec68d3587fec60d161cc149c1ad4a91", + 0x2760) + ); + } + + public static String getOIDFromPublicKey(ECPublicKey ecPublicKey) { + ECParameterSpec ecParameterSpec = ecPublicKey.getParams(); + BigInteger order = ecParameterSpec.getOrder(); + BigInteger affineX = ecParameterSpec.getGenerator().getAffineX(); + BigInteger affineY = ecParameterSpec.getGenerator().getAffineY(); + BigInteger a = ecParameterSpec.getCurve().getA(); + BigInteger b = ecParameterSpec.getCurve().getB(); + int h = ecParameterSpec.getCofactor(); + ECField ecField = ecParameterSpec.getCurve().getField(); + BigInteger field; + if (ecField instanceof ECFieldFp) { + ECFieldFp ecFieldFp = (ECFieldFp) ecField; + field = ecFieldFp.getP(); + } else { + ECFieldF2m ecFieldF2m = (ECFieldF2m) ecField; + field = ecFieldF2m.getReductionPolynomial(); + } + + Iterator ecCurveDefinitionIterator = ecCurveDefinitions.iterator(); + while (ecCurveDefinitionIterator.hasNext()) { + ECCurveDefinition ecCurveDefinition = ecCurveDefinitionIterator.next(); + String oid = ecCurveDefinition.equals(field, a, b, affineX, affineY, order, h); + if (oid != null) { + return oid; + } + } + return null; + } + + public static ECCurveDefinition getECCurveDefinition(String oid) { + Iterator ecCurveDefinitionIterator = ecCurveDefinitions.iterator(); + while (ecCurveDefinitionIterator.hasNext()) { + ECCurveDefinition ecCurveDefinition = ecCurveDefinitionIterator.next(); + if (ecCurveDefinition.getOid().equals(oid)) { + return ecCurveDefinition; + } + } + return null; + } + + public static class ECCurveDefinition { + + private final String name; + private final String oid; + private final String field; + private final String a; + private final String b; + private final String x; + private final String y; + private final String n; + private final int h; + + public ECCurveDefinition(String name, String oid, String field, String a, String b, String x, String y, String n, int h) { + this.name = name; + this.oid = oid; + this.field = field; + this.a = a; + this.b = b; + this.x = x; + this.y = y; + this.n = n; + this.h = h; + } + + /** + * returns the ec oid if parameter are equal to this definition + */ + public String equals(BigInteger field, BigInteger a, BigInteger b, BigInteger x, BigInteger y, BigInteger n, int h) { + if (this.field.equals(field.toString(16)) + && this.a.equals(a.toString(16)) + && this.b.equals(b.toString(16)) + && this.x.equals(x.toString(16)) + && this.y.equals(y.toString(16)) + && this.n.equals(n.toString(16)) + && this.h == h) { + return this.oid; + } + return null; + } + + public String getName() { + return name; + } + + public String getOid() { + return oid; + } + + public String getField() { + return field; + } + + public String getA() { + return a; + } + + public String getB() { + return b; + } + + public String getX() { + return x; + } + + public String getY() { + return y; + } + + public String getN() { + return n; + } + + public int getH() { + return h; + } + } + + public static byte[] encodePoint(ECPoint ecPoint, EllipticCurve ellipticCurve) { + int size = (ellipticCurve.getField().getFieldSize() + 7) / 8; + byte affineXBytes[] = stripLeadingZeros(ecPoint.getAffineX().toByteArray()); + byte affineYBytes[] = stripLeadingZeros(ecPoint.getAffineY().toByteArray()); + byte encodedBytes[] = new byte[size * 2 + 1]; + encodedBytes[0] = 0x04; //uncompressed + System.arraycopy(affineXBytes, 0, encodedBytes, size - affineXBytes.length + 1, affineXBytes.length); + System.arraycopy(affineYBytes, 0, encodedBytes, encodedBytes.length - affineYBytes.length, affineYBytes.length); + return encodedBytes; + } + + public static ECPoint decodePoint(byte[] encodedBytes, EllipticCurve elliptiCcurve) { + if (encodedBytes[0] != 0x04) { + throw new IllegalArgumentException("Only uncompressed format is supported"); + } + + int size = (elliptiCcurve.getField().getFieldSize() + 7) / 8; + byte affineXBytes[] = new byte[size]; + byte affineYBytes[] = new byte[size]; + System.arraycopy(encodedBytes, 1, affineXBytes, 0, size); + System.arraycopy(encodedBytes, size + 1, affineYBytes, 0, size); + return new ECPoint(new BigInteger(1, affineXBytes), new BigInteger(1, affineYBytes)); + } + + public static byte[] stripLeadingZeros(byte[] bytes) { + int i; + for (i = 0; i < bytes.length - 1; i++) { + if (bytes[i] != 0) { + break; + } + } + + if (i == 0) { + return bytes; + } else { + byte stripped[] = new byte[bytes.length - i]; + System.arraycopy(bytes, i, stripped, 0, stripped.length); + return stripped; + } + } +} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java @@ -44,21 +44,20 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { - /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IntegrityHmac.class.getName()); + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(IntegrityHmac.class); /** Field macAlgorithm */ - private Mac macAlgorithm = null; + private Mac macAlgorithm; /** Field HMACOutputLength */ - private int HMACOutputLength = 0; + private int HMACOutputLength; private boolean HMACOutputLengthSet = false; /** * Method engineGetURI * - *@inheritDoc + *{@inheritDoc} */ public abstract String engineGetURI(); @@ -74,9 +73,7 @@ */ 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); - } + LOG.debug("Created IntegrityHmacSHA1 using {}", algorithmID); try { this.macAlgorithm = Mac.getInstance(algorithmID); @@ -96,7 +93,7 @@ * @throws XMLSignatureException */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { - throw new XMLSignatureException("empty"); + throw new XMLSignatureException("empty", new Object[]{"Incorrect method call"}); } public void reset() { @@ -116,9 +113,7 @@ 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()); - } + LOG.debug("HMACOutputLength must not be less than {}", getDigestLength()); Object[] exArgs = { String.valueOf(getDigestLength()) }; throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); } else { @@ -126,7 +121,7 @@ return MessageDigestAlgorithm.isEqual(completeResult, signature); } } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } @@ -139,7 +134,10 @@ */ protected void engineInitVerify(Key secretKey) throws XMLSignatureException { if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); + String supplied = null; + if (secretKey != null) { + supplied = secretKey.getClass().getName(); + } String needed = SecretKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -156,12 +154,10 @@ 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); - } + LOG.debug("Exception when reinstantiating Mac: {}", e); this.macAlgorithm = mac; } - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } @@ -175,16 +171,14 @@ 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()); - } + LOG.debug("HMACOutputLength must not be less than {}", getDigestLength()); Object[] exArgs = { String.valueOf(getDigestLength()) }; throw new XMLSignatureException("algorithms.HMACOutputLengthMin", exArgs); } else { return this.macAlgorithm.doFinal(); } } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } @@ -195,19 +189,7 @@ * @throws XMLSignatureException */ protected void engineInitSign(Key secretKey) throws XMLSignatureException { - if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); - String needed = SecretKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); - } - - try { - this.macAlgorithm.init(secretKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } + engineInitSign(secretKey, (AlgorithmParameterSpec)null); } /** @@ -221,7 +203,10 @@ Key secretKey, AlgorithmParameterSpec algorithmParameterSpec ) throws XMLSignatureException { if (!(secretKey instanceof SecretKey)) { - String supplied = secretKey.getClass().getName(); + String supplied = null; + if (secretKey != null) { + supplied = secretKey.getClass().getName(); + } String needed = SecretKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -229,11 +214,15 @@ } try { - this.macAlgorithm.init(secretKey, algorithmParameterSpec); + if (algorithmParameterSpec == null) { + this.macAlgorithm.init(secretKey); + } else { + this.macAlgorithm.init(secretKey, algorithmParameterSpec); + } } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } @@ -260,7 +249,7 @@ try { this.macAlgorithm.update(input); } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } @@ -275,7 +264,7 @@ try { this.macAlgorithm.update(input); } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } @@ -292,13 +281,13 @@ try { this.macAlgorithm.update(buf, offset, len); } catch (IllegalStateException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } /** * Method engineGetJCEAlgorithmString - * @inheritDoc + * {@inheritDoc} * */ protected String engineGetJCEAlgorithmString() { @@ -308,7 +297,7 @@ /** * Method engineGetJCEAlgorithmString * - * @inheritDoc + * {@inheritDoc} */ protected String engineGetJCEProviderName() { return this.macAlgorithm.getProvider().getName(); @@ -360,7 +349,7 @@ Element HMElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH); Text HMText = - doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString()); + doc.createTextNode("" + this.HMACOutputLength); HMElem.appendChild(HMText); XMLUtils.addReturnToElement(element); @@ -385,7 +374,7 @@ /** * Method engineGetURI - * @inheritDoc + * {@inheritDoc} * */ public String engineGetURI() { @@ -398,6 +387,34 @@ } /** + * Class IntegrityHmacSHA224 + */ + public static class IntegrityHmacSHA224 extends IntegrityHmac { + + /** + * Constructor IntegrityHmacSHA224 + * + * @throws XMLSignatureException + */ + public IntegrityHmacSHA224() throws XMLSignatureException { + super(); + } + + /** + * Method engineGetURI + * + * {@inheritDoc} + */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_MAC_HMAC_SHA224; + } + + int getDigestLength() { + return 224; + } + } + + /** * Class IntegrityHmacSHA256 */ public static class IntegrityHmacSHA256 extends IntegrityHmac { @@ -414,7 +431,7 @@ /** * Method engineGetURI * - * @inheritDoc + * {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_SHA256; @@ -441,7 +458,7 @@ /** * Method engineGetURI - * @inheritDoc + * {@inheritDoc} * */ public String engineGetURI() { @@ -469,7 +486,7 @@ /** * Method engineGetURI - * @inheritDoc + * {@inheritDoc} * */ public String engineGetURI() { @@ -498,7 +515,7 @@ /** * Method engineGetURI * - * @inheritDoc + * {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160; @@ -526,7 +543,7 @@ /** * Method engineGetURI * - * @inheritDoc + * {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5; diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureBaseRSA.java @@ -40,15 +40,14 @@ public abstract class SignatureBaseRSA extends SignatureAlgorithmSpi { - /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SignatureBaseRSA.class.getName()); + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureBaseRSA.class); - /** @inheritDoc */ + /** {@inheritDoc} */ public abstract String engineGetURI(); /** Field algorithm */ - private java.security.Signature signatureAlgorithm = null; + private Signature signatureAlgorithm; /** * Constructor SignatureRSA @@ -58,15 +57,13 @@ public SignatureBaseRSA() throws XMLSignatureException { String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Created SignatureRSA using " + algorithmID); - } + LOG.debug("Created SignatureRSA using {}", algorithmID); String provider = JCEMapper.getProviderId(); try { 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() }; @@ -79,29 +76,32 @@ } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { try { this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected boolean engineVerify(byte[] signature) throws XMLSignatureException { try { return this.signatureAlgorithm.verify(signature); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); + String supplied = null; + if (publicKey != null) { + supplied = publicKey.getClass().getName(); + } String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -119,46 +119,30 @@ } 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); - } + LOG.debug("Exception when reinstantiating Signature: {}", e); this.signatureAlgorithm = sig; } - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected byte[] engineSign() throws XMLSignatureException { try { return this.signatureAlgorithm.sign(); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); - } - - try { - this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); + String supplied = null; + if (privateKey != null) { + supplied = privateKey.getClass().getName(); + } String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -166,56 +150,65 @@ } try { - this.signatureAlgorithm.initSign((PrivateKey) privateKey); + if (secureRandom == null) { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } else { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + engineInitSign(privateKey, (SecureRandom)null); + } + + /** {@inheritDoc} */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineUpdate(byte input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@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); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected String engineGetJCEAlgorithmString() { return this.signatureAlgorithm.getAlgorithm(); } - /** @inheritDoc */ + /** {@inheritDoc} */ protected String engineGetJCEProviderName() { return this.signatureAlgorithm.getProvider().getName(); } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException { throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineInitSign( Key signingKey, AlgorithmParameterSpec algorithmParameterSpec ) throws XMLSignatureException { @@ -236,13 +229,33 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1; } } /** + * Class SignatureRSASHA224 + */ + public static class SignatureRSASHA224 extends SignatureBaseRSA { + + /** + * Constructor SignatureRSASHA224 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA224() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224; + } + } + + /** * Class SignatureRSASHA256 */ public static class SignatureRSASHA256 extends SignatureBaseRSA { @@ -256,7 +269,7 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; } @@ -276,7 +289,7 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; } @@ -296,7 +309,7 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; } @@ -316,7 +329,7 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; } @@ -336,9 +349,109 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5; } } + + /** + * Class SignatureRSASHA1MGF1 + */ + public static class SignatureRSASHA1MGF1 extends SignatureBaseRSA { + + /** + * Constructor SignatureRSASHA1MGF1 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA1MGF1() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1; + } + } + + /** + * Class SignatureRSASHA224MGF1 + */ + public static class SignatureRSASHA224MGF1 extends SignatureBaseRSA { + + /** + * Constructor SignatureRSASHA224MGF1 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA224MGF1() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1; + } + } + + /** + * Class SignatureRSASHA256MGF1 + */ + public static class SignatureRSASHA256MGF1 extends SignatureBaseRSA { + + /** + * Constructor SignatureRSASHA256MGF1 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA256MGF1() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1; + } + } + + /** + * Class SignatureRSASHA384MGF1 + */ + public static class SignatureRSASHA384MGF1 extends SignatureBaseRSA { + + /** + * Constructor SignatureRSASHA384MGF1 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA384MGF1() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1; + } + } + + /** + * Class SignatureRSASHA512MGF1 + */ + public static class SignatureRSASHA512MGF1 extends SignatureBaseRSA { + + /** + * Constructor SignatureRSASHA512MGF1 + * + * @throws XMLSignatureException + */ + public SignatureRSASHA512MGF1() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1; + } + } } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureDSA.java @@ -33,22 +33,24 @@ import java.security.SignatureException; import java.security.interfaces.DSAKey; import java.security.spec.AlgorithmParameterSpec; +import java.util.Base64; import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi; import com.sun.org.apache.xml.internal.security.signature.XMLSignature; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; -import com.sun.org.apache.xml.internal.security.utils.Base64; +import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.JavaUtils; public class SignatureDSA extends SignatureAlgorithmSpi { - /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SignatureDSA.class.getName()); + public static final String URI = Constants.SignatureSpecNS + "dsa-sha1"; + + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureDSA.class); /** Field algorithm */ - private java.security.Signature signatureAlgorithm = null; + private Signature signatureAlgorithm; /** size of Q */ private int size; @@ -56,7 +58,7 @@ /** * Method engineGetURI * - * @inheritDoc + * {@inheritDoc} */ protected String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_DSA; @@ -69,9 +71,7 @@ */ public SignatureDSA() throws XMLSignatureException { String algorithmID = JCEMapper.translateURItoJCEID(engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID); - } + LOG.debug("Created SignatureDSA using {}", algorithmID); String provider = JCEMapper.getProviderId(); try { @@ -91,25 +91,25 @@ } /** - * @inheritDoc + * {@inheritDoc} */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { try { this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } /** - * @inheritDoc + * {@inheritDoc} */ protected boolean engineVerify(byte[] signature) throws XMLSignatureException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Called DSA.verify() on " + Base64.encode(signature)); + if (LOG.isDebugEnabled()) { + LOG.debug("Called DSA.verify() on " + Base64.getMimeEncoder().encodeToString(signature)); } byte[] jcebytes = JavaUtils.convertDsaXMLDSIGtoASN1(signature, @@ -117,18 +117,21 @@ return this.signatureAlgorithm.verify(jcebytes); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } /** - * @inheritDoc + * {@inheritDoc} */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); + String supplied = null; + if (publicKey != null) { + supplied = publicKey.getClass().getName(); + } String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -146,18 +149,16 @@ } 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); - } + LOG.debug("Exception when reinstantiating Signature: {}", e); this.signatureAlgorithm = sig; } - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } size = ((DSAKey)publicKey).getParams().getQ().bitLength(); } /** - * @inheritDoc + * {@inheritDoc} */ protected byte[] engineSign() throws XMLSignatureException { try { @@ -165,19 +166,22 @@ return JavaUtils.convertDsaASN1toXMLDSIG(jcebytes, size/8); } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } /** - * @inheritDoc + * {@inheritDoc} */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); + String supplied = null; + if (privateKey != null) { + supplied = privateKey.getClass().getName(); + } String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -185,70 +189,61 @@ } try { - this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + if (secureRandom == null) { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } else { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - size = ((DSAKey)privateKey).getParams().getQ().bitLength(); - } - - /** - * @inheritDoc - */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); - } - - try { - this.signatureAlgorithm.initSign((PrivateKey) privateKey); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } size = ((DSAKey)privateKey).getParams().getQ().bitLength(); } /** - * @inheritDoc + * {@inheritDoc} + */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + engineInitSign(privateKey, (SecureRandom)null); + } + + /** + * {@inheritDoc} */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } /** - * @inheritDoc + * {@inheritDoc} */ protected void engineUpdate(byte input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } /** - * @inheritDoc + * {@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); + throw new XMLSignatureException(ex); } } /** * Method engineGetJCEAlgorithmString * - * @inheritDoc + * {@inheritDoc} */ protected String engineGetJCEAlgorithmString() { return this.signatureAlgorithm.getAlgorithm(); @@ -257,7 +252,7 @@ /** * Method engineGetJCEProviderName * - * @inheritDoc + * {@inheritDoc} */ protected String engineGetJCEProviderName() { return this.signatureAlgorithm.getProvider().getName(); diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/SignatureECDSA.java @@ -33,34 +33,31 @@ import java.security.Signature; import java.security.SignatureException; import java.security.spec.AlgorithmParameterSpec; +import java.util.Base64; import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi; import com.sun.org.apache.xml.internal.security.signature.XMLSignature; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; -import com.sun.org.apache.xml.internal.security.utils.Base64; /** * - * @author $Author: raul $ - * @author Alex Dupre */ public abstract class SignatureECDSA extends SignatureAlgorithmSpi { - /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(SignatureECDSA.class.getName()); + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(SignatureECDSA.class); - /** @inheritDoc */ + /** {@inheritDoc} */ public abstract String engineGetURI(); /** Field algorithm */ - private java.security.Signature signatureAlgorithm = null; + private Signature signatureAlgorithm; /** * 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 + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value * pairs; the XML Signature requires the core BigInteger values. * * @param asn1Bytes @@ -71,51 +68,13 @@ * @see 3.3. ECDSA Signatures */ public static byte[] convertASN1toXMLDSIG(byte asn1Bytes[]) throws IOException { - - if (asn1Bytes.length < 8 || asn1Bytes[0] != 48) { - throw new IOException("Invalid ASN.1 format of ECDSA signature"); - } - int offset; - if (asn1Bytes[1] > 0) { - offset = 2; - } else if (asn1Bytes[1] == (byte) 0x81) { - offset = 3; - } else { - throw new IOException("Invalid ASN.1 format of ECDSA signature"); - } - - byte rLength = asn1Bytes[offset + 1]; - int i; - - for (i = rLength; (i > 0) && (asn1Bytes[(offset + 2 + rLength) - i] == 0); i--); - - byte sLength = asn1Bytes[offset + 2 + rLength + 1]; - int j; - - for (j = sLength; - (j > 0) && (asn1Bytes[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--); - - int rawLen = Math.max(i, j); - - if ((asn1Bytes[offset - 1] & 0xff) != asn1Bytes.length - offset - || (asn1Bytes[offset - 1] & 0xff) != 2 + rLength + 2 + sLength - || asn1Bytes[offset] != 2 - || asn1Bytes[offset + 2 + rLength] != 2) { - throw new IOException("Invalid ASN.1 format of ECDSA signature"); - } - byte xmldsigBytes[] = new byte[2*rawLen]; - - System.arraycopy(asn1Bytes, (offset + 2 + rLength) - i, xmldsigBytes, rawLen - i, i); - System.arraycopy(asn1Bytes, (offset + 2 + rLength + 2 + sLength) - j, xmldsigBytes, - 2*rawLen - j, j); - - return xmldsigBytes; + return ECDSAUtils.convertASN1toXMLDSIG(asn1Bytes); } /** * 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 + * The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r, s) value * pairs; the XML Signature requires the core BigInteger values. * * @param xmldsigBytes @@ -126,58 +85,7 @@ * @see 3.3. ECDSA Signatures */ public static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[]) throws IOException { - - int rawLen = xmldsigBytes.length/2; - - int i; - - for (i = rawLen; (i > 0) && (xmldsigBytes[rawLen - i] == 0); i--); - - int j = i; - - if (xmldsigBytes[rawLen - i] < 0) { - j += 1; - } - - int k; - - for (k = rawLen; (k > 0) && (xmldsigBytes[2*rawLen - k] == 0); k--); - - int l = k; - - if (xmldsigBytes[2*rawLen - k] < 0) { - l += 1; - } - - int len = 2 + j + 2 + l; - if (len > 255) { - throw new IOException("Invalid XMLDSIG format of ECDSA signature"); - } - int offset; - byte asn1Bytes[]; - if (len < 128) { - asn1Bytes = new byte[2 + 2 + j + 2 + l]; - offset = 1; - } else { - asn1Bytes = new byte[3 + 2 + j + 2 + l]; - asn1Bytes[1] = (byte) 0x81; - offset = 2; - } - asn1Bytes[0] = 48; - asn1Bytes[offset++] = (byte) len; - asn1Bytes[offset++] = 2; - asn1Bytes[offset++] = (byte) j; - - System.arraycopy(xmldsigBytes, rawLen - i, asn1Bytes, (offset + j) - i, i); - - offset += j; - - asn1Bytes[offset++] = 2; - asn1Bytes[offset++] = (byte) l; - - System.arraycopy(xmldsigBytes, 2*rawLen - k, asn1Bytes, (offset + l) - k, k); - - return asn1Bytes; + return ECDSAUtils.convertXMLDSIGtoASN1(xmldsigBytes); } /** @@ -189,15 +97,13 @@ String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID); - } + LOG.debug("Created SignatureECDSA using {}", algorithmID); String provider = JCEMapper.getProviderId(); try { 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() }; @@ -210,38 +116,41 @@ } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { try { this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected boolean engineVerify(byte[] signature) throws XMLSignatureException { try { byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature)); + if (LOG.isDebugEnabled()) { + LOG.debug("Called ECDSA.verify() on " + Base64.getMimeEncoder().encodeToString(signature)); } return this.signatureAlgorithm.verify(jcebytes); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineInitVerify(Key publicKey) throws XMLSignatureException { if (!(publicKey instanceof PublicKey)) { - String supplied = publicKey.getClass().getName(); + String supplied = null; + if (publicKey != null) { + supplied = publicKey.getClass().getName(); + } String needed = PublicKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -259,50 +168,34 @@ } 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); - } + LOG.debug("Exception when reinstantiating Signature: {}", e); this.signatureAlgorithm = sig; } - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected byte[] engineSign() throws XMLSignatureException { try { byte jcebytes[] = this.signatureAlgorithm.sign(); return SignatureECDSA.convertASN1toXMLDSIG(jcebytes); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineInitSign(Key privateKey, SecureRandom secureRandom) throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); - String needed = PrivateKey.class.getName(); - Object exArgs[] = { supplied, needed }; - - throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); - } - - try { - this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); - } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** @inheritDoc */ - protected void engineInitSign(Key privateKey) throws XMLSignatureException { - if (!(privateKey instanceof PrivateKey)) { - String supplied = privateKey.getClass().getName(); + String supplied = null; + if (privateKey != null) { + supplied = privateKey.getClass().getName(); + } String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; @@ -310,56 +203,65 @@ } try { - this.signatureAlgorithm.initSign((PrivateKey) privateKey); + if (secureRandom == null) { + this.signatureAlgorithm.initSign((PrivateKey) privateKey); + } else { + this.signatureAlgorithm.initSign((PrivateKey) privateKey, secureRandom); + } } catch (InvalidKeyException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ + protected void engineInitSign(Key privateKey) throws XMLSignatureException { + engineInitSign(privateKey, (SecureRandom)null); + } + + /** {@inheritDoc} */ protected void engineUpdate(byte[] input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineUpdate(byte input) throws XMLSignatureException { try { this.signatureAlgorithm.update(input); } catch (SignatureException ex) { - throw new XMLSignatureException("empty", ex); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@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); + throw new XMLSignatureException(ex); } } - /** @inheritDoc */ + /** {@inheritDoc} */ protected String engineGetJCEAlgorithmString() { return this.signatureAlgorithm.getAlgorithm(); } - /** @inheritDoc */ + /** {@inheritDoc} */ protected String engineGetJCEProviderName() { return this.signatureAlgorithm.getProvider().getName(); } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineSetHMACOutputLength(int HMACOutputLength) throws XMLSignatureException { throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC"); } - /** @inheritDoc */ + /** {@inheritDoc} */ protected void engineInitSign( Key signingKey, AlgorithmParameterSpec algorithmParameterSpec ) throws XMLSignatureException { @@ -367,13 +269,12 @@ } /** - * Class SignatureRSASHA1 + * Class SignatureECDSASHA1 * - * @author $Author: marcx $ */ public static class SignatureECDSASHA1 extends SignatureECDSA { /** - * Constructor SignatureRSASHA1 + * Constructor SignatureECDSASHA1 * * @throws XMLSignatureException */ @@ -381,21 +282,40 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1; } } /** - * Class SignatureRSASHA256 + * Class SignatureECDSASHA224 + */ + public static class SignatureECDSASHA224 extends SignatureECDSA { + + /** + * Constructor SignatureECDSASHA224 + * + * @throws XMLSignatureException + */ + public SignatureECDSASHA224() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224; + } + } + + /** + * Class SignatureECDSASHA256 * - * @author Alex Dupre */ public static class SignatureECDSASHA256 extends SignatureECDSA { /** - * Constructor SignatureRSASHA256 + * Constructor SignatureECDSASHA256 * * @throws XMLSignatureException */ @@ -403,21 +323,20 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256; } } /** - * Class SignatureRSASHA384 + * Class SignatureECDSASHA384 * - * @author Alex Dupre */ public static class SignatureECDSASHA384 extends SignatureECDSA { /** - * Constructor SignatureRSASHA384 + * Constructor SignatureECDSASHA384 * * @throws XMLSignatureException */ @@ -425,21 +344,20 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384; } } /** - * Class SignatureRSASHA512 + * Class SignatureECDSASHA512 * - * @author Alex Dupre */ public static class SignatureECDSASHA512 extends SignatureECDSA { /** - * Constructor SignatureRSASHA512 + * Constructor SignatureECDSASHA512 * * @throws XMLSignatureException */ @@ -447,10 +365,30 @@ super(); } - /** @inheritDoc */ + /** {@inheritDoc} */ public String engineGetURI() { return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512; } } + /** + * Class SignatureECDSARIPEMD160 + */ + public static class SignatureECDSARIPEMD160 extends SignatureECDSA { + + /** + * Constructor SignatureECDSARIPEMD160 + * + * @throws XMLSignatureException + */ + public SignatureECDSARIPEMD160() throws XMLSignatureException { + super(); + } + + /** {@inheritDoc} */ + public String engineGetURI() { + return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160; + } + } + } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/package.html +++ /dev/null @@ -1,3 +0,0 @@ - -implementations of {@link com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi}. -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/package.html +++ /dev/null @@ -1,3 +0,0 @@ --algorithm factories. -
\ No newline at end of file diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizationException.java @@ -27,7 +27,6 @@ /** * Class CanonicalizationException * - * @author Christian Geuer-Pollmann */ public class CanonicalizationException extends XMLSecurityException { @@ -44,6 +43,10 @@ super(); } + public CanonicalizationException(Exception ex) { + super(ex); + } + /** * Constructor CanonicalizationException * @@ -66,23 +69,33 @@ /** * Constructor CanonicalizationException * + * @param originalException * @param msgID - * @param originalException */ + public CanonicalizationException(Exception originalException, String msgID) { + super(originalException, msgID); + } + + @Deprecated public CanonicalizationException(String msgID, Exception originalException) { - super(msgID, originalException); + this(originalException, msgID); } /** * Constructor CanonicalizationException * + * @param originalException * @param msgID * @param exArgs - * @param originalException */ public CanonicalizationException( - String msgID, Object exArgs[], Exception originalException + Exception originalException, String msgID, Object exArgs[] ) { - super(msgID, exArgs, originalException); + super(originalException, msgID, exArgs); + } + + @Deprecated + public CanonicalizationException(String msgID, Object exArgs[], Exception originalException) { + this(originalException, msgID, exArgs); } } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/Canonicalizer.java @@ -25,13 +25,12 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments; import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_WithComments; @@ -42,6 +41,7 @@ import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerPhysical; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import com.sun.org.apache.xml.internal.security.utils.JavaUtils; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -49,12 +49,11 @@ /** * - * @author Christian Geuer-Pollmann */ public class Canonicalizer { /** The output encoding of canonicalized data */ - public static final String ENCODING = "UTF8"; + public static final String ENCODING = StandardCharsets.UTF_8.name(); /** * XPath Expression for selecting every node and continuous comments joined @@ -103,6 +102,7 @@ new ConcurrentHashMap>(); private final CanonicalizerSpi canonicalizerSpi; + private boolean secureValidation; /** * Constructor Canonicalizer @@ -120,7 +120,7 @@ } catch (Exception e) { Object exArgs[] = { algorithmURI }; throw new InvalidCanonicalizerException( - "signature.Canonicalizer.UnknownCanonicalizer", exArgs, e + e, "signature.Canonicalizer.UnknownCanonicalizer", exArgs ); } } @@ -160,7 +160,8 @@ } canonicalizerHash.put( - algorithmURI, (Class extends CanonicalizerSpi>)Class.forName(implementingClass) + algorithmURI, (Class extends CanonicalizerSpi>) + ClassLoaderUtils.loadClass(implementingClass, Canonicalizer.class) ); } @@ -242,7 +243,7 @@ /** * This method tries to canonicalize the given bytes. It's possible to even * canonicalize non-wellformed sequences if they are well-formed after being - * wrapped with a >a<...>/a<
. + * wrapped with a {@code >a<...>/a<}. * * @param inputBytes * @return the result of the canonicalization. @@ -254,47 +255,43 @@ public byte[] canonicalize(byte[] inputBytes) throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException, CanonicalizationException { - InputStream bais = new ByteArrayInputStream(inputBytes); - InputSource in = new InputSource(bais); - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document document = null; + try (InputStream bais = new ByteArrayInputStream(inputBytes)) { + InputSource in = new InputSource(bais); - dfactory.setNamespaceAware(true); - - // needs to validate for ID attribute normalization - dfactory.setValidating(true); - - DocumentBuilder db = dfactory.newDocumentBuilder(); + // needs to validate for ID attribute normalization + DocumentBuilder db = XMLUtils.createDocumentBuilder(true, secureValidation); - /* - * for some of the test vectors from the specification, - * there has to be a validating parser for ID attributes, default - * attribute values, NMTOKENS, etc. - * Unfortunately, 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. - */ - db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler()); + /* + * for some of the test vectors from the specification, + * there has to be a validating parser for ID attributes, default + * attribute values, NMTOKENS, etc. + * Unfortunately, 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. + */ + db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler()); - Document document = db.parse(in); + document = db.parse(in); + } return this.canonicalizeSubtree(document); } /** - * Canonicalizes the subtree rooted bynode
. + * Canonicalizes the subtree rooted by {@code node}. * * @param node The node to canonicalize * @return the result of the c14n. @@ -302,11 +299,12 @@ * @throws CanonicalizationException */ public byte[] canonicalizeSubtree(Node node) throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; return canonicalizerSpi.engineCanonicalizeSubTree(node); } /** - * Canonicalizes the subtree rooted bynode
. + * Canonicalizes the subtree rooted by {@code node}. * * @param node * @param inclusiveNamespaces @@ -315,11 +313,26 @@ */ public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces) throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces); } /** - * Canonicalizes an XPath node set. ThexpathNodeSet
is treated + * Canonicalizes the subtree rooted by {@code node}. + * + * @param node + * @param inclusiveNamespaces + * @return the result of the c14n. + * @throws CanonicalizationException + */ + public byte[] canonicalizeSubtree(Node node, String inclusiveNamespaces, boolean propagateDefaultNamespace) + throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; + return canonicalizerSpi.engineCanonicalizeSubTree(node, inclusiveNamespaces, propagateDefaultNamespace); + } + + /** + * Canonicalizes an XPath node set. The {@code xpathNodeSet} is treated * as a list of XPath nodes, not as a list of subtrees. * * @param xpathNodeSet @@ -328,11 +341,12 @@ */ public byte[] canonicalizeXPathNodeSet(NodeList xpathNodeSet) throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); } /** - * Canonicalizes an XPath node set. ThexpathNodeSet
is treated + * Canonicalizes an XPath node set. The {@code xpathNodeSet} is treated * as a list of XPath nodes, not as a list of subtrees. * * @param xpathNodeSet @@ -343,6 +357,7 @@ public byte[] canonicalizeXPathNodeSet( NodeList xpathNodeSet, String inclusiveNamespaces ) throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); } @@ -356,6 +371,7 @@ */ public byte[] canonicalizeXPathNodeSet(SetxpathNodeSet) throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet); } @@ -370,6 +386,7 @@ public byte[] canonicalizeXPathNodeSet( Set xpathNodeSet, String inclusiveNamespaces ) throws CanonicalizationException { + canonicalizerSpi.secureValidation = secureValidation; return canonicalizerSpi.engineCanonicalizeXPathNodeSet(xpathNodeSet, inclusiveNamespaces); } @@ -399,4 +416,12 @@ canonicalizerSpi.reset = false; } + public boolean isSecureValidation() { + return secureValidation; + } + + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/CanonicalizerSpi.java @@ -26,9 +26,7 @@ import java.io.OutputStream; import java.util.Set; -import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; @@ -39,12 +37,12 @@ /** * Base class which all Canonicalization algorithms extend. * - * @author Christian Geuer-Pollmann */ public abstract class CanonicalizerSpi { /** Reset the writer after a c14n */ protected boolean reset = false; + protected boolean secureValidation; /** * Method canonicalize @@ -61,17 +59,14 @@ throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException, CanonicalizationException { - java.io.InputStream bais = new ByteArrayInputStream(inputBytes); - InputSource in = new InputSource(bais); - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document document = null; + try (java.io.InputStream bais = new ByteArrayInputStream(inputBytes)) { + InputSource in = new InputSource(bais); - // needs to validate for ID attribute normalization - dfactory.setNamespaceAware(true); + DocumentBuilder db = XMLUtils.createDocumentBuilder(false, secureValidation); - DocumentBuilder db = dfactory.newDocumentBuilder(); - - Document document = db.parse(in); + document = db.parse(in); + } return this.engineCanonicalizeSubTree(document); } @@ -160,10 +155,31 @@ throws CanonicalizationException; /** + * C14n a node tree. + * + * @param rootNode + * @param inclusiveNamespaces + * @param propagateDefaultNamespace If true the default namespace will be propagated to the c14n-ized root element + * @return the c14n bytes + * @throws CanonicalizationException + */ + public abstract byte[] engineCanonicalizeSubTree( + Node rootNode, String inclusiveNamespaces, boolean propagateDefaultNamespace) + throws CanonicalizationException; + + /** * Sets the writer where the canonicalization ends. ByteArrayOutputStream if * none is set. * @param os */ public abstract void setWriter(OutputStream os); + public boolean isSecureValidation() { + return secureValidation; + } + + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java new file mode 100644 --- /dev/null +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/ClassLoaderUtils.java @@ -0,0 +1,84 @@ +/* + * 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; + +// NOTE! This is a duplicate of utils.ClassLoaderUtils with public +// modifiers changed to package-private. Make sure to integrate any future +// changes to utils.ClassLoaderUtils to this file. +final class ClassLoaderUtils { + + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class); + + private ClassLoaderUtils() { + } + + /** + * Load a class with a given name. It will try to load the class in the + * following order: + * + *
+ * + * @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) { + LOG.debug(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); + } + } + LOG.debug(ex.getMessage(), ex); + throw ex; + } + } +} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/InvalidCanonicalizerException.java @@ -61,23 +61,33 @@ /** * Constructor InvalidCanonicalizerException * + * @param originalException * @param msgID - * @param originalException */ + public InvalidCanonicalizerException(Exception originalException, String msgID) { + super(originalException, msgID); + } + + @Deprecated public InvalidCanonicalizerException(String msgID, Exception originalException) { - super(msgID, originalException); + this(originalException, msgID); } /** * Constructor InvalidCanonicalizerException * + * @param originalException * @param msgID * @param exArgs - * @param originalException */ public InvalidCanonicalizerException( - String msgID, Object exArgs[], Exception originalException + Exception originalException, String msgID, Object exArgs[] ) { - super(msgID, exArgs, originalException); + super(originalException, msgID, exArgs); + } + + @Deprecated + public InvalidCanonicalizerException(String msgID, Object[] exArgs, Exception originalException) { + this(originalException, msgID, exArgs); } } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/helper/AttrCompare.java @@ -41,7 +41,6 @@ * key (an empty namespace URI is lexicographically least). *- From Thread.currentThread().getContextClassLoader() + *
- Using the basic Class.forName() + *
- From ClassLoaderUtil.class.getClassLoader() + *
- From the callingClass.getClassLoader() + *
-helper classes for canonicalization. -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/Canonicalizer11.java +++ /dev/null @@ -1,687 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.c14n.implementations; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import javax.xml.parsers.ParserConfigurationException; -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; -import org.xml.sax.SAXException; - -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; -import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.XMLUtils; - -/** - * Implements - * Canonical XML Version 1.1, a W3C Proposed Recommendation from 29 - * January 2008. - * - * @author Sean Mullan - * @author Raul Benito - */ -public abstract class Canonicalizer11 extends CanonicalizerBase { - - 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&
<
"
#x9
, #xA, and #xD, with character
+ * #xD
is represented
- * by the character reference 
)int
value
+ * @param newCapacity an {@code int} value
*/
protected void rehash(int newCapacity) {
int oldCapacity = keys.length;
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/implementations/UtfHelpper.java
@@ -24,11 +24,27 @@
import java.io.IOException;
import java.io.OutputStream;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.Map;
-public class UtfHelpper {
+public final class UtfHelpper {
- static final void writeByte(
+ /**
+ * Revert to the old behavior (version 2 or before), i.e. surrogate pairs characters becomes
+ * '??' in output. Set system property com.sun.org.apache.xml.internal.security.c14n.oldUtf8=true if you want
+ * to verify signatures generated by version 2 or before that contains 32 bit chars in the
+ * XML document.
+ */
+ private static final boolean OLD_UTF8 =
+ AccessController.doPrivileged((PrivilegedAction-canonicalization implementations. -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/c14n/package.html +++ /dev/null @@ -1,3 +0,0 @@ --Canonicalization related material and algorithms. -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/AbstractSerializer.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.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; - -/** - * ConvertsString
s into Node
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 String
representation of the specified
- * Element
.
- *
- * Refer also to comments about setup of format.
- *
- * @param element the Element
to serialize.
- * @return the String
representation of the serilaized
- * Element
.
- * @throws Exception
- */
- public String serialize(Element element) throws Exception {
- return canonSerialize(element);
- }
-
- /**
- * Returns a byte[]
representation of the specified
- * Element
.
- *
- * @param element the Element
to serialize.
- * @return the byte[]
representation of the serilaized
- * Element
.
- * @throws Exception
- */
- public byte[] serializeToByteArray(Element element) throws Exception {
- return canonSerializeToByteArray(element);
- }
-
- /**
- * Returns a String
representation of the specified
- * NodeList
.
- *
- * This is a special case because the NodeList may represent a
- * DocumentFragment
. A document fragment may be a
- * non-valid XML document (refer to appropriate description of
- * W3C) because it my start with a non-element node, e.g. a text
- * node.
- *
- * The methods first converts the node list into a document fragment.
- * Special care is taken to not destroy the current document, thus
- * the method clones the nodes (deep cloning) before it appends
- * them to the document fragment.
- *
- * Refer also to comments about setup of format.
- *
- * @param content the NodeList
to serialize.
- * @return the String
representation of the serialized
- * NodeList
.
- * @throws Exception
- */
- public String serialize(NodeList content) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- canon.setWriter(baos);
- canon.notReset();
- for (int i = 0; i < content.getLength(); i++) {
- canon.canonicalizeSubtree(content.item(i));
- }
- String ret = baos.toString("UTF-8");
- baos.reset();
- return ret;
- }
-
- /**
- * Returns a byte[]
representation of the specified
- * NodeList
.
- *
- * @param content the NodeList
to serialize.
- * @return the byte[]
representation of the serialized
- * NodeList
.
- * @throws Exception
- */
- public byte[] serializeToByteArray(NodeList content) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- canon.setWriter(baos);
- canon.notReset();
- for (int i = 0; i < content.getLength(); i++) {
- canon.canonicalizeSubtree(content.item(i));
- }
- return baos.toByteArray();
- }
-
- /**
- * Use the Canonicalizer to serialize the node
- * @param node
- * @return the canonicalization of the node
- * @throws Exception
- */
- public String canonSerialize(Node node) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- canon.setWriter(baos);
- canon.notReset();
- canon.canonicalizeSubtree(node);
- String ret = baos.toString("UTF-8");
- baos.reset();
- return ret;
- }
-
- /**
- * Use the Canonicalizer to serialize the node
- * @param node
- * @return the (byte[]) canonicalization of the node
- * @throws Exception
- */
- public byte[] canonSerializeToByteArray(Node node) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- canon.setWriter(baos);
- canon.notReset();
- canon.canonicalizeSubtree(node);
- return baos.toByteArray();
- }
-
- /**
- * @param source
- * @param ctx
- * @return the Node resulting from the parse of the source
- * @throws XMLEncryptionException
- */
- public abstract Node deserialize(String source, Node ctx) throws XMLEncryptionException;
-
- /**
- * @param source
- * @param ctx
- * @return the Node resulting from the parse of the source
- * @throws XMLEncryptionException
- */
- public abstract Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException;
-
- protected static byte[] createContext(byte[] source, Node ctx) throws XMLEncryptionException {
- // Create the context to parse the document against
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- try {
- OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
- outputStreamWriter.write("- * Note: XML Encryption does not provide an on-line key agreement - * negotiation protocol. The {@code AgreementMethod} element can be used by - * the originator to identify the keys and computational procedure that were - * used to obtain a shared encryption key. The method used to obtain or select - * the keys or algorithm used for the agreement computation is beyond the scope - * of this specification. - *
- * The {@code AgreementMethod} element appears as the content of a - * {@code ds:KeyInfo} since, like other {@code ds:KeyInfo} children, - * it yields a key. This {@code ds:KeyInfo} is in turn a child of an - * {@code EncryptedData} or {@code EncryptedKey} element. The - * Algorithm attribute and KeySize child of the {@code EncryptionMethod} - * element under this {@code EncryptedData} or {@code EncryptedKey} - * element are implicit parameters to the key agreement computation. In cases - * where this {@code EncryptionMethod} algorithm {@code URI} is - * insufficient to determine the key length, a KeySize MUST have been included. - * In addition, the sender may place a KA-Nonce element under - * {@code AgreementMethod} to assure that different keying material is - * generated even for repeated agreements using the same sender and recipient - * public keys. - *
- * If the agreed key is being used to wrap a key, then - * {@code AgreementMethod} would appear inside a {@code ds:KeyInfo} - * inside an {@code EncryptedKey} element. - *
- * The Schema for AgreementMethod is as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface AgreementMethod { - - /** - * Returns a {@code byte} array. - * @return a {@code byte} array. - */ - byte[] getKANonce(); - - /** - * Sets the KANonce.jj - * @param kanonce - */ - void setKANonce(byte[] kanonce); - - /** - * Returns additional information regarding the {@code AgreementMethod}. - * @return additional information regarding the {@code AgreementMethod}. - */ - Iterator- * - * - * }- * - *- * - * - * - * - * - *
{@code - *- */ - void addAgreementMethodInformation(Element info); - - /** - * Removes additional {@code AgreementMethod} information. - * - * @param info a {@code Element} that represents additional information - * specified by - *- * }
{@code - *- */ - void revoveAgreementMethodInformation(Element info); - - /** - * Returns information relating to the originator's shared secret. - * - * @return information relating to the originator's shared secret. - */ - KeyInfo getOriginatorKeyInfo(); - - /** - * Sets the information relating to the originator's shared secret. - * - * @param keyInfo information relating to the originator's shared secret. - */ - void setOriginatorKeyInfo(KeyInfo keyInfo); - - /** - * Returns information relating to the recipient's shared secret. - * - * @return information relating to the recipient's shared secret. - */ - KeyInfo getRecipientKeyInfo(); - - /** - * Sets the information relating to the recipient's shared secret. - * - * @param keyInfo information relating to the recipient's shared secret. - */ - void setRecipientKeyInfo(KeyInfo keyInfo); - - /** - * Returns the algorithm URI of this {@code CryptographicMethod}. - * - * @return the algorithm URI of this {@code CryptographicMethod} - */ - String getAlgorithm(); -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherData.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -/** - * {@code CipherData} provides encrypted data. It must either contain the - * encrypted octet sequence as base64 encoded text of the - * {@code CipherValue} element, or provide a reference to an external - * location containing the encrypted octet sequence via the - * {@code CipherReference} element. - *- * }
- * The schema definition is as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface CipherData { - - /** VALUE_TYPE ASN */ - int VALUE_TYPE = 0x00000001; - - /** REFERENCE_TYPE ASN */ - int REFERENCE_TYPE = 0x00000002; - - /** - * Returns the type of encrypted data contained in the - * {@code CipherData}. - * - * @return {@code VALUE_TYPE} if the encrypted data is contained as - * {@code CipherValue} or {@code REFERENCE_TYPE} if the - * encrypted data is contained as {@code CipherReference}. - */ - int getDataType(); - - /** - * Returns the cipher value as a base64 encoded {@code byte} array. - * - * @return the {@code CipherData}'s value. - */ - CipherValue getCipherValue(); - - /** - * Sets the {@code CipherData}'s value. - * - * @param value the value of the {@code CipherData}. - * @throws XMLEncryptionException - */ - void setCipherValue(CipherValue value) throws XMLEncryptionException; - - /** - * Returns a reference to an external location containing the encrypted - * octet sequence ({@code byte} array). - * - * @return the reference to an external location containing the encrypted - * octet sequence. - */ - CipherReference getCipherReference(); - - /** - * Sets the {@code CipherData}'s reference. - * - * @param reference an external location containing the encrypted octet sequence. - * @throws XMLEncryptionException - */ - void setCipherReference(CipherReference reference) throws XMLEncryptionException; -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherReference.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import org.w3c.dom.Attr; - -/** - * {@code CipherReference} identifies a source which, when processed, - * yields the encrypted octet sequence. - *- * - * - * }- * - *- * - *
- * The actual value is obtained as follows. The {@code CipherReference URI} - * contains an identifier that is dereferenced. Should the - * Transforms, the data resulting from dereferencing the {@code URI} is - * transformed as specified so as to yield the intended cipher value. For - * example, if the value is base64 encoded within an XML document; the - * transforms could specify an XPath expression followed by a base64 decoding so - * as to extract the octets. - *
- * The syntax of the {@code URI} and Transforms is similar to that of - * [XML-DSIG]. However, there is a difference between signature and encryption - * processing. In [XML-DSIG] both generation and validation processing start - * with the same source data and perform that transform in the same order. In - * encryption, the decryptor has only the cipher data and the specified - * transforms are enumerated for the decryptor, in the order necessary to obtain - * the octets. Consequently, because it has different semantics Transforms is in - * the &xenc; namespace. - *
- * The schema definition is as follows: - *
{@code - ** - * Additionally, if another Exception has been caught, we can supply it, too> + * Additionally, if another Exception has been caught, we can supply it, too *- * - * - * }- * - *- * - * - * - * @author Axl Mattheus - */ -public interface CipherReference { - /** - * Returns an {@code URI} that contains an identifier that should be - * dereferenced. - * @return an {@code URI} that contains an identifier that should be - * dereferenced. - */ - String getURI(); - - /** - * Gets the URI as an Attribute node. Used to meld the CipherReference - * with the XMLSignature ResourceResolvers - * @return the URI as an Attribute node - */ - Attr getURIAsAttr(); - - /** - * Returns the {@code Transforms} that specifies how to transform the - * {@code URI} to yield the appropriate cipher value. - * - * @return the transform that specifies how to transform the reference to - * yield the intended cipher value. - */ - Transforms getTransforms(); - - /** - * Sets the {@code Transforms} that specifies how to transform the - * {@code URI} to yield the appropriate cipher value. - * - * @param transforms the set of {@code Transforms} that specifies how - * to transform the reference to yield the intended cipher value. - */ - void setTransforms(Transforms transforms); -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/CipherValue.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -/** - ** - * Additionally, if another Exception has been caught, we can supply it, too> + * Additionally, if another Exception has been caught, we can supply it, too *CipherValue
is the wrapper for cipher text. - * - * @author Axl Mattheus - */ -public interface CipherValue { - /** - * Returns the Base 64 encoded, encrypted octets that is the - *CipherValue
. - * - * @return cipher value. - */ - String getValue(); - - /** - * Sets the Base 64 encoded, encrypted octets that is the - *CipherValue
. - * - * @param value the cipher value. - */ - void setValue(String value); -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/DocumentSerializer.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.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; - -/** - * ConvertsString
s intoNode
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); - } - } - -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedData.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -/** - * The {@code EncryptedData} element is the core element in the syntax. Not - * only does its {@code CipherData} child contain the encrypted data, but - * it's also the element that replaces the encrypted element, or serves as the - * new document root. - *- * It's schema definition is as follows: - *
- *
{@code - *- * - * @author Axl Mattheus - */ -public interface EncryptedData extends EncryptedType { -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedKey.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -/** - * The {@code EncryptedKey} element is used to transport encryption keys - * from the originator to a known recipient(s). It may be used as a stand-alone - * XML document, be placed within an application document, or appear inside an - * {@code EncryptedData} element as a child of a {@code ds:KeyInfo} - * element. The key value is always encrypted to the recipient(s). When - * {@code EncryptedKey} is decrypted the resulting octets are made - * available to the {@code EncryptionMethod} algorithm without any - * additional processing. - *- * - * - * }- * - *- * - * Its schema definition is as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface EncryptedKey extends EncryptedType { - - /** - * Returns a hint as to which recipient this encrypted key value is intended for. - * - * @return the recipient of the {@code EncryptedKey}. - */ - String getRecipient(); - - /** - * Sets the recipient for this {@code EncryptedKey}. - * - * @param recipient the recipient for this {@code EncryptedKey}. - */ - void setRecipient(String recipient); - - /** - * Returns pointers to data and keys encrypted using this key. The reference - * list may contain multiple references to {@code EncryptedKey} and - * {@code EncryptedData} elements. This is done using - * {@code KeyReference} and {@code DataReference} elements - * respectively. - * - * @return an {@code Iterator} over all the {@code ReferenceList}s - * contained in this {@code EncryptedKey}. - */ - ReferenceList getReferenceList(); - - /** - * Sets the {@code ReferenceList} to the {@code EncryptedKey}. - * - * @param list a list of pointers to data elements encrypted using this key. - */ - void setReferenceList(ReferenceList list); - - /** - * Returns a user readable name with the key value. This may then be used to - * reference the key using the {@code ds:KeyName} element within - * {@code ds:KeyInfo}. The same {@code CarriedKeyName} label, - * unlike an ID type, may occur multiple times within a single document. The - * value of the key is to be the same in all {@code EncryptedKey} - * elements identified with the same {@code CarriedKeyName} label - * within a single XML document. - *- * - * - * }- * - *- * - *- * - *- * - * - *
- * Note that because whitespace is significant in the value of - * the {@code ds:KeyName} element, whitespace is also significant in - * the value of the {@code CarriedKeyName} element. - * - * @return over all the carried names contained in - * this {@code EncryptedKey}. - */ - String getCarriedName(); - - /** - * Sets the carried name. - * - * @param name the carried name. - */ - void setCarriedName(String name); -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptedType.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import com.sun.org.apache.xml.internal.security.keys.KeyInfo; - -/** - * EncryptedType is the abstract type from which {@code EncryptedData} and - * {@code EncryptedKey} are derived. While these two latter element types - * are very similar with respect to their content models, a syntactical - * distinction is useful to processing. - *- * Its schema definition is as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface EncryptedType { - - /** - * Returns a {@code String} providing for the standard method of - * assigning an id to the element within the document context. - * - * @return the id for the {@code EncryptedType}. - */ - String getId(); - - /** - * Sets the id. - * - * @param id - */ - void setId(String id); - - /** - * Returns an {@code URI} identifying type information about the - * plaintext form of the encrypted content. While optional, this - * specification takes advantage of it for mandatory processing described in - * Processing Rules: Decryption (section 4.2). If the - * {@code EncryptedData} element contains data of Type 'element' or - * element 'content', and replaces that data in an XML document context, it - * is strongly recommended the Type attribute be provided. Without this - * information, the decryptor will be unable to automatically restore the - * XML document to its original cleartext form. - * - * @return the identifier for the type of information in plaintext form of - * encrypted content. - */ - String getType(); - - /** - * Sets the type. - * - * @param type an {@code URI} identifying type information about the - * plaintext form of the encrypted content. - */ - void setType(String type); - - /** - * Returns a {@code String} which describes the media type of the data - * which has been encrypted. The value of this attribute has values defined - * by [MIME]. For example, if the data that is encrypted is a base64 encoded - * PNG, the transfer Encoding may be specified as - * 'http://www.w3.org/2000/09/xmldsig#base64' and the MimeType as - * 'image/png'. - *- * - * }- * - *- * - * - * - * - * - * - * - *
- * This attribute is purely advisory; no validation of the MimeType - * information is required and it does not indicate the encryption - * application must do any additional processing. Note, this information may - * not be necessary if it is already bound to the identifier in the Type - * attribute. For example, the Element and Content types defined in this - * specification are always UTF-8 encoded text. - * - * @return the media type of the data which was encrypted. - */ - String getMimeType(); - - /** - * Sets the mime type. - * - * @param type a {@code String} which describes the media type of the - * data which has been encrypted. - */ - void setMimeType(String type); - - /** - * Return an {@code URI} representing the encoding of the - * {@code EncryptedType}. - * - * @return the encoding of this {@code EncryptedType}. - */ - String getEncoding(); - - /** - * Sets the {@code URI} representing the encoding of the - * {@code EncryptedType}. - * - * @param encoding - */ - void setEncoding(String encoding); - - /** - * Returns an {@code EncryptionMethod} that describes the encryption - * algorithm applied to the cipher data. If the element is absent, the - * encryption algorithm must be known by the recipient or the decryption - * will fail. - * - * @return the method used to encrypt the cipher data. - */ - EncryptionMethod getEncryptionMethod(); - - /** - * Sets the {@code EncryptionMethod} used to encrypt the cipher data. - * - * @param method the {@code EncryptionMethod}. - */ - void setEncryptionMethod(EncryptionMethod method); - - /** - * Returns the {@code ds:KeyInfo}, that carries information about the - * key used to encrypt the data. Subsequent sections of this specification - * define new elements that may appear as children of - * {@code ds:KeyInfo}. - * - * @return information about the key that encrypted the cipher data. - */ - KeyInfo getKeyInfo(); - - /** - * Sets the encryption key information. - * - * @param info the {@code ds:KeyInfo}, that carries information about - * the key used to encrypt the data. - */ - void setKeyInfo(KeyInfo info); - - /** - * Returns the {@code CipherReference} that contains the - * {@code CipherValue} or {@code CipherReference} with the - * encrypted data. - * - * @return the cipher data for the encrypted type. - */ - CipherData getCipherData(); - - /** - * Returns additional information concerning the generation of the - * {@code EncryptedType}. - * - * @return information relating to the generation of the - * {@code EncryptedType}. - */ - EncryptionProperties getEncryptionProperties(); - - /** - * Sets the {@code EncryptionProperties} that supplies additional - * information about the generation of the {@code EncryptedType}. - * - * @param properties - */ - void setEncryptionProperties(EncryptionProperties properties); -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionMethod.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.util.Iterator; -import org.w3c.dom.Element; - -/** - * {@code EncryptionMethod} describes the encryption algorithm applied to - * the cipher data. If the element is absent, the encryption algorithm must be - * known by the recipient or the decryption will fail. - *- * It is defined as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface EncryptionMethod { - /** - * Returns the algorithm applied to the cipher data. - * - * @return the encryption algorithm. - */ - String getAlgorithm(); - - /** - * Returns the key size of the key of the algorithm applied to the cipher - * data. - * - * @return the key size. - */ - int getKeySize(); - - /** - * Sets the size of the key of the algorithm applied to the cipher data. - * - * @param size the key size. - */ - void setKeySize(int size); - - /** - * Returns the OAEP parameters of the algorithm applied applied to the - * cipher data. - * - * @return the OAEP parameters. - */ - byte[] getOAEPparams(); - - /** - * Sets the OAEP parameters. - * - * @param parameters the OAEP parameters. - */ - void setOAEPparams(byte[] parameters); - - /** - * Set the Digest Algorithm to use - * @param digestAlgorithm the Digest Algorithm to use - */ - void setDigestAlgorithm(String digestAlgorithm); - - /** - * Get the Digest Algorithm to use - * @return the Digest Algorithm to use - */ - String getDigestAlgorithm(); - - /** - * Set the MGF Algorithm to use - * @param mgfAlgorithm the MGF Algorithm to use - */ - void setMGFAlgorithm(String mgfAlgorithm); - - /** - * Get the MGF Algorithm to use - * @return the MGF Algorithm to use - */ - String getMGFAlgorithm(); - - /** - * Returns an iterator over all the additional elements contained in the - * {@code EncryptionMethod}. - * - * @return an {@code Iterator} over all the additional information - * about the {@code EncryptionMethod}. - */ - Iterator- * - * }- * - *- * - * - * - * getEncryptionMethodInformation(); - - /** - * Adds encryption method information. - * - * @param information additional encryption method information. - */ - void addEncryptionMethodInformation(Element information); - - /** - * Removes encryption method information. - * - * @param information the information to remove from the - * {@code EncryptionMethod}. - */ - void removeEncryptionMethodInformation(Element information); -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperties.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.util.Iterator; - -/** - * {@code EncryptionProperties} can hold additional information concerning - * the generation of the {@code EncryptedData} or - * {@code EncryptedKey}. This information is wraped int an - * {@code EncryptionProperty} element. Examples of additional information - * is e.g., a date/time stamp or the serial number of cryptographic hardware - * used during encryption). - * - * It is defined as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface EncryptionProperties { - - /** - * Returns the {@code EncryptionProperties}' id. - * - * @return the id. - */ - String getId(); - - /** - * Sets the id. - * - * @param id the id. - */ - void setId(String id); - - /** - * Returns an {@code Iterator} over all the - * {@code EncryptionPropterty} elements contained in this - * {@code EncryptionProperties}. - * - * @return an {@code Iterator} over all the encryption properties. - */ - Iterator- * - * - * }- * - *- * - * getEncryptionProperties(); - - /** - * Adds an {@code EncryptionProperty}. - * - * @param property - */ - void addEncryptionProperty(EncryptionProperty property); - - /** - * Removes the specified {@code EncryptionProperty}. - * - * @param property - */ - void removeEncryptionProperty(EncryptionProperty property); -} - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/EncryptionProperty.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.util.Iterator; -import org.w3c.dom.Element; - -/** - * Additional information items concerning the generation of the - * {@code EncryptedData} or {@code EncryptedKey} can be placed in an - * {@code EncryptionProperty} element (e.g., date/time stamp or the serial - * number of cryptographic hardware used during encryption). The Target - * attribute identifies the {@code EncryptedType} structure being - * described. anyAttribute permits the inclusion of attributes from the XML - * namespace to be included (i.e., {@code xml:space}, - * {@code xml:lang}, and {@code xml:base}). - * - * It is defined as follows: - *
{@code - *- * - * @author Axl Mattheus - */ -public interface EncryptionProperty { - - /** - * Returns the {@code EncryptedType} being described. - * - * @return the {@code EncryptedType} being described by this - * {@code EncryptionProperty}. - */ - String getTarget(); - - /** - * Sets the target. - * - * @param target - */ - void setTarget(String target); - - /** - * Returns the id of the {@CODE EncryptionProperty}. - * - * @return the id. - */ - String getId(); - - /** - * Sets the id. - * - * @param id - */ - void setId(String id); - - /** - * Returns the attribute's value in the {@code xml} namespace. - * - * @param attribute - * @return the attribute's value. - */ - String getAttribute(String attribute); - - /** - * Set the attribute value. - * - * @param attribute the attribute's name. - * @param value the attribute's value. - */ - void setAttribute(String attribute, String value); - - /** - * Returns the properties of the {@CODE EncryptionProperty}. - * - * @return an {@code Iterator} over all the additional encryption - * information contained in this class. - */ - Iterator- * - * - * }- * - *- * - * - * - * getEncryptionInformation(); - - /** - * Adds encryption information. - * - * @param information the additional encryption information. - */ - void addEncryptionInformation(Element information); - - /** - * Removes encryption information. - * - * @param information the information to remove. - */ - void removeEncryptionInformation(Element information); -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Reference.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.util.Iterator; -import org.w3c.dom.Element; - -/** - * A wrapper for a pointer from a key value of an {@code EncryptedKey} to - * items encrypted by that key value ({@code EncryptedData} or - * {@code EncryptedKey} elements). - * - * It is defined as follows: - *
{@code - *- * - * @author Axl Mattheus - * @see ReferenceList - */ -public interface Reference { - /** - * Returns the {@code Element} tag name for this {@code Reference}. - * - * @return the tag name of this {@code Reference}. - */ - String getType(); - - /** - * Returns a {@code URI} that points to an {@code Element} that - * were encrypted using the key defined in the enclosing - * {@code EncryptedKey} element. - * - * @return an Uniform Resource Identifier that qualifies an - * {@code EncryptedType}. - */ - String getURI(); - - /** - * Sets a {@code URI} that points to an {@code Element} that - * were encrypted using the key defined in the enclosing - * {@code EncryptedKey} element. - * - * @param uri the Uniform Resource Identifier that qualifies an - * {@code EncryptedType}. - */ - void setURI(String uri); - - /** - * Returns an {@code Iterator} over all the child elements contained in - * this {@code Reference} that will aid the recipient in retrieving the - * {@code EncryptedKey} and/or {@code EncryptedData} elements. - * These could include information such as XPath transforms, decompression - * transforms, or information on how to retrieve the elements from a - * document storage facility. - * - * @return child elements. - */ - Iterator- * - * }- * - *- * - * getElementRetrievalInformation(); - - /** - * Adds retrieval information. - * - * @param info - */ - void addElementRetrievalInformation(Element info); - - /** - * Removes the specified retrieval information. - * - * @param info - */ - void removeElementRetrievalInformation(Element info); -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/ReferenceList.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.util.Iterator; - -/** - * {@code ReferenceList} is an element that contains pointers from a key - * value of an {@code EncryptedKey} to items encrypted by that key value - * ({@code EncryptedData} or {@code EncryptedKey} elements). - * - * It is defined as follows: - *
{@code - *- * - * @author Axl Mattheus - * @see Reference - */ -public interface ReferenceList { - - /** DATA TAG */ - int DATA_REFERENCE = 0x00000001; - - /** KEY TAG */ - int KEY_REFERENCE = 0x00000002; - - /** - * Adds a reference to this reference list. - * - * @param reference the reference to add. - * @throws IllegalAccessException if the {@code Reference} is not an - * instance of {@code DataReference} or {@code KeyReference}. - */ - void add(Reference reference); - - /** - * Removes a reference from the {@code ReferenceList}. - * - * @param reference the reference to remove. - */ - void remove(Reference reference); - - /** - * Returns the size of the {@code ReferenceList}. - * - * @return the size of the {@code ReferenceList}. - */ - int size(); - - /** - * Indicates if the {@code ReferenceList} is empty. - * - * @return {@code true} if the {@code ReferenceList} is - * empty, else {@code false}. - */ - boolean isEmpty(); - - /** - * Returns an {@code Iterator} over all the {@code Reference}s - * contained in this {@code ReferenceList}. - * - * @return Iterator. - */ - Iterator- * - * }- * - *- * - *- * - * getReferences(); - - /** - * {@code DataReference} factory method. Returns a - * {@code DataReference}. - * @param uri - * @return a {@code DataReference}. - */ - Reference newDataReference(String uri); - - /** - * {@code KeyReference} factory method. Returns a - * {@code KeyReference}. - * @param uri - * @return a {@code KeyReference}. - */ - Reference newKeyReference(String uri); -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Serializer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.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 String
s intoNode
s and visa versa. - */ -public interface Serializer { - - /** - * Set the Canonicalizer object to use. - */ - void setCanonicalizer(Canonicalizer canon); - - /** - * Returns abyte[]
representation of the specified - *Element
. - * - * @param element theElement
to serialize. - * @return thebyte[]
representation of the serilaized - *Element
. - * @throws Exception - */ - byte[] serializeToByteArray(Element element) throws Exception; - - /** - * Returns abyte[]
representation of the specified - *NodeList
. - * - * @param content theNodeList
to serialize. - * @return thebyte[]
representation of the serialized - *NodeList
. - * @throws Exception - */ - byte[] serializeToByteArray(NodeList content) throws Exception; - - /** - * Use the Canonicalizer to serialize the node - * @param node - * @return the (byte[]) canonicalization of the node - * @throws Exception - */ - byte[] canonSerializeToByteArray(Node node) throws Exception; - - /** - * @param source - * @param ctx - * @return the Node resulting from the parse of the source - * @throws XMLEncryptionException - */ - Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException; -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/Transforms.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -/** - * A container for {@code ds:Transform}s. - *- * It is defined as follows: - *
{@code - *- * - * @author Axl Mattheus - * @see com.sun.org.apache.xml.internal.security.encryption.CipherReference - */ -public interface Transforms { - /** - * Temporary method to turn the XMLEncryption Transforms class - * into a DS class. The main logic is currently implemented in the - * DS class, so we need to get to get the base class. - *- * - * }- * - *- * - * Note This will be removed in future versions - */ - com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms(); - -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipher.java +++ /dev/null @@ -1,3539 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -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.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; -import com.sun.org.apache.xml.internal.security.transforms.TransformationException; -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.ElementProxy; -import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; -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; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - *
XMLCipher
encrypts and decrypts the contents of - *Document
s,Element
s andElement
- * contents. It was designed to resemblejavax.crypto.Cipher
in - * order to facilitate understanding of its functioning. - * - * @author Axl Mattheus (Sun Microsystems) - * @author Christian Geuer-Pollmann - */ -public class XMLCipher { - - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLCipher.class.getName()); - - /** 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 exclusive */ - public static final String EXCL_XML_N14C = - Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; - - /** N14C_XML exclusive with comments*/ - public static final String EXCL_XML_N14C_WITH_COMMENTS = - Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; - - /** N14C_PHYSICAL preserve the physical representation*/ - public static final String PHYSICAL_XML_N14C = - Canonicalizer.ALGO_ID_C14N_PHYSICAL; - - /** Base64 encoding */ - public static final String BASE64_ENCODING = - com.sun.org.apache.xml.internal.security.transforms.Transforms.TRANSFORM_BASE64_DECODE; - - /** 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" + 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 SecureRandom random; - - private boolean secureValidation; - - private String digestAlg; - - /** List of internal KeyResolvers for DECRYPT and UNWRAP modes. */ - private ListinternalKeyResolvers; - - /** - * Set the Serializer algorithm to use - */ - public void setSerializer(Serializer serializer) { - this.serializer = serializer; - serializer.setCanonicalizer(this.canon); - } - - /** - * Get the Serializer algorithm to use - */ - public Serializer getSerializer() { - return serializer; - } - - /** - * Creates a new XMLCipher
. - * - * @param transformation the name of the transformation, e.g., - *XMLCipher.TRIPLEDES
. If null the XMLCipher can only - * be used for decrypt or unwrap operations where the encryption method - * is defined in theEncryptionMethod
element. - * @param provider the JCE provider that supplies the transformation, - * if null use the default provider. - * @param canon the name of the c14n algorithm, if - *null
use standard serializer - * @param digestMethod An optional digestMethod to use. - */ - private XMLCipher( - String transformation, - String provider, - String canonAlg, - String digestMethod - ) throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Constructing XMLCipher..."); - } - - factory = new Factory(); - - algorithm = transformation; - requestedJCEProvider = provider; - digestAlg = digestMethod; - - // Create a canonicalizer - used when serializing DOM to octets - // prior to encryption (and for the reverse) - - 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); - } - } - - /** - * Checks to ensure that the supplied algorithm is valid. - * - * @param algorithm the algorithm to check. - * @return true if the algorithm is valid, otherwise false. - * @since 1.0. - */ - private static boolean isValidEncryptionAlgorithm(String algorithm) { - 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) - ); - } - - /** - * Validate the transformation argument of getInstance or getProviderInstance - * - * @param transformation the name of the transformation, e.g., - *XMLCipher.TRIPLEDES
which is shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - */ - private static void validateTransformation(String transformation) { - if (null == transformation) { - throw new NullPointerException("Transformation unexpectedly null..."); - } - if (!isValidEncryptionAlgorithm(transformation)) { - log.log(java.util.logging.Level.WARNING, "Algorithm non-standard, expected one of " + ENC_ALGORITHMS); - } - } - - /** - * Returns anXMLCipher
that implements the specified - * transformation and operates on the specified context document. - *- * If the default provider package supplies an implementation of the - * requested transformation, an instance of Cipher containing that - * implementation is returned. If the transformation is not available in - * the default provider package, other provider packages are searched. - *
- * NOTE1: The transformation name does not follow the same - * 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. - *
- * NOTE2:
getInstance()
does not follow the - * same pattern regarding exceptional conditions as that used in - *javax.crypto.Cipher
. Instead, it only throws an - *XMLEncryptionException
which wraps an underlying exception. - * The stack trace from the exception should be self explanatory. - * - * @param transformation the name of the transformation, e.g., - *XMLCipher.TRIPLEDES
which is shorthand for - * "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" - * @throws XMLEncryptionException - * @return the XMLCipher - * @see javax.crypto.Cipher#getInstance(java.lang.String) - */ - 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"); - } - validateTransformation(transformation); - return new XMLCipher(transformation, null, null, null); - } - - /** - * Returns anXMLCipher
that implements the specified - * transformation, operates on the specified context document and serializes - * the document with the specified canonicalization algorithm before it - * encrypts the document. - *- * - * @param transformation the name of the transformation - * @param canon the name of the c14n algorithm, if
null
use - * standard serializer - * @return the XMLCipher - * @throws XMLEncryptionException - */ - public static XMLCipher getInstance(String transformation, String canon) - throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm"); - } - validateTransformation(transformation); - return new XMLCipher(transformation, null, canon, null); - } - - /** - * Returns anXMLCipher
that implements the specified - * transformation, operates on the specified context document and serializes - * the document with the specified canonicalization algorithm before it - * encrypts the document. - *- * - * @param transformation the name of the transformation - * @param canon the name of the c14n algorithm, if
null
use - * standard serializer - * @param digestMethod An optional digestMethod to use - * @return the XMLCipher - * @throws XMLEncryptionException - */ - public static XMLCipher getInstance(String transformation, String canon, String digestMethod) - throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation and c14n algorithm"); - } - validateTransformation(transformation); - return new XMLCipher(transformation, null, canon, digestMethod); - } - - /** - * Returns anXMLCipher
that implements the specified - * transformation and operates on the specified context document. - * - * @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 { - 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.."); - } - validateTransformation(transformation); - return new XMLCipher(transformation, provider, null, null); - } - - /** - * Returns anXMLCipher
that implements the specified - * transformation, operates on the specified context document and serializes - * the document with the specified canonicalization algorithm before it - * encrypts the document. - *- * - * @param transformation the name of the transformation - * @param provider the JCE provider that supplies the transformation - * @param canon the name of the c14n algorithm, if
null
use standard - * serializer - * @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 anXMLCipher
that implements the specified - * transformation, operates on the specified context document and serializes - * the document with the specified canonicalization algorithm before it - * encrypts the document. - *- * - * @param transformation the name of the transformation - * @param provider the JCE provider that supplies the transformation - * @param canon the name of the c14n algorithm, if
null
use standard - * serializer - * @param digestMethod An optional digestMethod to use - * @return the XMLCipher - * @throws XMLEncryptionException - */ - public static XMLCipher getProviderInstance( - String transformation, String provider, String canon, String digestMethod - ) throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Getting XMLCipher with transformation, provider and c14n algorithm"); - } - if (null == provider) { - throw new NullPointerException("Provider unexpectedly null.."); - } - validateTransformation(transformation); - return new XMLCipher(transformation, provider, canon, digestMethod); - } - - /** - * Returns anXMLCipher
that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - *EncryptionMethod
element. - * - * @return The XMLCipher - * @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 anXMLCipher
that implements no specific - * transformation, and can therefore only be used for decrypt or - * unwrap operations where the encryption method is defined in the - *EncryptionMethod
element. - * - * Allows the caller to specify a provider that will be used for - * cryptographic operations. - * - * @param provider the JCE provider that supplies the transformation - * @return the XMLCipher - * @throws XMLEncryptionException - */ - public static XMLCipher getProviderInstance(String provider) throws XMLEncryptionException { - 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); - } - - /** - * Initializes this cipher with a key. - *- * 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}. - * - * @param opmode the operation mode of this cipher (this is one of the - * following: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE or UNWRAP_MODE) - * @param key - * @see javax.crypto.Cipher#init(int, java.security.Key) - * @throws XMLEncryptionException - */ - public void init(int opmode, Key key) throws XMLEncryptionException { - // sanity checks - 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; - } - - /** - * This method is used to add a custom {@link KeyResolverSpi} to an XMLCipher. - * These KeyResolvers are used in KeyInfo objects in DECRYPT and - * UNWRAP modes. - * - * @param keyResolver - */ - public void registerInternalKeyResolver(KeyResolverSpi keyResolver) { - if (internalKeyResolvers == null) { - internalKeyResolvers = new ArrayList
(); - } - internalKeyResolvers.add(keyResolver); - } - - /** - * Get the EncryptedData being built - * - * Returns the EncryptedData being built during an ENCRYPT operation. - * This can then be used by applications to add KeyInfo elements and - * set other parameters. - * - * @return The EncryptedData being built - */ - public EncryptedData getEncryptedData() { - // Sanity checks - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Returning EncryptedData"); - } - return ed; - } - - /** - * Get the EncryptedData being build - * - * Returns the EncryptedData being built during an ENCRYPT operation. - * This can then be used by applications to add KeyInfo elements and - * set other parameters. - * - * @return The EncryptedData being built - */ - public EncryptedKey getEncryptedKey() { - // Sanity checks - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Returning EncryptedKey"); - } - return ek; - } - - /** - * Set a Key Encryption Key. - *
- * The Key Encryption Key (KEK) is used for encrypting/decrypting - * EncryptedKey elements. By setting this separately, the XMLCipher - * class can know whether a key applies to the data part or wrapped key - * part of an encrypted object. - * - * @param kek The key to use for de/encrypting key data - */ - - public void setKEK(Key kek) { - this.kek = kek; - } - - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriate
EncryptedData
- *- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedData EncryptedData object to martial - * @return the DOM
Element
representing the passed in - * object - */ - public Element martial(EncryptedData encryptedData) { - return factory.toElement(encryptedData); - } - - /** - * Martial an EncryptedData - * - * Takes an EncryptedData object and returns a DOM Element that - * represents the appropriateEncryptedData
- * - * @param context The document that will own the returned nodes - * @param encryptedData EncryptedData object to martial - * @return the DOMElement
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 appropriateEncryptedKey
- * - *- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param encryptedKey EncryptedKey object to martial - * @return the DOM
Element
representing the passed in - * object - */ - public Element martial(EncryptedKey encryptedKey) { - return factory.toElement(encryptedKey); - } - - /** - * Martial an EncryptedKey - * - * Takes an EncryptedKey object and returns a DOM Element that - * represents the appropriateEncryptedKey
- * - * @param context The document that will own the created nodes - * @param encryptedKey EncryptedKey object to martial - * @return the DOMElement
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 appropriateReferenceList
- * - *- * Note: This should only be used in cases where the context - * document has been passed in via a call to doFinal. - * - * @param referenceList ReferenceList object to martial - * @return the DOM
Element
representing the passed in - * object - */ - public Element martial(ReferenceList referenceList) { - return factory.toElement(referenceList); - } - - /** - * Martial a ReferenceList - * - * Takes a ReferenceList object and returns a DOM Element that - * represents the appropriateReferenceList
- * - * @param context The document that will own the created nodes - * @param referenceList ReferenceList object to martial - * @return the DOMElement
representing the passed in - * object - */ - public Element martial(Document context, ReferenceList referenceList) { - contextDocument = context; - return factory.toElement(referenceList); - } - - /** - * Encrypts anElement
and replaces it with its encrypted - * counterpart in the contextDocument
, that is, the - *Document
specified when one calls - * {@link #getInstance(String) getInstance}. - * - * @param element theElement
to encrypt. - * @return the contextDocument
with the encrypted - *Element
having replaced the sourceElement
. - * @throws Exception - */ - private Document encryptElement(Element element) throws Exception{ - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Encrypting element..."); - } - if (null == element) { - log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null..."); - } - if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE..."); - } - - if (algorithm == null) { - throw new XMLEncryptionException("XMLCipher instance without transformation specified"); - } - encryptData(contextDocument, element, false); - - Element encryptedElement = factory.toElement(ed); - - Node sourceParent = element.getParentNode(); - sourceParent.replaceChild(encryptedElement, element); - - return contextDocument; - } - - /** - * Encrypts aNodeList
(the contents of an - *Element
) and replaces its parentElement
's - * content with this the resultingEncryptedType
within the - * contextDocument
, that is, theDocument
- * specified when one calls - * {@link #getInstance(String) getInstance}. - * - * @param element theNodeList
to encrypt. - * @return the contextDocument
with the encrypted - *NodeList
having replaced the content of the source - *Element
. - * @throws Exception - */ - 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; - } - - /** - * Process a DOMDocument
node. The processing depends on the - * initialization parameters of {@link #init(int, Key) init()}. - * - * @param context the contextDocument
. - * @param source theDocument
to be encrypted or decrypted. - * @return the processedDocument
. - * @throws Exception to indicate any exceptional conditions. - */ - 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) { - case DECRYPT_MODE: - result = decryptElement(source.getDocumentElement()); - break; - case ENCRYPT_MODE: - result = encryptElement(source.getDocumentElement()); - break; - case UNWRAP_MODE: - case WRAP_MODE: - break; - default: - throw new XMLEncryptionException("empty", new IllegalStateException()); - } - - return result; - } - - /** - * Process a DOMElement
node. The processing depends on the - * initialization parameters of {@link #init(int, Key) init()}. - * - * @param context the contextDocument
. - * @param element theElement
to be encrypted. - * @return the processedDocument
. - * @throws Exception to indicate any exceptional conditions. - */ - 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) { - case DECRYPT_MODE: - result = decryptElement(element); - break; - case ENCRYPT_MODE: - result = encryptElement(element); - break; - case UNWRAP_MODE: - case WRAP_MODE: - break; - default: - throw new XMLEncryptionException("empty", new IllegalStateException()); - } - - return result; - } - - /** - * Process the contents of a DOMElement
node. The processing - * depends on the initialization parameters of - * {@link #init(int, Key) init()}. - * - * @param context the contextDocument
. - * @param element theElement
which contents is to be - * encrypted. - * @param content - * @return the processedDocument
. - * @throws Exception to indicate any exceptional conditions. - */ - public Document doFinal(Document context, Element element, boolean content) - 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) { - case DECRYPT_MODE: - if (content) { - result = decryptElementContent(element); - } else { - result = decryptElement(element); - } - break; - case ENCRYPT_MODE: - if (content) { - result = encryptElementContent(element); - } else { - result = encryptElement(element); - } - break; - case UNWRAP_MODE: - case WRAP_MODE: - break; - default: - throw new XMLEncryptionException("empty", new IllegalStateException()); - } - - return result; - } - - /** - * Returns anEncryptedData
interface. Use this operation if - * you want to have full control over the contents of the - *EncryptedData
structure. - * - * This does not change the source document in any way. - * - * @param context the contextDocument
. - * @param element theElement
that will be encrypted. - * @return theEncryptedData
- * @throws Exception - */ - public EncryptedData encryptData(Document context, Element element) throws - /* XMLEncryption */Exception { - return encryptData(context, element, false); - } - - /** - * Returns anEncryptedData
interface. Use this operation if - * you want to have full control over the serialization of the element - * or element content. - * - * This does not change the source document in any way. - * - * @param context the contextDocument
. - * @param type a URI identifying type information about the plaintext form - * of the encrypted content (may benull
) - * @param serializedData the serialized data - * @return theEncryptedData
- * @throws Exception - */ - 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); - } - - /** - * Returns anEncryptedData
interface. Use this operation if - * you want to have full control over the contents of the - *EncryptedData
structure. - * - * This does not change the source document in any way. - * - * @param context the contextDocument
. - * @param element theElement
that will be encrypted. - * @param contentModetrue
to encrypt element's content only, - *false
otherwise - * @return theEncryptedData
- * @throws Exception - */ - public EncryptedData encryptData( - 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); - } else { - 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"); - } - - byte[] serializedOctets = null; - if (serializedData == null) { - if (type.equals(EncryptionConstants.TYPE_CONTENT)) { - NodeList children = element.getChildNodes(); - if (null != children) { - serializedOctets = serializer.serializeToByteArray(children); - } else { - Object exArgs[] = { "Element has no content." }; - throw new XMLEncryptionException("empty", exArgs); - } - } else { - serializedOctets = serializer.serializeToByteArray(element); - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Serialized octets:\n" + new String(serializedOctets, "UTF-8")); - } - } - - byte[] encryptedBytes = null; - - // Now create the working cipher if none was created already - Cipher c; - if (contextCipher == null) { - c = constructCipher(algorithm, null); - } else { - c = contextCipher; - } - // Now perform the encryption - - try { - // 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 { - if (serializedData != null) { - int numBytes; - byte[] buf = new byte[8192]; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - while ((numBytes = serializedData.read(buf)) != -1) { - byte[] data = c.update(buf, 0, numBytes); - baos.write(data); - } - baos.write(c.doFinal()); - encryptedBytes = baos.toByteArray(); - } else { - encryptedBytes = c.doFinal(serializedOctets); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Expected cipher.outputSize = " + - Integer.toString(c.getOutputSize(serializedOctets.length))); - } - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Actual cipher.outputSize = " - + Integer.toString(encryptedBytes.length)); - } - } catch (IllegalStateException ise) { - throw new XMLEncryptionException("empty", ise); - } catch (IllegalBlockSizeException ibse) { - throw new XMLEncryptionException("empty", ibse); - } catch (BadPaddingException bpe) { - throw new XMLEncryptionException("empty", bpe); - } catch (UnsupportedEncodingException uee) { - throw new XMLEncryptionException("empty", uee); - } - - // 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]; - System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length); - System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length); - String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes); - - 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(); - CipherValue cv = cd.getCipherValue(); - // cv.setValue(base64EncodedEncryptedOctets.getBytes()); - cv.setValue(base64EncodedEncryptedOctets); - - if (type != null) { - ed.setType(new URI(type).toString()); - } - EncryptionMethod method = - factory.newEncryptionMethod(new URI(algorithm).toString()); - method.setDigestAlgorithm(digestAlg); - ed.setEncryptionMethod(method); - } catch (URISyntaxException ex) { - throw new XMLEncryptionException("empty", ex); - } - return ed; - } - - /** - * Returns anEncryptedData
interface. Use this operation if - * you want to load anEncryptedData
structure from a DOM - * structure and manipulate the contents. - * - * @param context the contextDocument
. - * @param element theElement
that will be loaded - * @throws XMLEncryptionException - * @return theEncryptedData
- */ - public EncryptedData loadEncryptedData(Document context, Element element) - throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Loading encrypted element..."); - } - if (null == context) { - throw new NullPointerException("Context document unexpectedly null..."); - } - if (null == element) { - throw new NullPointerException("Element unexpectedly null..."); - } - if (cipherMode != DECRYPT_MODE) { - throw new XMLEncryptionException("XMLCipher unexpectedly not in DECRYPT_MODE..."); - } - - contextDocument = context; - ed = factory.newEncryptedData(element); - - return ed; - } - - /** - * Returns anEncryptedKey
interface. Use this operation if - * you want to load anEncryptedKey
structure from a DOM - * structure and manipulate the contents. - * - * @param context the contextDocument
. - * @param element theElement
that will be loaded - * @return theEncryptedKey
- * @throws XMLEncryptionException - */ - public EncryptedKey loadEncryptedKey(Document context, Element element) - throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Loading encrypted key..."); - } - if (null == context) { - throw new NullPointerException("Context document unexpectedly null..."); - } - if (null == element) { - throw new NullPointerException("Element unexpectedly null..."); - } - if (cipherMode != UNWRAP_MODE && cipherMode != DECRYPT_MODE) { - throw new XMLEncryptionException( - "XMLCipher unexpectedly not in UNWRAP_MODE or DECRYPT_MODE..." - ); - } - - contextDocument = context; - ek = factory.newEncryptedKey(element); - return ek; - } - - /** - * Returns anEncryptedKey
interface. Use this operation if - * you want to load anEncryptedKey
structure from a DOM - * structure and manipulate the contents. - * - * Assumes that the context document is the document that owns the element - * - * @param element theElement
that will be loaded - * @return theEncryptedKey
- * @throws XMLEncryptionException - */ - 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 theEncryptedKey
- * @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 - * @param mgfAlgorithm The xenc11 MGF Algorithm to use - * @param oaepParams The OAEPParams to use - * @return theEncryptedKey
- * @throws XMLEncryptionException - */ - public EncryptedKey encryptKey( - Document doc, - Key key, - String mgfAlgorithm, - byte[] oaepParams - ) throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Encrypting key ..."); - } - - if (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); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets); - log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length()); - } - - CipherValue cv = ek.getCipherData().getCipherValue(); - cv.setValue(base64EncodedEncryptedOctets); - - try { - EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString()); - method.setDigestAlgorithm(digestAlg); - method.setMGFAlgorithm(mgfAlgorithm); - method.setOAEPparams(oaepParams); - ek.setEncryptionMethod(method); - } catch (URISyntaxException ex) { - throw new XMLEncryptionException("empty", ex); - } - return ek; - } - - /** - * Decrypt a key from a passed in EncryptedKey structure - * - * @param encryptedKey Previously loaded EncryptedKey that needs - * to be decrypted. - * @param algorithm Algorithm for the decryption - * @return a key corresponding to the given type - * @throws XMLEncryptionException - */ - public Key decryptKey(EncryptedKey encryptedKey, String algorithm) - throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Decrypting key from previously loaded EncryptedKey..."); - } - - 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(); - } - } - catch (Exception e) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, e.getMessage(), e); - } - } - } - if (key == null) { - log.log(java.util.logging.Level.SEVERE, "XMLCipher::decryptKey called without a KEK and cannot resolve"); - throw new XMLEncryptionException("Unable to decrypt without a KEK"); - } - } - - // 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"); - } - } - return new OAEPParameterSpec(jceDigestAlgorithm, "MGF1", mgfParameterSpec, pSource); - } - - return null; - } - - /** - * Construct a Cipher object - */ - private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException { - String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm); - } - - Cipher c; - try { - if (requestedJCEProvider == null) { - c = Cipher.getInstance(jceAlgorithm); - } else { - c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider); - } - } catch (NoSuchAlgorithmException nsae) { - // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested - // Some JDKs don't support RSA/ECB/OAEPPadding - if (XMLCipher.RSA_OAEP.equals(algorithm) - && (digestAlgorithm == null - || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) { - try { - if (requestedJCEProvider == null) { - c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); - } else { - c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider); - } - } catch (Exception ex) { - throw new XMLEncryptionException("empty", ex); - } - } else { - throw new XMLEncryptionException("empty", nsae); - } - } catch (NoSuchProviderException nspre) { - throw new XMLEncryptionException("empty", nspre); - } catch (NoSuchPaddingException nspae) { - throw new XMLEncryptionException("empty", nspae); - } - - return c; - } - - /** - * Decrypt a key from a passed in EncryptedKey structure. This version - * is used mainly internally, when the cipher already has an - * EncryptedData loaded. The algorithm URI will be read from the - * EncryptedData - * - * @param encryptedKey Previously loaded EncryptedKey that needs - * to be decrypted. - * @return a key corresponding to the given type - * @throws XMLEncryptionException - */ - public Key decryptKey(EncryptedKey encryptedKey) throws XMLEncryptionException { - return decryptKey(encryptedKey, ed.getEncryptionMethod().getAlgorithm()); - } - - /** - * Removes the contents of aNode
. - * - * @param node theNode
to clear. - */ - private static void removeContent(Node node) { - while (node.hasChildNodes()) { - node.removeChild(node.getFirstChild()); - } - } - - /** - * DecryptsEncryptedData
in a single-part operation. - * - * @param element theEncryptedData
to decrypt. - * @return theNode
as a result of the decrypt operation. - * @throws XMLEncryptionException - */ - 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 theNode
as a result of the decrypt operation. - * @throws XMLEncryptionException - */ - private Document decryptElementContent(Element element) throws XMLEncryptionException { - Element e = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA - ).item(0); - - if (null == e) { - throw new XMLEncryptionException("No EncryptedData child element."); - } - - 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. - * @param element - * @return the bytes resulting from the decryption - * @throws XMLEncryptionException - */ - public byte[] decryptToByteArray(Element element) throws XMLEncryptionException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Decrypting to ByteArray..."); - } - - 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)); - } - } - 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); - } - } - } - - 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 { - 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); - } - } - - /* - * Expose the interface for creating XML Encryption objects - */ - - /** - * Creates anEncryptedData
Element
. - * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *- * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. - * @param value the Base 64 encoded, encrypted text to wrap in the - *
EncryptedData
or the URI to set in the CipherReference - * (usage will depend on thetype
- * @return theEncryptedData
Element
. - * - * - * @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); - } - - return result; - } - - /** - * Creates anEncryptedKey
Element
. - * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *- * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. - * @param value the Base 64 encoded, encrypted text to wrap in the - *
EncryptedKey
or the URI to set in the CipherReference - * (usage will depend on thetype
- * @return theEncryptedKey
Element
. - * - * - * @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 a newAgreementMethod
- */ - 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 newCipherData
- */ - public CipherData createCipherData(int type) { - return factory.newCipherData(type); - } - - /** - * Create a CipherReference object - * - * @param uri The URI that the reference will refer - * @return a newCipherReference
- */ - public CipherReference createCipherReference(String uri) { - return factory.newCipherReference(uri); - } - - /** - * Create a CipherValue element - * - * @param value The value to set the ciphertext to - * @return a newCipherValue
- */ - public CipherValue createCipherValue(String value) { - return factory.newCipherValue(value); - } - - /** - * Create an EncryptionMethod object - * - * @param algorithm Algorithm for the encryption - * @return a newEncryptionMethod
- */ - public EncryptionMethod createEncryptionMethod(String algorithm) { - return factory.newEncryptionMethod(algorithm); - } - - /** - * Create an EncryptionProperties element - * @return a newEncryptionProperties
- */ - public EncryptionProperties createEncryptionProperties() { - return factory.newEncryptionProperties(); - } - - /** - * Create a new EncryptionProperty element - * @return a newEncryptionProperty
- */ - public EncryptionProperty createEncryptionProperty() { - return factory.newEncryptionProperty(); - } - - /** - * Create a new ReferenceList object - * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE - * @return a newReferenceList
- */ - public ReferenceList createReferenceList(int type) { - return factory.newReferenceList(type); - } - - /** - * Create a new Transforms object - *- * Note: A context document must have been set - * elsewhere (possibly via a call to doFinal). If not, use the - * createTransforms(Document) method. - * @return a new
Transforms
- */ - public Transforms createTransforms() { - return factory.newTransforms(); - } - - /** - * Create a new Transforms object - * - * Because the handling of Transforms is currently done in the signature - * code, the creation of a Transforms object requires a - * context document. - * - * @param doc Document that will own the created Transforms node - * @return a newTransforms
- */ - public Transforms createTransforms(Document doc) { - return factory.newTransforms(doc); - } - - /** - * - * @author Axl Mattheus - */ - private class Factory { - /** - * @param algorithm - * @return a new AgreementMethod - */ - AgreementMethod newAgreementMethod(String algorithm) { - return new AgreementMethodImpl(algorithm); - } - - /** - * @param type - * @return a new CipherData - * - */ - 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); - } - - /** - * @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(); - } - - /** - * @param doc - * @return a new Transforms - */ - Transforms newTransforms(Document doc) { - return new TransformsImpl(doc); - } - - /** - * @param element - * @return a new CipherData - * @throws XMLEncryptionException - */ - CipherData newCipherData(Element element) throws XMLEncryptionException { - if (null == element) { - throw new NullPointerException("element is null"); - } - - int type = 0; - Element e = null; - if (element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0 - ) { - type = CipherData.VALUE_TYPE; - e = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE).item(0); - } else if (element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERREFERENCE).getLength() > 0) { - type = CipherData.REFERENCE_TYPE; - e = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERREFERENCE).item(0); - } - - CipherData result = newCipherData(type); - if (type == CipherData.VALUE_TYPE) { - result.setCipherValue(newCipherValue(e)); - } else if (type == CipherData.REFERENCE_TYPE) { - result.setCipherReference(newCipherReference(e)); - } - - return result; - } - - /** - * @param element - * @return a new CipherReference - * @throws XMLEncryptionException - * - */ - CipherReference newCipherReference(Element element) throws XMLEncryptionException { - - Attr uriAttr = - element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); - CipherReference result = new CipherReferenceImpl(uriAttr); - - // 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 a new CipherValue - */ - CipherValue newCipherValue(Element element) { - String value = XMLUtils.getFullTextChildrenFromElement(element); - - return newCipherValue(value); - } - - /** - * @param element - * @return a new EncryptedData - * @throws XMLEncryptionException - * - */ - EncryptedData newEncryptedData(Element element) throws XMLEncryptionException { - EncryptedData result = null; - - 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 - - Element dataElement = - (Element) dataElements.item(dataElements.getLength() - 1); - - CipherData data = newCipherData(dataElement); - - 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)); - - Element encryptionMethodElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); - if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); - } - - // BFL 16/7/03 - simple implementation - // TODO: Work out how to handle relative URI - - Element keyInfoElement = - (Element) element.getElementsByTagNameNS( - Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); - if (null != keyInfoElement) { - KeyInfo ki = newKeyInfo(keyInfoElement); - result.setKeyInfo(ki); - } - - // TODO: Implement - Element encryptionPropertiesElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); - if (null != encryptionPropertiesElement) { - result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement) - ); - } - - return result; - } - - /** - * @param element - * @return a new EncryptedKey - * @throws XMLEncryptionException - */ - EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException { - EncryptedKey result = null; - 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)); - - Element encryptionMethodElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); - if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); - } - - Element keyInfoElement = - (Element) element.getElementsByTagNameNS( - Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); - if (null != keyInfoElement) { - KeyInfo ki = newKeyInfo(keyInfoElement); - result.setKeyInfo(ki); - } - - // TODO: Implement - Element encryptionPropertiesElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); - if (null != encryptionPropertiesElement) { - result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement) - ); - } - - Element referenceListElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_REFERENCELIST).item(0); - if (null != referenceListElement) { - result.setReferenceList(newReferenceList(referenceListElement)); - } - - Element carriedNameElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CARRIEDKEYNAME).item(0); - if (null != carriedNameElement) { - result.setCarriedName(carriedNameElement.getFirstChild().getNodeValue()); - } - - return result; - } - - /** - * @param element - * @return a new KeyInfo - * @throws XMLEncryptionException - */ - KeyInfo newKeyInfo(Element element) throws XMLEncryptionException { - try { - KeyInfo ki = new KeyInfo(element, null); - ki.setSecureValidation(secureValidation); - if (internalKeyResolvers != null) { - int size = internalKeyResolvers.size(); - for (int i = 0; i < size; i++) { - ki.registerInternalKeyResolver(internalKeyResolvers.get(i)); - } - } - return ki; - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("Error loading Key Info", xse); - } - } - - /** - * @param element - * @return a new EncryptionMethod - */ - EncryptionMethod newEncryptionMethod(Element element) { - String encAlgorithm = element.getAttributeNS(null, EncryptionConstants._ATT_ALGORITHM); - EncryptionMethod result = newEncryptionMethod(encAlgorithm); - - Element keySizeElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYSIZE).item(0); - if (null != keySizeElement) { - result.setKeySize( - Integer.valueOf( - keySizeElement.getFirstChild().getNodeValue()).intValue()); - } - - Element oaepParamsElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_OAEPPARAMS).item(0); - if (null != oaepParamsElement) { - try { - String oaepParams = oaepParamsElement.getFirstChild().getNodeValue(); - result.setOAEPparams(Base64.decode(oaepParams.getBytes("UTF-8"))); - } catch(UnsupportedEncodingException e) { - throw new RuntimeException("UTF-8 not supported", e); - } catch (Base64DecodingException e) { - throw new RuntimeException("BASE-64 decoding error", e); - } - } - - Element digestElement = - (Element) element.getElementsByTagNameNS( - Constants.SignatureSpecNS, Constants._TAG_DIGESTMETHOD).item(0); - if (digestElement != null) { - String digestAlgorithm = digestElement.getAttributeNS(null, "Algorithm"); - result.setDigestAlgorithm(digestAlgorithm); - } - - Element mgfElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpec11NS, EncryptionConstants._TAG_MGF).item(0); - if (mgfElement != null && !XMLCipher.RSA_OAEP.equals(algorithm)) { - String mgfAlgorithm = mgfElement.getAttributeNS(null, "Algorithm"); - result.setMGFAlgorithm(mgfAlgorithm); - } - - // TODO: Make this mess work - //- - return result; - } - - /** - * @param element - * @return a new EncryptionProperties - */ - EncryptionProperties newEncryptionProperties(Element element) { - EncryptionProperties result = newEncryptionProperties(); - - 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++) { - Node n = encryptionPropertyList.item(i); - if (null != n) { - result.addEncryptionProperty(newEncryptionProperty((Element) n)); - } - } - - return result; - } - - /** - * @param element - * @return a new EncryptionProperty - */ - EncryptionProperty newEncryptionProperty(Element element) { - EncryptionProperty result = newEncryptionProperty(); - - result.setTarget(element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); - result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); - // TODO: Make this lot work... - // - - // TODO: Make this work... - // - - return result; - } - - /** - * @param element - * @return a new ReferenceList - */ - ReferenceList newReferenceList(Element element) { - int type = 0; - if (null != element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_DATAREFERENCE).item(0)) { - type = ReferenceList.DATA_REFERENCE; - } else if (null != element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYREFERENCE).item(0)) { - type = ReferenceList.KEY_REFERENCE; - } - - ReferenceList result = new ReferenceListImpl(type); - NodeList list = null; - switch (type) { - case ReferenceList.DATA_REFERENCE: - 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); - for (int i = 0; i < list.getLength() ; i++) { - String uri = ((Element) list.item(i)).getAttribute("URI"); - result.add(result.newKeyReference(uri)); - } - } - - return result; - } - - /** - * @param encryptedData - * @return the XML Element form of that EncryptedData - */ - Element toElement(EncryptedData encryptedData) { - return ((EncryptedDataImpl) encryptedData).toElement(); - } - - /** - * @param encryptedKey - * @return the XML Element form of that EncryptedKey - */ - Element toElement(EncryptedKey encryptedKey) { - return ((EncryptedKeyImpl) encryptedKey).toElement(); - } - - /** - * @param referenceList - * @return the XML Element form of that ReferenceList - */ - Element toElement(ReferenceList referenceList) { - return ((ReferenceListImpl) referenceList).toElement(); - } - - private class AgreementMethodImpl implements AgreementMethod { - private byte[] kaNonce = null; - private List agreementMethodInformation = null; - private KeyInfo originatorKeyInfo = null; - private KeyInfo recipientKeyInfo = null; - private String algorithmURI = null; - - /** - * @param algorithm - */ - public AgreementMethodImpl(String algorithm) { - agreementMethodInformation = new LinkedList (); - URI tmpAlgorithm = null; - try { - tmpAlgorithm = new URI(algorithm); - } catch (URISyntaxException ex) { - throw (IllegalArgumentException) - new IllegalArgumentException().initCause(ex); - } - algorithmURI = tmpAlgorithm.toString(); - } - - /** @inheritDoc */ - public byte[] getKANonce() { - return kaNonce; - } - - /** @inheritDoc */ - public void setKANonce(byte[] kanonce) { - kaNonce = kanonce; - } - - /** @inheritDoc */ - public Iterator getAgreementMethodInformation() { - return agreementMethodInformation.iterator(); - } - - /** @inheritDoc */ - public void addAgreementMethodInformation(Element info) { - agreementMethodInformation.add(info); - } - - /** @inheritDoc */ - public void revoveAgreementMethodInformation(Element info) { - agreementMethodInformation.remove(info); - } - - /** @inheritDoc */ - public KeyInfo getOriginatorKeyInfo() { - return originatorKeyInfo; - } - - /** @inheritDoc */ - public void setOriginatorKeyInfo(KeyInfo keyInfo) { - originatorKeyInfo = keyInfo; - } - - /** @inheritDoc */ - public KeyInfo getRecipientKeyInfo() { - return recipientKeyInfo; - } - - /** @inheritDoc */ - public void setRecipientKeyInfo(KeyInfo keyInfo) { - recipientKeyInfo = keyInfo; - } - - /** @inheritDoc */ - public String getAlgorithm() { - return algorithmURI; - } - } - - private class CipherDataImpl implements CipherData { - private static final String valueMessage = - "Data type is reference type."; - private static final String referenceMessage = - "Data type is value type."; - private CipherValue cipherValue = null; - private CipherReference cipherReference = null; - private int cipherType = Integer.MIN_VALUE; - - /** - * @param type - */ - public CipherDataImpl(int type) { - cipherType = type; - } - - /** @inheritDoc */ - public CipherValue getCipherValue() { - return cipherValue; - } - - /** @inheritDoc */ - public void setCipherValue(CipherValue value) throws XMLEncryptionException { - - if (cipherType == REFERENCE_TYPE) { - throw new XMLEncryptionException( - "empty", new UnsupportedOperationException(valueMessage) - ); - } - - cipherValue = value; - } - - /** @inheritDoc */ - public CipherReference getCipherReference() { - return cipherReference; - } - - /** @inheritDoc */ - public void setCipherReference(CipherReference reference) throws - XMLEncryptionException { - if (cipherType == VALUE_TYPE) { - throw new XMLEncryptionException( - "empty", new UnsupportedOperationException(referenceMessage) - ); - } - - cipherReference = reference; - } - - /** @inheritDoc */ - public int getDataType() { - return cipherType; - } - - Element toElement() { - Element result = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_CIPHERDATA - ); - if (cipherType == VALUE_TYPE) { - result.appendChild(((CipherValueImpl) cipherValue).toElement()); - } else if (cipherType == REFERENCE_TYPE) { - result.appendChild(((CipherReferenceImpl) cipherReference).toElement()); - } - - return result; - } - } - - private class CipherReferenceImpl implements CipherReference { - private String referenceURI = null; - private Transforms referenceTransforms = null; - private Attr referenceNode = null; - - /** - * @param uri - */ - public CipherReferenceImpl(String uri) { - /* Don't check validity of URI as may be "" */ - referenceURI = uri; - referenceNode = null; - } - - /** - * @param uri - */ - public CipherReferenceImpl(Attr uri) { - referenceURI = uri.getNodeValue(); - referenceNode = uri; - } - - /** @inheritDoc */ - public String getURI() { - return referenceURI; - } - - /** @inheritDoc */ - public Attr getURIAsAttr() { - return referenceNode; - } - - /** @inheritDoc */ - public Transforms getTransforms() { - return referenceTransforms; - } - - /** @inheritDoc */ - public void setTransforms(Transforms transforms) { - referenceTransforms = transforms; - } - - Element toElement() { - Element result = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE - ); - result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI); - if (null != referenceTransforms) { - result.appendChild(((TransformsImpl) referenceTransforms).toElement()); - } - - return result; - } - } - - private class CipherValueImpl implements CipherValue { - private String cipherValue = null; - - /** - * @param value - */ - public CipherValueImpl(String value) { - cipherValue = value; - } - - /** @inheritDoc */ - public String getValue() { - return cipherValue; - } - - /** @inheritDoc */ - public void setValue(String value) { - cipherValue = value; - } - - Element toElement() { - Element result = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_CIPHERVALUE - ); - result.appendChild(contextDocument.createTextNode(cipherValue)); - - return result; - } - } - - private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData { - - /** - * @param data - */ - public EncryptedDataImpl(CipherData data) { - super(data); - } - - Element toElement() { - Element result = - ElementProxy.createElementForFamily( - contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA - ); - - if (null != super.getId()) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); - } - if (null != super.getType()) { - result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); - } - if (null != super.getMimeType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() - ); - } - if (null != super.getEncoding()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ENCODING, super.getEncoding() - ); - } - if (null != super.getEncryptionMethod()) { - result.appendChild( - ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement() - ); - } - if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); - } - - result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); - if (null != super.getEncryptionProperties()) { - result.appendChild(((EncryptionPropertiesImpl) - super.getEncryptionProperties()).toElement()); - } - - return result; - } - } - - private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey { - private String keyRecipient = null; - private ReferenceList referenceList = null; - private String carriedName = null; - - /** - * @param data - */ - public EncryptedKeyImpl(CipherData data) { - super(data); - } - - /** @inheritDoc */ - public String getRecipient() { - return keyRecipient; - } - - /** @inheritDoc */ - public void setRecipient(String recipient) { - keyRecipient = recipient; - } - - /** @inheritDoc */ - public ReferenceList getReferenceList() { - return referenceList; - } - - /** @inheritDoc */ - public void setReferenceList(ReferenceList list) { - referenceList = list; - } - - /** @inheritDoc */ - public String getCarriedName() { - return carriedName; - } - - /** @inheritDoc */ - public void setCarriedName(String name) { - carriedName = name; - } - - Element toElement() { - Element result = - ElementProxy.createElementForFamily( - contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDKEY - ); - - if (null != super.getId()) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); - } - if (null != super.getType()) { - result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); - } - if (null != super.getMimeType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() - ); - } - if (null != super.getEncoding()) { - result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding()); - } - if (null != 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().cloneNode(true)); - } - 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()); - } - if (null != carriedName) { - Element element = - ElementProxy.createElementForFamily( - contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CARRIEDKEYNAME - ); - Node node = contextDocument.createTextNode(carriedName); - element.appendChild(node); - result.appendChild(element); - } - - return result; - } - } - - private abstract class EncryptedTypeImpl { - private String id = null; - private String type = null; - private String mimeType = null; - private String encoding = null; - private EncryptionMethod encryptionMethod = null; - private KeyInfo keyInfo = null; - private CipherData cipherData = null; - private EncryptionProperties encryptionProperties = null; - - /** - * Constructor. - * @param data - */ - protected EncryptedTypeImpl(CipherData data) { - cipherData = data; - } - - /** - * - * @return the Id - */ - public String getId() { - return id; - } - - /** - * - * @param id - */ - public void setId(String id) { - this.id = id; - } - - /** - * - * @return the type - */ - public String getType() { - return type; - } - - /** - * - * @param type - */ - public void setType(String type) { - if (type == null || type.length() == 0) { - this.type = null; - } else { - URI tmpType = null; - try { - tmpType = new URI(type); - } catch (URISyntaxException ex) { - throw (IllegalArgumentException) - new IllegalArgumentException().initCause(ex); - } - this.type = tmpType.toString(); - } - } - - /** - * - * @return the MimeType - */ - public String getMimeType() { - return mimeType; - } - /** - * - * @param type - */ - public void setMimeType(String type) { - mimeType = type; - } - - /** - * - * @return the encoding - */ - public String getEncoding() { - return encoding; - } - - /** - * - * @param encoding - */ - public void setEncoding(String encoding) { - if (encoding == null || encoding.length() == 0) { - this.encoding = null; - } else { - URI tmpEncoding = null; - try { - tmpEncoding = new URI(encoding); - } catch (URISyntaxException ex) { - throw (IllegalArgumentException) - new IllegalArgumentException().initCause(ex); - } - this.encoding = tmpEncoding.toString(); - } - } - - /** - * - * @return the EncryptionMethod - */ - public EncryptionMethod getEncryptionMethod() { - return encryptionMethod; - } - - /** - * - * @param method - */ - public void setEncryptionMethod(EncryptionMethod method) { - encryptionMethod = method; - } - - /** - * - * @return the KeyInfo - */ - public KeyInfo getKeyInfo() { - return keyInfo; - } - - /** - * - * @param info - */ - public void setKeyInfo(KeyInfo info) { - keyInfo = info; - } - - /** - * - * @return the CipherData - */ - public CipherData getCipherData() { - return cipherData; - } - - /** - * - * @return the EncryptionProperties - */ - public EncryptionProperties getEncryptionProperties() { - return encryptionProperties; - } - - /** - * - * @param properties - */ - public void setEncryptionProperties(EncryptionProperties properties) { - encryptionProperties = properties; - } - } - - private class EncryptionMethodImpl implements EncryptionMethod { - private String algorithm = null; - private int keySize = Integer.MIN_VALUE; - private byte[] oaepParams = null; - private List encryptionMethodInformation = null; - private String digestAlgorithm = null; - private String mgfAlgorithm = null; - - /** - * Constructor. - * @param algorithm - */ - public EncryptionMethodImpl(String algorithm) { - URI tmpAlgorithm = null; - try { - tmpAlgorithm = new URI(algorithm); - } catch (URISyntaxException ex) { - throw (IllegalArgumentException) - new IllegalArgumentException().initCause(ex); - } - this.algorithm = tmpAlgorithm.toString(); - encryptionMethodInformation = new LinkedList (); - } - - /** @inheritDoc */ - public String getAlgorithm() { - return algorithm; - } - - /** @inheritDoc */ - public int getKeySize() { - return keySize; - } - - /** @inheritDoc */ - public void setKeySize(int size) { - keySize = size; - } - - /** @inheritDoc */ - public byte[] getOAEPparams() { - return oaepParams; - } - - /** @inheritDoc */ - public void setOAEPparams(byte[] params) { - oaepParams = params; - } - - /** @inheritDoc */ - public void setDigestAlgorithm(String digestAlgorithm) { - this.digestAlgorithm = digestAlgorithm; - } - - /** @inheritDoc */ - public String getDigestAlgorithm() { - return digestAlgorithm; - } - - /** @inheritDoc */ - public void setMGFAlgorithm(String mgfAlgorithm) { - this.mgfAlgorithm = mgfAlgorithm; - } - - /** @inheritDoc */ - public String getMGFAlgorithm() { - return mgfAlgorithm; - } - - /** @inheritDoc */ - public Iterator getEncryptionMethodInformation() { - return encryptionMethodInformation.iterator(); - } - - /** @inheritDoc */ - public void addEncryptionMethodInformation(Element info) { - encryptionMethodInformation.add(info); - } - - /** @inheritDoc */ - public void removeEncryptionMethodInformation(Element info) { - encryptionMethodInformation.remove(info); - } - - Element toElement() { - Element result = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD - ); - result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm); - if (keySize > 0) { - result.appendChild( - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_KEYSIZE - ).appendChild(contextDocument.createTextNode(String.valueOf(keySize)))); - } - if (null != oaepParams) { - Element oaepElement = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_OAEPPARAMS - ); - oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams))); - result.appendChild(oaepElement); - } - if (digestAlgorithm != null) { - Element digestElement = - XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD); - digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm); - result.appendChild(digestElement); - } - if (mgfAlgorithm != null) { - Element mgfElement = - XMLUtils.createElementInEncryption11Space( - contextDocument, EncryptionConstants._TAG_MGF - ); - mgfElement.setAttributeNS(null, "Algorithm", mgfAlgorithm); - mgfElement.setAttributeNS( - Constants.NamespaceSpecNS, - "xmlns:" + ElementProxy.getDefaultPrefix(EncryptionConstants.EncryptionSpec11NS), - EncryptionConstants.EncryptionSpec11NS - ); - result.appendChild(mgfElement); - } - Iterator itr = encryptionMethodInformation.iterator(); - while (itr.hasNext()) { - result.appendChild(itr.next()); - } - - return result; - } - } - - private class EncryptionPropertiesImpl implements EncryptionProperties { - private String id = null; - private List encryptionProperties = null; - - /** - * Constructor. - */ - public EncryptionPropertiesImpl() { - encryptionProperties = new LinkedList (); - } - - /** @inheritDoc */ - public String getId() { - return id; - } - - /** @inheritDoc */ - public void setId(String id) { - this.id = id; - } - - /** @inheritDoc */ - public Iterator getEncryptionProperties() { - return encryptionProperties.iterator(); - } - - /** @inheritDoc */ - public void addEncryptionProperty(EncryptionProperty property) { - encryptionProperties.add(property); - } - - /** @inheritDoc */ - public void removeEncryptionProperty(EncryptionProperty property) { - encryptionProperties.remove(property); - } - - Element toElement() { - Element result = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTIES - ); - if (null != id) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); - } - Iterator itr = getEncryptionProperties(); - while (itr.hasNext()) { - result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement()); - } - - return result; - } - } - - private class EncryptionPropertyImpl implements EncryptionProperty { - private String target = null; - private String id = null; - private Map attributeMap = new HashMap (); - private List encryptionInformation = null; - - /** - * Constructor. - */ - public EncryptionPropertyImpl() { - encryptionInformation = new LinkedList (); - } - - /** @inheritDoc */ - public String getTarget() { - return target; - } - - /** @inheritDoc */ - public void setTarget(String target) { - if (target == null || target.length() == 0) { - this.target = null; - } else if (target.startsWith("#")) { - /* - * This is a same document URI reference. Do not parse, - * because it has no scheme. - */ - this.target = target; - } else { - URI tmpTarget = null; - try { - tmpTarget = new URI(target); - } catch (URISyntaxException ex) { - throw (IllegalArgumentException) - new IllegalArgumentException().initCause(ex); - } - this.target = tmpTarget.toString(); - } - } - - /** @inheritDoc */ - public String getId() { - return id; - } - - /** @inheritDoc */ - public void setId(String id) { - this.id = id; - } - - /** @inheritDoc */ - public String getAttribute(String attribute) { - return attributeMap.get(attribute); - } - - /** @inheritDoc */ - public void setAttribute(String attribute, String value) { - attributeMap.put(attribute, value); - } - - /** @inheritDoc */ - public Iterator getEncryptionInformation() { - return encryptionInformation.iterator(); - } - - /** @inheritDoc */ - public void addEncryptionInformation(Element info) { - encryptionInformation.add(info); - } - - /** @inheritDoc */ - public void removeEncryptionInformation(Element info) { - encryptionInformation.remove(info); - } - - Element toElement() { - Element result = - XMLUtils.createElementInEncryptionSpace( - contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTY - ); - if (null != target) { - result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, target); - } - if (null != id) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); - } - // TODO: figure out the anyAttribyte stuff... - // TODO: figure out the any stuff... - - return result; - } - } - - 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, ""); - } - - /** - * - * @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 - /** @inheritDoc */ - public String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } - } - - private class ReferenceListImpl implements ReferenceList { - private Class> sentry; - private List references; - - /** - * Constructor. - * @param type - */ - public ReferenceListImpl(int type) { - if (type == ReferenceList.DATA_REFERENCE) { - sentry = DataReference.class; - } else if (type == ReferenceList.KEY_REFERENCE) { - sentry = KeyReference.class; - } else { - throw new IllegalArgumentException(); - } - references = new LinkedList (); - } - - /** @inheritDoc */ - public void add(Reference reference) { - if (!reference.getClass().equals(sentry)) { - throw new IllegalArgumentException(); - } - references.add(reference); - } - - /** @inheritDoc */ - public void remove(Reference reference) { - if (!reference.getClass().equals(sentry)) { - throw new IllegalArgumentException(); - } - references.remove(reference); - } - - /** @inheritDoc */ - public int size() { - return references.size(); - } - - /** @inheritDoc */ - public boolean isEmpty() { - return references.isEmpty(); - } - - /** @inheritDoc */ - public Iterator getReferences() { - return references.iterator(); - } - - Element toElement() { - Element result = - ElementProxy.createElementForFamily( - contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_REFERENCELIST - ); - Iterator eachReference = references.iterator(); - while (eachReference.hasNext()) { - Reference reference = eachReference.next(); - result.appendChild(((ReferenceImpl) reference).toElement()); - } - return result; - } - - /** @inheritDoc */ - public Reference newDataReference(String uri) { - return new DataReference(uri); - } - - /** @inheritDoc */ - public Reference newKeyReference(String uri) { - return new KeyReference(uri); - } - - /** - * ReferenceImpl
is an implementation of - *Reference
. - * - * @see Reference - */ - private abstract class ReferenceImpl implements Reference { - private String uri; - private ListreferenceInformation; - - ReferenceImpl(String uri) { - this.uri = uri; - referenceInformation = new LinkedList (); - } - - /** @inheritDoc */ - public abstract String getType(); - - /** @inheritDoc */ - public String getURI() { - return uri; - } - - /** @inheritDoc */ - public Iterator getElementRetrievalInformation() { - return referenceInformation.iterator(); - } - - /** @inheritDoc */ - 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 the XML Element form of that Reference - */ - public Element toElement() { - String tagName = getType(); - Element result = - ElementProxy.createElementForFamily( - contextDocument, - EncryptionConstants.EncryptionSpecNS, - tagName - ); - result.setAttribute(EncryptionConstants._ATT_URI, uri); - - // TODO: Need to martial referenceInformation - // Figure out how to make this work.. - // - - return result; - } - } - - private class DataReference extends ReferenceImpl { - - DataReference(String uri) { - super(uri); - } - - /** @inheritDoc */ - public String getType() { - return EncryptionConstants._TAG_DATAREFERENCE; - } - } - - private class KeyReference extends ReferenceImpl { - - KeyReference(String uri) { - super(uri); - } - - /** @inheritDoc */ - public String getType() { - return EncryptionConstants._TAG_KEYREFERENCE; - } - } - } - } -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import java.io.IOException; - -import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; -import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; -import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; -import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; -import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; -import com.sun.org.apache.xml.internal.security.transforms.TransformationException; -import org.w3c.dom.Attr; -import com.sun.org.apache.xml.internal.security.utils.Base64; - -/** - * XMLCipherInput
is used to wrap input passed into the - * XMLCipher encryption operations. - * - * In decryption mode, it takes aCipherData
object and allows - * callers to dereference the CipherData into the encrypted bytes that it - * actually represents. This takes care of all base64 encoding etc. - * - * While primarily an internal class, this can be used by applications to - * quickly and easily retrieve the encrypted bytes from an EncryptedType - * object - * - * @author Berin Lautenbach - */ -public class XMLCipherInput { - - private static java.util.logging.Logger logger = - java.util.logging.Logger.getLogger(XMLCipherInput.class.getName()); - - /** The data we are working with */ - private CipherData cipherData; - - /** MODES */ - private int mode; - - private boolean secureValidation; - - /** - * Constructor for processing encrypted octets - * - * @param data TheCipherData
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 TheEncryptedType
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 - * @return The decripted bytes. - */ - public byte[] getBytes() throws XMLEncryptionException { - if (mode == XMLCipher.DECRYPT_MODE) { - return getDecryptBytes(); - } - return null; - } - - /** - * Internal method to get bytes in decryption mode - * @return the decrypted bytes - * @throws XMLEncryptionException - */ - private byte[] getDecryptBytes() throws XMLEncryptionException { - String base64EncodedEncryptedOctets = null; - - if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) { - // Fun time! - 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 - - Attr uriAttr = cr.getURIAsAttr(); - XMLSignatureInput input = null; - - try { - ResourceResolver resolver = - ResourceResolver.getInstance(uriAttr, null, secureValidation); - input = resolver.resolve(uriAttr, null, secureValidation); - } catch (ResourceResolverException ex) { - throw new XMLEncryptionException("empty", ex); - } - - if (input != null) { - if (logger.isLoggable(java.util.logging.Level.FINE)) { - logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); - } - } else { - 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) { - 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); - } - } - - try { - return input.getBytes(); - } catch (IOException ex) { - throw new XMLEncryptionException("empty", ex); - } catch (CanonicalizationException ex) { - throw new XMLEncryptionException("empty", ex); - } - - // retrieve the cipher text - } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) { - base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue(); - } else { - throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); - } - - if (logger.isLoggable(java.util.logging.Level.FINE)) { - logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); - } - - try { - return Base64.decode(base64EncodedEncryptedOctets); - } catch (Base64DecodingException bde) { - throw new XMLEncryptionException("empty", bde); - } - } -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -/** - * Constants - */ -public interface XMLCipherParameters { - - String AES_128 = - "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; - - String AES_256 = - "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; - - String AES_192 = - "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; - - String RSA_1_5 = - "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; - - String RSA_OAEP = - "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; - - String DIFFIE_HELLMAN = - "http://www.w3.org/2001/04/xmlenc#dh"; - - String TRIPLEDES_KEYWRAP = - "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; - - String AES_128_KEYWRAP = - "http://www.w3.org/2001/04/xmlenc#kw-aes128"; - - String AES_256_KEYWRAP = - "http://www.w3.org/2001/04/xmlenc#kw-aes256"; - - String AES_192_KEYWRAP = - "http://www.w3.org/2001/04/xmlenc#kw-aes192"; - - String SHA1 = - "http://www.w3.org/2000/09/xmldsig#sha1"; - - String SHA256 = - "http://www.w3.org/2001/04/xmlenc#sha256"; - - String SHA512 = - "http://www.w3.org/2001/04/xmlenc#sha512"; - - String RIPEMD_160 = - "http://www.w3.org/2001/04/xmlenc#ripemd160"; - - String XML_DSIG = - "http://www.w3.org/2000/09/xmldsig#"; - - String N14C_XML = - "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; - - String N14C_XML_CMMNTS = - "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - - String EXCL_XML_N14C = - "http://www.w3.org/2001/10/xml-exc-c14n#"; - - String EXCL_XML_N14C_CMMNTS = - "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package com.sun.org.apache.xml.internal.security.encryption; - -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - */ -public class XMLEncryptionException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * - * - */ - public XMLEncryptionException() { - super(); - } - - /** - * - * @param msgID - */ - public XMLEncryptionException(String msgID) { - super(msgID); - } - - /** - * - * @param msgID - * @param exArgs - */ - public XMLEncryptionException(String msgID, Object exArgs[]) { - super(msgID, exArgs); - } - - /** - * - * @param msgID - * @param originalException - */ - public XMLEncryptionException(String msgID, Exception originalException) { - super(msgID, originalException); - - } - - /** - * - * @param msgID - * @param exArgs - * @param originalException - */ - public XMLEncryptionException(String msgID, Object exArgs[], Exception originalException) { - super(msgID, exArgs, originalException); - } -} diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/package.html +++ /dev/null @@ -1,25 +0,0 @@ - - - -- - -Provides classes for implementing XML Encryption applications. There are two -main families of classes in this package. The first group of classes is an -XML Schema to Java mapping of the complex types and elements of the -XML Encryption Schema as outllined at XML Encrtypyion -Specification. The second group of classes are used to perform encryption -operations, and to manipulate the first group of classes. The most important -classes in this second group is XMLCipher
, -XMLEncryptionFactory
-andXMLSerializer
.XMLCipher
was designed to resemble -javax.crypto.Cipher
. The aforementioned classes were desinged -with ease-of-use and configurability in mind. Becuase of this, the programmer -may at times be exposed to lower level programming tasks. This library strives -to be as simple as possible to use, but no simpler.
-
- - diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java @@ -58,24 +58,34 @@ /** * Constructor AlgorithmAlreadyRegisteredException * + * @param originalException * @param msgID - * @param originalException */ + public AlgorithmAlreadyRegisteredException(Exception originalException, String msgID) { + super(originalException, msgID); + } + + @Deprecated public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) { - super(msgID, originalException); + this(originalException, msgID); } /** * Constructor AlgorithmAlreadyRegisteredException * + * @param originalException * @param msgID * @param exArgs - * @param originalException */ public AlgorithmAlreadyRegisteredException( - String msgID, Object exArgs[], Exception originalException + Exception originalException, String msgID, Object exArgs[] ) { - super(msgID, exArgs, originalException); + super(originalException, msgID, exArgs); + } + + @Deprecated + public AlgorithmAlreadyRegisteredException(String msgID, Object[] exArgs, Exception originalException) { + this(originalException, msgID, exArgs); } } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java @@ -25,7 +25,6 @@ /** * This Exception is thrown if decoding of Base64 data fails. * - * @author Christian Geuer-Pollmann */ public class Base64DecodingException extends XMLSecurityException { @@ -61,22 +60,32 @@ /** * Constructor Base64DecodingException * + * @param originalException * @param msgID - * @param originalException */ + public Base64DecodingException(Exception originalException, String msgID) { + super(originalException, msgID); + } + + @Deprecated public Base64DecodingException(String msgID, Exception originalException) { - super(msgID, originalException); + this(originalException, msgID); } /** * Constructor Base64DecodingException * + * @param originalException * @param msgID * @param exArgs - * @param originalException */ - public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) { - super(msgID, exArgs, originalException); + public Base64DecodingException(Exception originalException, String msgID, Object exArgs[]) { + super(originalException, msgID, exArgs); + } + + @Deprecated + public Base64DecodingException(String msgID, Object[] exArgs, Exception originalException) { + this(originalException, msgID, exArgs); } } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java @@ -22,18 +22,15 @@ */ package com.sun.org.apache.xml.internal.security.exceptions; -import java.io.PrintStream; -import java.io.PrintWriter; import java.text.MessageFormat; -import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; /** * The mother of all Exceptions in this bundle. It allows exceptions to have * their messages translated to the different locales. * - * Thexmlsecurity_en.properties
file contains this line: + * The {@code xmlsecurity_en.properties} file contains this line: ** xml.WrongElement = Can't create a {0} from a {1} element *@@ -47,7 +44,7 @@ * } ** try { * ... @@ -59,7 +56,6 @@ ** * - * @author Christian Geuer-Pollmann */ public class XMLSecurityException extends Exception { @@ -98,7 +94,7 @@ * @param msgID * @param exArgs */ - public XMLSecurityException(String msgID, Object exArgs[]) { + public XMLSecurityException(String msgID, Object[] exArgs) { super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); @@ -112,11 +108,7 @@ */ public XMLSecurityException(Exception originalException) { - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + originalException.getClass().getName() + " and message " - + originalException.getMessage(), originalException); + super(originalException.getMessage(), originalException); } /** @@ -125,12 +117,17 @@ * @param msgID * @param originalException */ - public XMLSecurityException(String msgID, Exception originalException) { + public XMLSecurityException(Exception originalException, String msgID) { super(I18n.getExceptionMessage(msgID, originalException), originalException); this.msgID = msgID; } + @Deprecated + public XMLSecurityException(String msgID, Exception originalException) { + this(originalException, msgID); + } + /** * Constructor XMLSecurityException * @@ -138,12 +135,18 @@ * @param exArgs * @param originalException */ - public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) { + public XMLSecurityException(Exception originalException, String msgID, Object[] exArgs) { super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); this.msgID = msgID; } + @Deprecated + public XMLSecurityException(String msgID, Object[] exArgs, Exception originalException) { + this(originalException, msgID, exArgs); + } + + /** * Method getMsgID * @@ -156,7 +159,7 @@ return msgID; } - /** @inheritDoc */ + /** {@inheritDoc} */ public String toString() { String s = this.getClass().getName(); String message = super.getLocalizedMessage(); @@ -185,24 +188,6 @@ } /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - super.printStackTrace(printwriter); - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - super.printStackTrace(printstream); - } - - /** * Method getOriginalException * * @return the original exception diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java @@ -22,8 +22,6 @@ */ package com.sun.org.apache.xml.internal.security.exceptions; -import java.io.PrintStream; -import java.io.PrintWriter; import java.text.MessageFormat; import com.sun.org.apache.xml.internal.security.utils.Constants; @@ -33,7 +31,7 @@ * The mother of all runtime Exceptions in this bundle. It allows exceptions to have * their messages translated to the different locales. * - * Thexmlsecurity_en.properties
file contains this line: + * The {@code xmlsecurity_en.properties} file contains this line: ** xml.WrongElement = Can't create a {0} from a {1} element *@@ -47,7 +45,7 @@ * } *
* try { * ... @@ -59,7 +57,6 @@ ** * - * @author Christian Geuer-Pollmann */ public class XMLSecurityRuntimeException extends RuntimeException { @@ -134,7 +131,7 @@ * @param originalException */ public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) { - super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); this.msgID = msgID; } @@ -151,7 +148,7 @@ return msgID; } - /** @inheritDoc */ + /** {@inheritDoc} */ public String toString() { String s = this.getClass().getName(); String message = super.getLocalizedMessage(); @@ -170,34 +167,6 @@ } /** - * Method printStackTrace - * - */ - public void printStackTrace() { - synchronized (System.err) { - super.printStackTrace(System.err); - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - super.printStackTrace(printwriter); - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - super.printStackTrace(printstream); - } - - /** * Method getOriginalException * * @return the original exception diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/package.html +++ /dev/null @@ -1,3 +0,0 @@ -
-general exceptions used by this library. -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java @@ -61,24 +61,34 @@ /** * Constructor ContentHandlerAlreadyRegisteredException * + * @param originalException * @param msgID - * @param originalException */ + public ContentHandlerAlreadyRegisteredException(Exception originalException, String msgID) { + super(originalException, msgID); + } + + @Deprecated public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) { - super(msgID, originalException); + this(originalException, msgID); } /** * Constructor ContentHandlerAlreadyRegisteredException * + * @param originalException * @param msgID * @param exArgs - * @param originalException */ public ContentHandlerAlreadyRegisteredException( - String msgID, Object exArgs[], Exception originalException + Exception originalException, String msgID, Object exArgs[] ) { - super(msgID, exArgs, originalException); + super(originalException, msgID, exArgs); + } + + @Deprecated + public ContentHandlerAlreadyRegisteredException(String msgID, Object[] exArgs, Exception originalException) { + this(originalException, msgID, exArgs); } } diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java @@ -31,9 +31,6 @@ 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.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; @@ -52,6 +49,7 @@ 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.ElementProxy; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; @@ -59,55 +57,52 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; -import org.w3c.dom.NodeList; /** * This class stand for KeyInfo Element that may contain keys, names, * certificates and other public key management information, * such as in-band key distribution or key agreement data. - *lengthXXX()
methods provide access to the internal Key
+ *
+ * The {@code lengthXXX()} methods provide access to the internal Key
* objects:
* KeyInfo
was constructed from an Element
- * (Signature verification), the lengthXXX()
methods searches
- * for child elements of ds:KeyInfo
for known types. KeyInfo
was constructed from scratch (during
- * Signature generation), the lengthXXX()
methods return the number
- * of XXXs
objects already passed to the KeyInfoaddXXX()
methods are used for adding Objects of the
- * appropriate type to the KeyInfo
. This is used during signature
+ *
+ * The {@code addXXX()} methods are used for adding Objects of the
+ * appropriate type to the {@code KeyInfo}. This is used during signature
* generation.
- * itemXXX(int i)
methods return the i'th object of the
+ *
+ * The {@code itemXXX(int i)} methods return the i'th object of the
* corresponding type.
- * containsXXX()
methods return whether the KeyInfo
+ *
+ * The {@code containsXXX()} methods return whether the KeyInfo
* contains the corresponding type.
*
*/
public class KeyInfo extends SignatureElementProxy {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(KeyInfo.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyInfo.class);
// We need at least one StorageResolver otherwise
// the KeyResolvers would not be called.
// The default StorageResolver is null.
- private ListId
attribute
+ * Sets the {@code Id} attribute
*
- * @param Id ID
+ * @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);
+ setLocalIdAttribute(Constants._ATT_ID, id);
}
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute
+ * @return the {@code Id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
@@ -182,7 +182,7 @@
* @param keynameString
*/
public void addKeyName(String keynameString) {
- this.add(new KeyName(this.doc, keynameString));
+ this.add(new KeyName(getDocument(), keynameString));
}
/**
@@ -191,8 +191,8 @@
* @param keyname
*/
public void add(KeyName keyname) {
- this.constructionElement.appendChild(keyname.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(keyname);
+ addReturnToSelf();
}
/**
@@ -201,7 +201,7 @@
* @param pk
*/
public void addKeyValue(PublicKey pk) {
- this.add(new KeyValue(this.doc, pk));
+ this.add(new KeyValue(getDocument(), pk));
}
/**
@@ -210,7 +210,7 @@
* @param unknownKeyValueElement
*/
public void addKeyValue(Element unknownKeyValueElement) {
- this.add(new KeyValue(this.doc, unknownKeyValueElement));
+ this.add(new KeyValue(getDocument(), unknownKeyValueElement));
}
/**
@@ -219,7 +219,7 @@
* @param dsakeyvalue
*/
public void add(DSAKeyValue dsakeyvalue) {
- this.add(new KeyValue(this.doc, dsakeyvalue));
+ this.add(new KeyValue(getDocument(), dsakeyvalue));
}
/**
@@ -228,7 +228,7 @@
* @param rsakeyvalue
*/
public void add(RSAKeyValue rsakeyvalue) {
- this.add(new KeyValue(this.doc, rsakeyvalue));
+ this.add(new KeyValue(getDocument(), rsakeyvalue));
}
/**
@@ -237,7 +237,7 @@
* @param pk
*/
public void add(PublicKey pk) {
- this.add(new KeyValue(this.doc, pk));
+ this.add(new KeyValue(getDocument(), pk));
}
/**
@@ -246,8 +246,8 @@
* @param keyvalue
*/
public void add(KeyValue keyvalue) {
- this.constructionElement.appendChild(keyvalue.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(keyvalue);
+ addReturnToSelf();
}
/**
@@ -256,7 +256,7 @@
* @param mgmtdata
*/
public void addMgmtData(String mgmtdata) {
- this.add(new MgmtData(this.doc, mgmtdata));
+ this.add(new MgmtData(getDocument(), mgmtdata));
}
/**
@@ -265,8 +265,8 @@
* @param mgmtdata
*/
public void add(MgmtData mgmtdata) {
- this.constructionElement.appendChild(mgmtdata.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(mgmtdata);
+ addReturnToSelf();
}
/**
@@ -275,8 +275,8 @@
* @param pgpdata
*/
public void add(PGPData pgpdata) {
- this.constructionElement.appendChild(pgpdata.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(pgpdata);
+ addReturnToSelf();
}
/**
@@ -287,7 +287,7 @@
* @param Type
*/
public void addRetrievalMethod(String uri, Transforms transforms, String Type) {
- this.add(new RetrievalMethod(this.doc, uri, transforms, Type));
+ this.add(new RetrievalMethod(getDocument(), uri, transforms, Type));
}
/**
@@ -296,8 +296,8 @@
* @param retrievalmethod
*/
public void add(RetrievalMethod retrievalmethod) {
- this.constructionElement.appendChild(retrievalmethod.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(retrievalmethod);
+ addReturnToSelf();
}
/**
@@ -306,8 +306,8 @@
* @param spkidata
*/
public void add(SPKIData spkidata) {
- this.constructionElement.appendChild(spkidata.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(spkidata);
+ addReturnToSelf();
}
/**
@@ -317,27 +317,11 @@
*/
public void add(X509Data x509data) {
if (x509Datas == null) {
- x509Datas = new ArrayListcom.sun.org.apache.xml.internal.security.keys
package.
+ * Utility class for {@code com.sun.org.apache.xml.internal.security.keys} package.
*
- * @author $Author: coheigea $
*/
-public class KeyUtils {
+public final class KeyUtils {
private KeyUtils() {
// no instantiation
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java
@@ -35,9 +35,8 @@
import org.w3c.dom.Element;
/**
- * Provides content model support for the dsig11:DEREncodedKeyvalue
element.
+ * Provides content model support for the {@code dsig11:DEREncodedKeyvalue} element.
*
- * @author Brent Putman (putmanb@georgetown.edu)
*/
public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent {
@@ -48,11 +47,11 @@
* Constructor DEREncodedKeyValue
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public DEREncodedKeyValue(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public DEREncodedKeyValue(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
@@ -72,7 +71,7 @@
* Constructor DEREncodedKeyValue
*
* @param doc
- * @param base64EncodedKey
+ * @param encodedKey
*/
public DEREncodedKeyValue(Document doc, byte[] encodedKey) {
super(doc);
@@ -81,29 +80,24 @@
}
/**
- * Sets the Id
attribute
+ * Sets the {@code Id} attribute
*
- * @param Id ID
+ * @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);
- }
+ setLocalIdAttribute(Constants._ATT_ID, id);
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute
+ * @return the {@code Id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_DERENCODEDKEYVALUE;
}
@@ -126,9 +120,9 @@
if (publicKey != null) {
return publicKey;
}
- } catch (NoSuchAlgorithmException e) {
+ } catch (NoSuchAlgorithmException e) { //NOPMD
// Do nothing, try the next type
- } catch (InvalidKeySpecException e) {
+ } catch (InvalidKeySpecException e) { //NOPMD
// Do nothing, try the next type
}
}
@@ -148,10 +142,10 @@
return keySpec.getEncoded();
} catch (NoSuchAlgorithmException e) {
Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
- throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e);
+ throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
} catch (InvalidKeySpecException e) {
Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() };
- throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e);
+ throw new XMLSecurityException(e, "DEREncodedKeyValue.UnsupportedPublicKey", exArgs);
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java
@@ -25,7 +25,6 @@
/**
* Empty interface just to identify Elements that can be children of ds:KeyInfo.
*
- * @author $Author: coheigea $
*/
public interface KeyInfoContent {
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java
@@ -30,9 +30,8 @@
import org.w3c.dom.Element;
/**
- * Provides content model support for the dsig11:KeyInfoReference
element.
+ * Provides content model support for the {@code dsig11:KeyInfoReference} element.
*
- * @author Brent Putman (putmanb@georgetown.edu)
*/
public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent {
@@ -40,7 +39,7 @@
* Constructor RetrievalMethod
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException {
@@ -51,12 +50,12 @@
* Constructor RetrievalMethod
*
* @param doc
- * @param URI
+ * @param uri
*/
- public KeyInfoReference(Document doc, String URI) {
+ public KeyInfoReference(Document doc, String uri) {
super(doc);
- this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
+ setLocalAttribute(Constants._ATT_URI, uri);
}
/**
@@ -65,7 +64,7 @@
* @return the URI attribute
*/
public Attr getURIAttr() {
- return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+ return getElement().getAttributeNodeNS(null, Constants._ATT_URI);
}
/**
@@ -78,29 +77,24 @@
}
/**
- * Sets the Id
attribute
+ * Sets the {@code Id} attribute
*
- * @param Id ID
+ * @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);
- }
+ setLocalIdAttribute(Constants._ATT_ID, id);
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute
+ * @return the {@code Id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_KEYINFOREFERENCE;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java
@@ -29,7 +29,6 @@
import org.w3c.dom.Element;
/**
- * @author $Author: coheigea $
*/
public class KeyName extends SignatureElementProxy implements KeyInfoContent {
@@ -37,11 +36,11 @@
* Constructor KeyName
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public KeyName(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public KeyName(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
@@ -65,7 +64,7 @@
return this.getTextFromTextChild();
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_KEYNAME;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java
@@ -41,7 +41,6 @@
* keys values represented as PCDATA or element types from an external
* namespace.
*
- * @author $Author: coheigea $
*/
public class KeyValue extends SignatureElementProxy implements KeyInfoContent {
@@ -54,9 +53,9 @@
public KeyValue(Document doc, DSAKeyValue dsaKeyValue) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
- this.constructionElement.appendChild(dsaKeyValue.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
+ appendSelf(dsaKeyValue);
+ addReturnToSelf();
}
/**
@@ -68,9 +67,9 @@
public KeyValue(Document doc, RSAKeyValue rsaKeyValue) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
- this.constructionElement.appendChild(rsaKeyValue.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
+ appendSelf(rsaKeyValue);
+ addReturnToSelf();
}
/**
@@ -82,9 +81,9 @@
public KeyValue(Document doc, Element unknownKeyValue) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
- this.constructionElement.appendChild(unknownKeyValue);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
+ appendSelf(unknownKeyValue);
+ addReturnToSelf();
}
/**
@@ -96,18 +95,22 @@
public KeyValue(Document doc, PublicKey pk) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
if (pk instanceof java.security.interfaces.DSAPublicKey) {
- DSAKeyValue dsa = new DSAKeyValue(this.doc, pk);
+ DSAKeyValue dsa = new DSAKeyValue(getDocument(), pk);
- this.constructionElement.appendChild(dsa.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(dsa);
+ addReturnToSelf();
} else if (pk instanceof java.security.interfaces.RSAPublicKey) {
- RSAKeyValue rsa = new RSAKeyValue(this.doc, pk);
+ RSAKeyValue rsa = new RSAKeyValue(getDocument(), pk);
- this.constructionElement.appendChild(rsa.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(rsa);
+ addReturnToSelf();
+ } else {
+ String error = "The given PublicKey type " + pk + " is not supported. Only DSAPublicKey and "
+ + "RSAPublicKey types are currently supported";
+ throw new IllegalArgumentException(error);
}
}
@@ -115,11 +118,11 @@
* Constructor KeyValue
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public KeyValue(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public KeyValue(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
@@ -131,7 +134,7 @@
public PublicKey getPublicKey() throws XMLSecurityException {
Element rsa =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
+ getFirstChild(), Constants._TAG_RSAKEYVALUE, 0);
if (rsa != null) {
RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI);
@@ -140,7 +143,7 @@
Element dsa =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
+ getFirstChild(), Constants._TAG_DSAKEYVALUE, 0);
if (dsa != null) {
DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI);
@@ -150,7 +153,7 @@
return null;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_KEYVALUE;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java
@@ -29,7 +29,6 @@
import org.w3c.dom.Element;
/**
- * @author $Author: coheigea $
*/
public class MgmtData extends SignatureElementProxy implements KeyInfoContent {
@@ -37,12 +36,12 @@
* Constructor MgmtData
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public MgmtData(Element element, String BaseURI)
+ public MgmtData(Element element, String baseURI)
throws XMLSecurityException {
- super(element, BaseURI);
+ super(element, baseURI);
}
/**
@@ -66,7 +65,7 @@
return this.getTextFromTextChild();
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_MGMTDATA;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java
@@ -28,7 +28,6 @@
import org.w3c.dom.Element;
/**
- * @author $Author: coheigea $
* $todo$ Implement
*/
public class PGPData extends SignatureElementProxy implements KeyInfoContent {
@@ -37,14 +36,14 @@
* Constructor PGPData
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public PGPData(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public PGPData(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_PGPDATA;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java
@@ -35,17 +35,17 @@
public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent {
/** DSA retrieval */
- public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue";
+ public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue";
/** RSA retrieval */
- public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue";
+ public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue";
/** PGP retrieval */
- public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData";
+ public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData";
/** SPKI retrieval */
- public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData";
+ public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData";
/** MGMT retrieval */
- public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData";
+ public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData";
/** X509 retrieval */
- public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data";
+ public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data";
/** RAWX509 retrieval */
public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate";
@@ -53,11 +53,11 @@
* Constructor RetrievalMethod
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public RetrievalMethod(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public RetrievalMethod(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
@@ -71,15 +71,15 @@
public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) {
super(doc);
- this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI);
+ setLocalAttribute(Constants._ATT_URI, URI);
if (Type != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type);
+ setLocalAttribute(Constants._ATT_TYPE, Type);
}
if (transforms != null) {
- this.constructionElement.appendChild(transforms.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(transforms);
+ addReturnToSelf();
}
}
@@ -89,7 +89,7 @@
* @return the URI attribute
*/
public Attr getURIAttr() {
- return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+ return getElement().getAttributeNodeNS(null, Constants._ATT_URI);
}
/**
@@ -98,12 +98,12 @@
* @return URI string
*/
public String getURI() {
- return this.getURIAttr().getNodeValue();
+ return getLocalAttribute(Constants._ATT_URI);
}
/** @return the type*/
public String getType() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+ return getLocalAttribute(Constants._ATT_TYPE);
}
/**
@@ -116,7 +116,7 @@
try {
Element transformsElem =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0);
+ getFirstChild(), Constants._TAG_TRANSFORMS, 0);
if (transformsElem != null) {
return new Transforms(transformsElem, this.baseURI);
@@ -124,11 +124,11 @@
return null;
} catch (XMLSignatureException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
}
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_RETRIEVALMETHOD;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java
@@ -28,7 +28,6 @@
import org.w3c.dom.Element;
/**
- * @author $Author: coheigea $
* $todo$ implement
*/
public class SPKIData extends SignatureElementProxy implements KeyInfoContent {
@@ -37,15 +36,15 @@
* Constructor SPKIData
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public SPKIData(Element element, String BaseURI)
+ public SPKIData(Element element, String baseURI)
throws XMLSecurityException {
- super(element, BaseURI);
+ super(element, baseURI);
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_SPKIDATA;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java
@@ -41,9 +41,8 @@
public class X509Data extends SignatureElementProxy implements KeyInfoContent {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(X509Data.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509Data.class);
/**
* Constructor X509Data
@@ -53,7 +52,7 @@
public X509Data(Document doc) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
}
/**
@@ -66,17 +65,15 @@
public X509Data(Element element, String baseURI) throws XMLSecurityException {
super(element, baseURI);
- Node sibling = this.constructionElement.getFirstChild();
- while (sibling != null) {
- if (sibling.getNodeType() != Node.ELEMENT_NODE) {
- sibling = sibling.getNextSibling();
- continue;
- }
- return;
+ Node sibling = getFirstChild();
+ while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
+ sibling = sibling.getNextSibling();
}
- /* No Elements found */
- Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
- throw new XMLSecurityException("xml.WrongContent", exArgs);
+ if (sibling == null || sibling.getNodeType() != Node.ELEMENT_NODE) {
+ /* No Elements found */
+ Object exArgs[] = { "Elements", Constants._TAG_X509DATA };
+ throw new XMLSecurityException("xml.WrongContent", exArgs);
+ }
}
/**
@@ -86,7 +83,7 @@
* @param X509SerialNumber
*/
public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) {
- this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+ this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
}
/**
@@ -96,7 +93,7 @@
* @param X509SerialNumber
*/
public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) {
- this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+ this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
}
/**
@@ -106,7 +103,7 @@
* @param X509SerialNumber
*/
public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) {
- this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber));
+ this.add(new XMLX509IssuerSerial(getDocument(), X509IssuerName, X509SerialNumber));
}
/**
@@ -116,8 +113,8 @@
*/
public void add(XMLX509IssuerSerial xmlX509IssuerSerial) {
- this.constructionElement.appendChild(xmlX509IssuerSerial.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(xmlX509IssuerSerial);
+ addReturnToSelf();
}
/**
@@ -126,7 +123,7 @@
* @param skiBytes
*/
public void addSKI(byte[] skiBytes) {
- this.add(new XMLX509SKI(this.doc, skiBytes));
+ this.add(new XMLX509SKI(getDocument(), skiBytes));
}
/**
@@ -137,7 +134,7 @@
*/
public void addSKI(X509Certificate x509certificate)
throws XMLSecurityException {
- this.add(new XMLX509SKI(this.doc, x509certificate));
+ this.add(new XMLX509SKI(getDocument(), x509certificate));
}
/**
@@ -146,8 +143,8 @@
* @param xmlX509SKI
*/
public void add(XMLX509SKI xmlX509SKI) {
- this.constructionElement.appendChild(xmlX509SKI.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(xmlX509SKI);
+ addReturnToSelf();
}
/**
@@ -156,7 +153,7 @@
* @param subjectName
*/
public void addSubjectName(String subjectName) {
- this.add(new XMLX509SubjectName(this.doc, subjectName));
+ this.add(new XMLX509SubjectName(getDocument(), subjectName));
}
/**
@@ -165,7 +162,7 @@
* @param x509certificate
*/
public void addSubjectName(X509Certificate x509certificate) {
- this.add(new XMLX509SubjectName(this.doc, x509certificate));
+ this.add(new XMLX509SubjectName(getDocument(), x509certificate));
}
/**
@@ -174,8 +171,8 @@
* @param xmlX509SubjectName
*/
public void add(XMLX509SubjectName xmlX509SubjectName) {
- this.constructionElement.appendChild(xmlX509SubjectName.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(xmlX509SubjectName);
+ addReturnToSelf();
}
/**
@@ -186,7 +183,7 @@
*/
public void addCertificate(X509Certificate x509certificate)
throws XMLSecurityException {
- this.add(new XMLX509Certificate(this.doc, x509certificate));
+ this.add(new XMLX509Certificate(getDocument(), x509certificate));
}
/**
@@ -195,7 +192,7 @@
* @param x509certificateBytes
*/
public void addCertificate(byte[] x509certificateBytes) {
- this.add(new XMLX509Certificate(this.doc, x509certificateBytes));
+ this.add(new XMLX509Certificate(getDocument(), x509certificateBytes));
}
/**
@@ -204,8 +201,8 @@
* @param xmlX509Certificate
*/
public void add(XMLX509Certificate xmlX509Certificate) {
- this.constructionElement.appendChild(xmlX509Certificate.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(xmlX509Certificate);
+ addReturnToSelf();
}
/**
@@ -214,7 +211,7 @@
* @param crlBytes
*/
public void addCRL(byte[] crlBytes) {
- this.add(new XMLX509CRL(this.doc, crlBytes));
+ this.add(new XMLX509CRL(getDocument(), crlBytes));
}
/**
@@ -223,8 +220,8 @@
* @param xmlX509CRL
*/
public void add(XMLX509CRL xmlX509CRL) {
- this.constructionElement.appendChild(xmlX509CRL.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(xmlX509CRL);
+ addReturnToSelf();
}
/**
@@ -236,27 +233,27 @@
*/
public void addDigest(X509Certificate x509certificate, String algorithmURI)
throws XMLSecurityException {
- this.add(new XMLX509Digest(this.doc, x509certificate, algorithmURI));
+ this.add(new XMLX509Digest(getDocument(), x509certificate, algorithmURI));
}
/**
* Method addDigest
*
- * @param x509CertificateDigestByes
+ * @param x509CertificateDigestBytes
* @param algorithmURI
*/
- public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) {
- this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI));
+ public void addDigest(byte[] x509CertificateDigestBytes, String algorithmURI) {
+ this.add(new XMLX509Digest(getDocument(), x509CertificateDigestBytes, algorithmURI));
}
/**
* Method add
*
- * @param XMLX509Digest
+ * @param xmlX509Digest
*/
public void add(XMLX509Digest xmlX509Digest) {
- this.constructionElement.appendChild(xmlX509Digest.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(xmlX509Digest);
+ addReturnToSelf();
}
/**
@@ -265,8 +262,8 @@
* @param element
*/
public void addUnknownElement(Element element) {
- this.constructionElement.appendChild(element);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(element);
+ addReturnToSelf();
}
/**
@@ -330,9 +327,9 @@
*/
public int lengthUnknownElement() {
int result = 0;
- Node n = this.constructionElement.getFirstChild();
- while (n != null){
- if ((n.getNodeType() == Node.ELEMENT_NODE)
+ Node n = getFirstChild();
+ while (n != null) {
+ if (n.getNodeType() == Node.ELEMENT_NODE
&& !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) {
result++;
}
@@ -352,7 +349,7 @@
public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
+ getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i);
if (e != null) {
return new XMLX509IssuerSerial(e, this.baseURI);
@@ -371,7 +368,7 @@
Element e =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i);
+ getFirstChild(), Constants._TAG_X509SKI, i);
if (e != null) {
return new XMLX509SKI(e, this.baseURI);
@@ -390,7 +387,7 @@
Element e =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
+ getFirstChild(), Constants._TAG_X509SUBJECTNAME, i);
if (e != null) {
return new XMLX509SubjectName(e, this.baseURI);
@@ -402,14 +399,14 @@
* Method itemCertificate
*
* @param i
- * @return the X509Certifacte, null if not present
+ * @return the X509Certificate, null if not present
* @throws XMLSecurityException
*/
public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException {
Element e =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
+ getFirstChild(), Constants._TAG_X509CERTIFICATE, i);
if (e != null) {
return new XMLX509Certificate(e, this.baseURI);
@@ -428,7 +425,7 @@
Element e =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i);
+ getFirstChild(), Constants._TAG_X509CRL, i);
if (e != null) {
return new XMLX509CRL(e, this.baseURI);
@@ -447,7 +444,7 @@
Element e =
XMLUtils.selectDs11Node(
- this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i);
+ getFirstChild(), Constants._TAG_X509DIGEST, i);
if (e != null) {
return new XMLX509Digest(e, this.baseURI);
@@ -463,9 +460,7 @@
* 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);
- }
+ LOG.debug("itemUnknownElement not implemented: {}", i);
return null;
}
@@ -532,7 +527,7 @@
return this.lengthUnknownElement() > 0;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_X509DATA;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java
@@ -27,6 +27,7 @@
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
+import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
@@ -35,7 +36,6 @@
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.SignatureElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -64,7 +64,7 @@
public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
this.addBigIntegerElement(P, Constants._TAG_P);
this.addBigIntegerElement(Q, Constants._TAG_Q);
this.addBigIntegerElement(G, Constants._TAG_G);
@@ -81,12 +81,13 @@
public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
- 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);
+ if (key instanceof DSAPublicKey) {
+ DSAParams params = ((DSAPublicKey) key).getParams();
+ this.addBigIntegerElement(params.getP(), Constants._TAG_P);
+ this.addBigIntegerElement(params.getQ(), Constants._TAG_Q);
+ this.addBigIntegerElement(params.getG(), Constants._TAG_G);
this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y);
} else {
Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() };
@@ -95,7 +96,7 @@
}
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public PublicKey getPublicKey() throws XMLSecurityException {
try {
DSAPublicKeySpec pkspec =
@@ -118,13 +119,13 @@
return pk;
} catch (NoSuchAlgorithmException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
} catch (InvalidKeySpecException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
}
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_DSAKEYVALUE;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java
@@ -35,7 +35,6 @@
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.SignatureElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -45,11 +44,11 @@
* Constructor RSAKeyValue
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public RSAKeyValue(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
@@ -62,7 +61,7 @@
public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
this.addBigIntegerElement(modulus, Constants._TAG_MODULUS);
this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT);
}
@@ -77,9 +76,9 @@
public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
- if (key instanceof java.security.interfaces.RSAPublicKey ) {
+ if (key instanceof RSAPublicKey ) {
this.addBigIntegerElement(
((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS
);
@@ -93,7 +92,7 @@
}
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public PublicKey getPublicKey() throws XMLSecurityException {
try {
KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
@@ -111,13 +110,13 @@
return pk;
} catch (NoSuchAlgorithmException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
} catch (InvalidKeySpecException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
}
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_RSAKEYVALUE;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/package.html
deleted file mode 100644
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/package.html
+++ /dev/null
@@ -1,3 +0,0 @@
-
-basic handlers for elements that can occur inside ds:KeyValue
.
-
-basic handlers for elements that can occur inside ds:KeyInfo
.
-
dsig11:X509Digest
element.
+ * Provides content model support for the {@code dsig11:X509Digest} element.
*
- * @author Brent Putman (putmanb@georgetown.edu)
*/
public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent {
@@ -44,11 +43,11 @@
* Constructor XMLX509Digest
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public XMLX509Digest(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public XMLX509Digest(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
@@ -61,7 +60,7 @@
public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) {
super(doc);
this.addBase64Text(digestBytes);
- this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+ setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
}
/**
@@ -75,7 +74,7 @@
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);
+ setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
}
/**
@@ -84,7 +83,7 @@
* @return the Algorithm attribute
*/
public Attr getAlgorithmAttr() {
- return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_ALGORITHM);
+ return getElement().getAttributeNodeNS(null, Constants._ATT_ALGORITHM);
}
/**
@@ -118,21 +117,21 @@
public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException {
String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI);
if (jcaDigestAlgorithm == null) {
- Object exArgs[] = { algorithmURI };
- throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs);
+ Object exArgs[] = { algorithmURI };
+ throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs);
}
try {
- MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
- return md.digest(cert.getEncoded());
- } catch (Exception e) {
- Object exArgs[] = { jcaDigestAlgorithm };
- throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
- }
+ MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm);
+ return md.digest(cert.getEncoded());
+ } catch (Exception e) {
+ Object exArgs[] = { jcaDigestAlgorithm };
+ throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs);
+ }
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_X509DIGEST;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java
@@ -29,15 +29,13 @@
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.RFC2253Parser;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLX509IssuerSerial.class);
/**
* Constructor XMLX509IssuerSerial
@@ -59,7 +57,7 @@
*/
public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME);
addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER);
}
@@ -108,9 +106,7 @@
public BigInteger getSerialNumber() {
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);
- }
+ LOG.debug("X509SerialNumber text: {}", text);
return new BigInteger(text);
}
@@ -135,7 +131,7 @@
);
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public boolean equals(Object obj) {
if (!(obj instanceof XMLX509IssuerSerial)) {
return false;
@@ -154,7 +150,7 @@
return result;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_X509ISSUERSERIAL;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java
@@ -24,9 +24,9 @@
import java.security.cert.X509Certificate;
import java.util.Arrays;
+import java.util.Base64;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
-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.SignatureElementProxy;
import org.w3c.dom.Document;
@@ -40,20 +40,19 @@
*/
public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(XMLX509SKI.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLX509SKI.class);
/**
- * SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14)
:
+ * {@code SubjectKeyIdentifier (id-ce-subjectKeyIdentifier) (2.5.29.14)}:
* This extension identifies the public key being certified. It enables
* distinct keys used by the same subject to be differentiated
* (e.g., as key updating occurs).
- *
-basic handlers for elements that can occur inside ds:X509Data
.
-
dsig11:DEREncodedKeyValue
element.
+ * {@code dsig11:DEREncodedKeyValue} element.
*
- * @author Brent Putman (putmanb@georgetown.edu)
*/
public class DEREncodedKeyValueResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(DEREncodedKeyValueResolver.class);
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE);
}
- /** {@inheritDoc}. */
+ /** {{@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());
- }
+ LOG.debug("Can I resolve {}", element.getTagName());
if (!engineCanResolve(element, baseURI, storage)) {
return null;
@@ -52,27 +66,25 @@
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);
- }
+ LOG.debug("XMLSecurityException", e);
}
return null;
}
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage)
throws KeyResolverException {
return null;
}
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
throws KeyResolverException {
return null;
}
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage)
throws KeyResolverException {
return null;
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java
@@ -35,21 +35,20 @@
public class DSAKeyValueResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(DSAKeyValueResolver.class);
/**
* Method engineResolvePublicKey
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @return null if no {@link PublicKey} could be obtained
*/
public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) {
if (element == null) {
return null;
@@ -71,14 +70,12 @@
}
try {
- DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI);
+ 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);
- }
+ LOG.debug(ex.getMessage(), ex);
//do nothing
}
@@ -86,16 +83,16 @@
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public X509Certificate engineLookupResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) {
return null;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) {
return null;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java
deleted file mode 100644
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * reserved comment block
- * DO NOT REMOVE OR ALTER!
- */
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations;
-
-import java.security.Key;
-import java.security.PublicKey;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.crypto.SecretKey;
-
-import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey;
-import com.sun.org.apache.xml.internal.security.encryption.XMLCipher;
-import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException;
-import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi;
-import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver;
-import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants;
-import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
-import org.w3c.dom.Element;
-
-/**
- * The EncryptedKeyResolver
is not a generic resolver. It can
- * only be for specific instantiations, as the key being unwrapped will
- * always be of a particular type and will always have been wrapped by
- * another key which needs to be recursively resolved.
- *
- * The EncryptedKeyResolver
can therefore only be instantiated
- * with an algorithm. It can also be instantiated with a key (the KEK) or
- * will search the static KeyResolvers to find the appropriate key.
- *
- * @author Berin Lautenbach
- */
-public class EncryptedKeyResolver extends KeyResolverSpi {
-
- /** {@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 Listdsig11:KeyInfoReference
element.
+ * {@code dsig11:KeyInfoReference} element.
*
- * @author Brent Putman (putmanb@georgetown.edu)
*/
public class KeyInfoReferenceResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(KeyInfoReferenceResolver.class);
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE);
}
- /** {@inheritDoc}. */
+ /** {{@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());
- }
+ LOG.debug("Can I resolve {}", element.getTagName());
if (!engineCanResolve(element, baseURI, storage)) {
return null;
@@ -68,21 +77,17 @@
return referent.getPublicKey();
}
} catch (XMLSecurityException e) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
- }
+ LOG.debug("XMLSecurityException", e);
}
return null;
}
- /** {@inheritDoc}. */
+ /** {{@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());
- }
+ LOG.debug("Can I resolve {}", element.getTagName());
if (!engineCanResolve(element, baseURI, storage)) {
return null;
@@ -94,21 +99,17 @@
return referent.getX509Certificate();
}
} catch (XMLSecurityException e) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
- }
+ LOG.debug("XMLSecurityException", e);
}
return null;
}
- /** {@inheritDoc}. */
+ /** {{@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());
- }
+ LOG.debug("Can I resolve {}", element.getTagName());
if (!engineCanResolve(element, baseURI, storage)) {
return null;
@@ -120,21 +121,17 @@
return referent.getSecretKey();
}
} catch (XMLSecurityException e) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
- }
+ LOG.debug("XMLSecurityException", e);
}
return null;
}
- /** {@inheritDoc}. */
+ /** {{@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());
- }
+ LOG.debug("Can I resolve " + element.getTagName());
if (!engineCanResolve(element, baseURI, storage)) {
return null;
@@ -146,9 +143,7 @@
return referent.getPrivateKey();
}
} catch (XMLSecurityException e) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
- }
+ LOG.debug("XMLSecurityException", e);
}
return null;
@@ -173,14 +168,12 @@
try {
referentElement = obtainReferenceElement(resource);
} catch (Exception e) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
- }
+ LOG.debug("XMLSecurityException", e);
return null;
}
if (referentElement == null) {
- log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue());
+ LOG.debug("De-reference of KeyInfoReference URI returned null: {}", uriAttr.getValue());
return null;
}
@@ -224,21 +217,20 @@
* @param uri
* @param baseURI
* @param secureValidation
- * @return
+ * @return the XML signature input represented by the specified URI.
* @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;
+ return resRes.resolve(uri, baseURI, secureValidation);
}
/**
* Resolve the Element effectively represented by the XML signature input source.
*
* @param resource
- * @return
+ * @return the Element effectively represented by the XML signature input source.
* @throws CanonicalizationException
* @throws ParserConfigurationException
* @throws IOException
@@ -253,38 +245,13 @@
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");
+ LOG.debug("De-reference of KeyInfoReference returned an unsupported NodeSet");
return null;
} else {
// Retrieved resource is a byte stream
byte inputBytes[] = resource.getBytes();
- e = getDocFromBytes(inputBytes);
+ e = getDocFromBytes(inputBytes, this.secureValidation);
}
return e;
}
-
- /**
- * Parses a byte array and returns the parsed Element.
- *
- * @param bytes
- * @return the Document Element after parsing bytes
- * @throws KeyResolverException if something goes wrong
- */
- private Element getDocFromBytes(byte[] bytes) throws KeyResolverException {
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(new ByteArrayInputStream(bytes));
- return doc.getDocumentElement();
- } catch (SAXException ex) {
- throw new KeyResolverException("empty", ex);
- } catch (IOException ex) {
- throw new KeyResolverException("empty", ex);
- } catch (ParserConfigurationException ex) {
- throw new KeyResolverException("empty", ex);
- }
- }
-
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java
@@ -2,6 +2,24 @@
* 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.keyresolver.implementations;
import java.security.Key;
@@ -34,9 +52,9 @@
* 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 static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(PrivateKeyResolver.class);
private KeyStore keyStore;
private char[] password;
@@ -53,11 +71,11 @@
* This method returns whether the KeyResolverSpi is able to perform the requested action.
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @return whether the KeyResolverSpi is able to perform the requested action.
*/
- public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {
+ public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)
|| XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
return true;
@@ -70,27 +88,27 @@
* Method engineLookupAndResolvePublicKey
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @return null if no {@link PublicKey} could be obtained
* @throws KeyResolverException
*/
public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
return null;
}
/**
* Method engineResolveX509Certificate
- * @inheritDoc
+ * {@inheritDoc}
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @throws KeyResolverException
*/
public X509Certificate engineLookupResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
return null;
}
@@ -99,21 +117,21 @@
* Method engineResolveSecretKey
*
* @param element
- * @param BaseURI
+ * @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
+ Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
return null;
}
/**
* Method engineResolvePrivateKey
- * @inheritDoc
+ * {@inheritDoc}
* @param element
* @param baseURI
* @param storage
@@ -123,9 +141,7 @@
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() + "?");
- }
+ LOG.debug("Can I resolve {}?", element.getTagName());
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
PrivateKey privKey = resolveX509Data(element, baseURI);
@@ -133,7 +149,7 @@
return privKey;
}
} else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
- log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?");
+ LOG.debug("Can I resolve KeyName?");
String keyName = element.getFirstChild().getNodeValue();
try {
@@ -142,16 +158,16 @@
return (PrivateKey) key;
}
} catch (Exception e) {
- log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
+ LOG.debug("Cannot recover the key", e);
}
}
- log.log(java.util.logging.Level.FINE, "I can't");
+ LOG.debug("I can't");
return null;
}
private PrivateKey resolveX509Data(Element element, String baseURI) {
- log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?");
+ LOG.debug("Can I resolve X509Data?");
try {
X509Data x509Data = new X509Data(element, baseURI);
@@ -192,9 +208,9 @@
}
}
} catch (XMLSecurityException e) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
+ LOG.debug("XMLSecurityException", e);
} catch (KeyStoreException e) {
- log.log(java.util.logging.Level.FINE, "KeyStoreException", e);
+ LOG.debug("KeyStoreException", e);
}
return null;
@@ -204,7 +220,7 @@
* 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?");
+ LOG.debug("Can I resolve X509SKI?");
Enumerationds:X509Certificate
Element.
+ * {@code ds:X509Certificate} Element.
*
- * @author $Author: coheigea $
*/
public class X509CertificateResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509CertificateResolver.class);
/**
* Method engineResolvePublicKey
- * @inheritDoc
+ * {@inheritDoc}
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
*
* @throws KeyResolverException
*/
public PublicKey engineLookupAndResolvePublicKey(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
X509Certificate cert =
- this.engineLookupResolveX509Certificate(element, BaseURI, storage);
+ this.engineLookupResolveX509Certificate(element, baseURI, storage);
if (cert != null) {
return cert.getPublicKey();
@@ -71,32 +69,32 @@
/**
* Method engineResolveX509Certificate
- * @inheritDoc
+ * {@inheritDoc}
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
*
* @throws KeyResolverException
*/
public X509Certificate engineLookupResolveX509Certificate(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
try {
Element[] els =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE);
- if ((els == null) || (els.length == 0)) {
+ 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 engineLookupResolveX509Certificate(el, baseURI, storage);
}
return null;
}
// populate Object array
for (int i = 0; i < els.length; i++) {
- XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI);
+ XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], baseURI);
X509Certificate cert = xmlCert.getX509Certificate();
if (cert != null) {
return cert;
@@ -104,22 +102,20 @@
}
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);
+ LOG.debug("Security Exception", ex);
+ throw new KeyResolverException(ex);
}
}
/**
* Method engineResolveSecretKey
- * @inheritDoc
+ * {@inheritDoc}
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
*/
public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
- Element element, String BaseURI, StorageResolver storage
+ Element element, String baseURI, StorageResolver storage
) {
return null;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java
@@ -2,6 +2,24 @@
* 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.keyresolver.implementations;
import java.security.PublicKey;
@@ -24,17 +42,15 @@
/**
* KeyResolverSpi implementation which resolves public keys and X.509 certificates from a
- * dsig11:X509Digest
element.
+ * {@code dsig11:X509Digest} element.
*
- * @author Brent Putman (putmanb@georgetown.edu)
*/
public class X509DigestResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(X509DigestResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509DigestResolver.class);
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) {
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
try {
@@ -48,7 +64,7 @@
}
}
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage)
throws KeyResolverException {
@@ -61,13 +77,11 @@
return null;
}
- /** {@inheritDoc}. */
+ /** {{@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());
- }
+ LOG.debug("Can I resolve {}", element.getTagName());
if (!engineCanResolve(element, baseURI, storage)) {
return null;
@@ -76,15 +90,13 @@
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);
- }
+ LOG.debug("XMLSecurityException", e);
}
return null;
}
- /** {@inheritDoc}. */
+ /** {{@inheritDoc}}. */
public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
throws KeyResolverException {
return null;
@@ -96,7 +108,7 @@
* @param element
* @param baseURI
* @param storage
- * @return
+ * @return the certificate represented by the digest.
* @throws XMLSecurityException
*/
private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage)
@@ -128,9 +140,7 @@
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());
- }
+ LOG.debug("Found certificate with: {}", cert.getSubjectX500Principal().getName());
return cert;
}
@@ -138,7 +148,7 @@
}
} catch (XMLSecurityException ex) {
- throw new KeyResolverException("empty", ex);
+ throw new KeyResolverException(ex);
}
return null;
@@ -154,9 +164,7 @@
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);
- }
+ LOG.debug("", ex);
throw ex;
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java
@@ -39,12 +39,11 @@
public class X509IssuerSerialResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509IssuerSerialResolver.class);
- /** @inheritDoc */
+ /** {@inheritDoc} */
public PublicKey engineLookupAndResolvePublicKey(
Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
@@ -59,26 +58,20 @@
return null;
}
- /** @inheritDoc */
+ /** {@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() + "?");
- }
+ LOG.debug("Can I resolve {}?", element.getTagName());
X509Data x509data = null;
try {
x509data = new X509Data(element, baseURI);
} catch (XMLSignatureException ex) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "I can't");
- }
+ LOG.debug("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");
- }
+ LOG.debug("I can't");
return null;
}
@@ -91,9 +84,7 @@
KeyResolverException ex =
new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "", ex);
- }
+ LOG.debug("", ex);
throw ex;
}
@@ -104,44 +95,32 @@
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());
- }
+ LOG.debug("Found Certificate Issuer: {}", certSerial.getIssuerName());
+ LOG.debug("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());
- }
+ LOG.debug("Found Element Issuer: {}", xmliss.getIssuerName());
+ LOG.debug("Found Element Serial: {}", xmliss.getSerialNumber().toString());
if (certSerial.equals(xmliss)) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "match !!! ");
- }
+ LOG.debug("match !!! ");
return cert;
}
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "no match...");
- }
+ LOG.debug("no match...");
}
}
return null;
} catch (XMLSecurityException ex) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
- }
+ LOG.debug("XMLSecurityException", ex);
- throw new KeyResolverException("generic.EmptyMessage", ex);
+ throw new KeyResolverException(ex);
}
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public javax.crypto.SecretKey engineLookupAndResolveSecretKey(
Element element, String baseURI, StorageResolver storage
) {
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java
@@ -39,9 +39,8 @@
public class X509SKIResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(X509SKIResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SKIResolver.class);
/**
@@ -69,7 +68,7 @@
/**
* Method engineResolveX509Certificate
- * @inheritDoc
+ * {@inheritDoc}
* @param element
* @param baseURI
* @param storage
@@ -79,13 +78,9 @@
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() + "?");
- }
+ LOG.debug("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");
- }
+ LOG.debug("I can't");
return null;
}
/** Field _x509childObject[] */
@@ -94,10 +89,8 @@
Element x509childNodes[] = null;
x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);
- if (!((x509childNodes != null) && (x509childNodes.length > 0))) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "I can't");
- }
+ if (!(x509childNodes != null && x509childNodes.length > 0)) {
+ LOG.debug("I can't");
return null;
}
try {
@@ -106,9 +99,7 @@
KeyResolverException ex =
new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "", ex);
- }
+ LOG.debug("", ex);
throw ex;
}
@@ -126,16 +117,14 @@
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());
- }
+ LOG.debug("Return PublicKey from {}", cert.getSubjectX500Principal().getName());
return cert;
}
}
}
} catch (XMLSecurityException ex) {
- throw new KeyResolverException("empty", ex);
+ throw new KeyResolverException(ex);
}
return null;
@@ -143,7 +132,7 @@
/**
* Method engineResolveSecretKey
- * @inheritDoc
+ * {@inheritDoc}
* @param element
* @param baseURI
* @param storage
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java
@@ -39,16 +39,15 @@
public class X509SubjectNameResolver extends KeyResolverSpi {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(X509SubjectNameResolver.class);
/**
* Method engineResolvePublicKey
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @param storage
* @return null if no {@link PublicKey} could be obtained
* @throws KeyResolverException
@@ -69,7 +68,7 @@
/**
* Method engineResolveX509Certificate
- * @inheritDoc
+ * {@inheritDoc}
* @param element
* @param baseURI
* @param storage
@@ -79,26 +78,19 @@
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() + "?");
- }
+ LOG.debug("Can I resolve {}?", element.getTagName());
Element[] x509childNodes = null;
XMLX509SubjectName x509childObject[] = null;
if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "I can't");
- }
+ LOG.debug("I can't");
return null;
}
x509childNodes =
XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME);
- if (!((x509childNodes != null)
- && (x509childNodes.length > 0))) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "I can't");
- }
+ if (!(x509childNodes != null && x509childNodes.length > 0)) {
+ LOG.debug("I can't");
return null;
}
@@ -108,9 +100,7 @@
KeyResolverException ex =
new KeyResolverException("KeyResolver.needStorageResolver", exArgs);
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "", ex);
- }
+ LOG.debug("", ex);
throw ex;
}
@@ -127,42 +117,31 @@
XMLX509SubjectName certSN =
new XMLX509SubjectName(element.getOwnerDocument(), cert);
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName());
- }
+ LOG.debug("Found Certificate SN: {}", certSN.getSubjectName());
for (int i = 0; i < x509childObject.length; i++) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Found Element SN: "
- + x509childObject[i].getSubjectName());
- }
+ LOG.debug("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 !!! ");
- }
+ LOG.debug("match !!! ");
return cert;
}
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "no match...");
- }
+ LOG.debug("no match...");
}
}
return null;
} catch (XMLSecurityException ex) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
- }
+ LOG.debug("XMLSecurityException", ex);
- throw new KeyResolverException("generic.EmptyMessage", ex);
+ throw new KeyResolverException(ex);
}
}
/**
* Method engineResolveSecretKey
- * @inheritDoc
+ * {@inheritDoc}
* @param element
* @param baseURI
* @param storage
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/package.html
deleted file mode 100644
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/package.html
+++ /dev/null
@@ -1,3 +0,0 @@
--implementations for retrieval of certificates and public keys from elements. -
\ No newline at end of file diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/package.html +++ /dev/null @@ -1,3 +0,0 @@ --the resolver framework for retrieval of certificates and public keys from elements. -
\ No newline at end of file diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/package.html +++ /dev/null @@ -1,3 +0,0 @@ --general key related material. -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java --- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java @@ -38,12 +38,11 @@ */ public class StorageResolver { - /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(StorageResolver.class.getName()); + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(StorageResolver.class); /** Field storageResolvers */ - private List-implementations of resolvers for retrieval for certificates and public keys from user-specified locations. -
\ No newline at end of file diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/package.html +++ /dev/null @@ -1,3 +0,0 @@ --a resolver framework for certificates and public keys from user-specified locations. -
\ No newline at end of file diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/package.html deleted file mode 100644 --- a/src/share/classes/com/sun/org/apache/xml/internal/security/package.html +++ /dev/null @@ -1,36 +0,0 @@ - - -See the xml-security project for further assistence
-Christian Geuer-Pollmann geuer-pollmann@nue.et-inf.uni-siegen.de
- University of Siegen
- Institute for Data Communications Systems
-
-software configuration and internationalization ({@link com.sun.org.apache.xml.internal.security.utils.I18n}). -
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties b/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties --- a/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties +++ b/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties @@ -1,126 +1,196 @@ +# +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# + algorithm.alreadyRegistered = URI {0} wurde bereits an die Klasse {1} gebunden -algorithm.classDoesNotExist = Kann URI {0} nicht für Klasse {1} registrieren weil sie nicht existiert +algorithm.classDoesNotExist = Kann URI {0} nicht f\u00fcr Klasse {1} registrieren weil sie nicht existiert algorithm.ClassDoesNotExist = Klasse {0} existiert nicht -algorithm.extendsWrongClass = Kann URI {0} nicht für Klasse {1} registrieren weil sie nicht {2} extended -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 -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 während Kanonisierung: Original Nachricht war {0} -c14n.Canonicalizer.IllegalNode = Unzulässiger NodeType {0}, NodeName lautete {1} -c14n.Canonicalizer.NoSuchCanonicalizer = Kein Canonicalizer mit dem URI {0} gefunden -c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException während Kanonisierung: Original Nachricht war {0} +algorithm.extendsWrongClass = Kann URI {0} nicht f\u00fcr Klasse {1} registrieren weil sie nicht von {2} abgeleitet ist +algorithms.CannotUseAlgorithmParameterSpecOnDSA = AlgorithmParameterSpec kann nicht f\u00fcr DSA Signaturen benutzt werden. +algorithms.CannotUseAlgorithmParameterSpecOnRSA = AlgorithmParameterSpec kann nicht f\u00fcr RSA Signaturen benutzt werden. +algorithms.CannotUseSecureRandomOnMAC = SecureRandom kann nicht f\u00fcr MAC's angewandt werden. +algorithms.HMACOutputLengthMin = HMACOutputLength darf nicht kleiner als {0} sein +algorithms.HMACOutputLengthOnlyForHMAC = Die HMACOutputLength kann nur bei HMAC integrit\u00e4ts Algorithmen angegeben werden +algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verf\u00fcgbar. +algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verf\u00fcgbar. Original Nachricht war\: {1} +algorithms.NoSuchMap = Algorithmus URI "{0}" konnte auf keinen JCE Algorithmus gemappt werden +algorithms.NoSuchProvider = Der angegebene Provider {0} existiert nicht. Original Nachricht war\: {1} +algorithms.operationOnlyVerification = Ein \u00f6ffentlicher Schl\u00fcssel (public key) kann nur zur Verifizierung einer Signatur verwendet werden. +algorithms.WrongKeyForThisOperation = Der angegebene Schl\u00fcssel-Typ kann nicht f\u00fcr diese Operation verwendet werden. Angegeben wurde {0} aber ein {1} wird ben\u00f6tigt. +attributeValueIllegal = Das Attribut {0} hat den Wert {1} muss aber {2} sein. +c14n.Canonicalizer.Exception = Fehler w\u00e4hrend der Kanonisierung\: Original Nachricht war {0} +c14n.Canonicalizer.IllegalNode = Unzul\u00e4ssiger NodeType {0}, NodeName lautete {1} +c14n.Canonicalizer.NoSuchCanonicalizer = Kein Kanonisierer mit dem URI {0} gefunden +c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException w\u00e4hrend der Kanonisierung\: Original Nachricht war {0} c14n.Canonicalizer.RelativeNamespace = Das Element {0} hat einen relativen Namespace: {1}="{2}" -c14n.Canonicalizer.SAXException = SAXException während Kanonisierung: Original Nachricht war {0} -c14n.Canonicalizer.TraversalNotSupported = Das DOM Dokument unterstützt keine Traversal {0} -c14n.Canonicalizer.UnsupportedEncoding = Unbekannte Kodierung {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 = Kann einen ElementProxy aus einem null Argument erzeugen +c14n.Canonicalizer.SAXException = SAXException w\u00e4hrend der Kanonisierung\: Original Nachricht war {0} +c14n.Canonicalizer.TraversalNotSupported = Das DOM Dokument unterst\u00fctzt keine Traversal {0} +c14n.Canonicalizer.UnsupportedEncoding = Nicht unterst\u00fctzte Kodierung {0} +c14n.Canonicalizer.UnsupportedOperation = Der Kanonisierer unterst\u00fctzt diese Operation nicht +c14n.XMLUtils.circumventBug2650forgotten = Die Baumstruktur wurde nicht vorbereitet f\u00fcr die Kanonisierung mit XMLUtils\#circumventBug2650(Document) +certificate.noSki.lowVersion = Das Zertifikat dard kein SubjectKeyIdentifier enthalten da es nur ein X509v{0} ist +certificate.noSki.notOctetString = Der SubjectKeyIdentifier des Zertifikates ist kein "OctetString" +certificate.noSki.null = Das Zertifikat enth\u00e4lt kein SubjectKeyIdentifier +defaultNamespaceCannotBeSetHere = Standard Namespace kann hier nicht gesetzt werden +ElementProxy.nullElement = Kann keinen ElementProxy aus einem null Argument erzeugen 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<ds:Manifest>
elements.
- * This element holds the Reference
elements
This element holds the {@code Reference} elements
*/ public class Manifest extends SignatureElementProxy { @@ -60,36 +60,35 @@ */ 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()); + private static final com.sun.org.slf4j.internal.Logger LOG = + com.sun.org.slf4j.internal.LoggerFactory.getLogger(Manifest.class); /** Field references */ private ListXMLsignature
is placed
+ * @param doc the {@link Document} in which {@code XMLsignature} is placed
*/
public Manifest(Document doc) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
- this.references = new ArrayListaddDocument
method is used to add a new resource to the
+ * This {@code addDocument} method is used to add a new resource to the
* signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built
* from the supplied values.
*
* @param baseURI the URI of the resource where the XML instance was stored
- * @param referenceURI URI
attribute in Reference
for specifying
+ * @param referenceURI {@code URI} attribute in {@code Reference} for specifying
* where data is
* @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered
* list of transformations to be performed.
@@ -176,7 +175,7 @@
) throws XMLSignatureException {
// the this.doc is handed implicitly by the this.getOwnerDocument()
Reference ref =
- new Reference(this.doc, baseURI, referenceURI, this, transforms, digestURI);
+ new Reference(getDocument(), baseURI, referenceURI, this, transforms, digestURI);
if (referenceId != null) {
ref.setId(referenceId);
@@ -190,8 +189,8 @@
this.references.add(ref);
// add the Element of the Reference object to the Manifest/SignedInfo
- this.constructionElement.appendChild(ref.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(ref);
+ addReturnToSelf();
}
/**
@@ -221,11 +220,11 @@
}
/**
- * Return the i
- * values are 0 to {link@ getSize}-1
.
+ * Return the ith reference. Valid {@code i}
+ * values are 0 to {@code {link@ getSize}-1}.
*
* @param i Index of the requested {@link Reference}
- * @return the Id
attribute
+ * Sets the {@code Id} attribute
*
- * @param Id the Id
attribute in ds:Manifest
+ * @param Id the {@code Id} attribute in {@code ds:Manifest}
*/
public void setId(String Id) {
if (Id != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
- this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute in ds:Manifest
+ * @return the {@code Id} attribute in {@code ds:Manifest}
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
@@ -267,8 +265,8 @@
*
* This step loops through all {@link Reference}s and does verify the hash
* values. If one or more verifications fail, the method returns
- * false
. If all verifications are successful,
- * it returns true
. The results of the individual reference
+ * {@code false}. If all verifications are successful,
+ * it returns {@code true}. The results of the individual reference
* validations are available by using the {@link #getVerificationResult(int)} method
*
* @return true if all References verify, false if one or more do not verify.
@@ -291,8 +289,8 @@
*
*
This step loops through all {@link Reference}s and does verify the hash
* values. If one or more verifications fail, the method returns
- * Create a new reference There are 2 types of constructors for this class. The ones that take a
@@ -105,6 +103,10 @@
public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 =
Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160";
+ /** Signature - Optional RSAwithSHA224 */
+ public static final String ALGO_ID_SIGNATURE_RSA_SHA224 =
+ Constants.MoreAlgorithmsSpecNS + "rsa-sha224";
+
/** Signature - Optional RSAwithSHA256 */
public static final String ALGO_ID_SIGNATURE_RSA_SHA256 =
Constants.MoreAlgorithmsSpecNS + "rsa-sha256";
@@ -117,6 +119,26 @@
public static final String ALGO_ID_SIGNATURE_RSA_SHA512 =
Constants.MoreAlgorithmsSpecNS + "rsa-sha512";
+ /** Signature - Optional RSAwithSHA1andMGF1 */
+ public static final String ALGO_ID_SIGNATURE_RSA_SHA1_MGF1 =
+ Constants.XML_DSIG_NS_MORE_07_05 + "sha1-rsa-MGF1";
+
+ /** Signature - Optional RSAwithSHA224andMGF1 */
+ public static final String ALGO_ID_SIGNATURE_RSA_SHA224_MGF1 =
+ Constants.XML_DSIG_NS_MORE_07_05 + "sha224-rsa-MGF1";
+
+ /** Signature - Optional RSAwithSHA256andMGF1 */
+ public static final String ALGO_ID_SIGNATURE_RSA_SHA256_MGF1 =
+ Constants.XML_DSIG_NS_MORE_07_05 + "sha256-rsa-MGF1";
+
+ /** Signature - Optional RSAwithSHA384andMGF1 */
+ public static final String ALGO_ID_SIGNATURE_RSA_SHA384_MGF1 =
+ Constants.XML_DSIG_NS_MORE_07_05 + "sha384-rsa-MGF1";
+
+ /** Signature - Optional RSAwithSHA512andMGF1 */
+ public static final String ALGO_ID_SIGNATURE_RSA_SHA512_MGF1 =
+ Constants.XML_DSIG_NS_MORE_07_05 + "sha512-rsa-MGF1";
+
/** HMAC - NOT Recommended HMAC-MD5 */
public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
Constants.MoreAlgorithmsSpecNS + "hmac-md5";
@@ -125,6 +147,10 @@
public static final String ALGO_ID_MAC_HMAC_RIPEMD160 =
Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160";
+ /** HMAC - Optional HMAC-SHA2224 */
+ public static final String ALGO_ID_MAC_HMAC_SHA224 =
+ Constants.MoreAlgorithmsSpecNS + "hmac-sha224";
+
/** HMAC - Optional HMAC-SHA256 */
public static final String ALGO_ID_MAC_HMAC_SHA256 =
Constants.MoreAlgorithmsSpecNS + "hmac-sha256";
@@ -141,6 +167,10 @@
public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 =
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1";
+ /**Signature - Optional ECDSAwithSHA224 */
+ public static final String ALGO_ID_SIGNATURE_ECDSA_SHA224 =
+ "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha224";
+
/**Signature - Optional ECDSAwithSHA256 */
public static final String ALGO_ID_SIGNATURE_ECDSA_SHA256 =
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
@@ -153,9 +183,12 @@
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());
+ /**Signature - Optional ECDSAwithRIPEMD160 */
+ public static final String ALGO_ID_SIGNATURE_ECDSA_RIPEMD160 =
+ "http://www.w3.org/2007/05/xmldsig-more#ecdsa-ripemd160";
+
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(XMLSignature.class);
/** ds:Signature.ds:SignedInfo element */
private SignedInfo signedInfo;
@@ -177,9 +210,9 @@
private int state = MODE_SIGN;
/**
- * This creates a new
-XML Signature specific classes.
- The normative specification for base64 decoding transforms is
@@ -58,7 +57,7 @@
* This transform requires an octet stream for input.
* If an XPath node-set (or sufficiently functional alternative) is
* given as input, then it is converted to an octet stream by
- * performing operations logically equivalent to 1) applying an XPath
+ * performing operations LOGically equivalent to 1) applying an XPath
* transform with expression self::text(), then 2) taking the string-value
* of the node-set. Thus, if an XML element is identified by a barename
* XPointer in the Reference URI, and its content consists solely of base64
@@ -67,8 +66,6 @@
* elements as well as any descendant comments and processing instructions.
* The output of this transform is an octet stream.
-implementations of XML Signature transforms.
-
-the framework for XML Signature transforms.
-false
. If all verifications are successful,
- * it returns true
. The results of the individual reference
+ * {@code false}. If all verifications are successful,
+ * it returns {@code true}. The results of the individual reference
* validations are available by using the {@link #getVerificationResult(int)} method
*
* @param followManifests
@@ -310,16 +308,14 @@
if (referencesEl == null) {
this.referencesEl =
XMLUtils.selectDsNodes(
- this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE
+ 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");
- }
+ LOG.debug("verify {} References", referencesEl.length);
+ LOG.debug("I am {} requested to follow nested Manifests", (followManifests
+ ? "" : "not"));
if (referencesEl.length == 0) {
- throw new XMLSecurityException("empty");
+ throw new XMLSecurityException("empty", new Object[]{"References are empty"});
}
if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) {
Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT };
@@ -344,15 +340,11 @@
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());
- }
+ LOG.debug("The Reference has Type {}", currentRef.getType());
// was verification successful till now and do we want to verify the Manifest?
if (verify && followManifests && currentRef.typeIsReferenceToManifest()) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest");
- }
+ LOG.debug("We have to follow a nested Manifest");
try {
XMLSignatureInput signedManifestNodes =
@@ -361,10 +353,10 @@
Manifest referencedManifest = null;
IteratorURI
attribute
- * in reference
element
+ * Adds Resource Resolver for retrieving resources at specified {@code URI} attribute
+ * in {@code reference} element
*
* @param resolver {@link ResourceResolver} can provide the implemenatin subclass of
* {@link ResourceResolverSpi} for retrieving resource.
@@ -481,14 +470,14 @@
return;
}
if (perManifestResolvers == null) {
- perManifestResolvers = new ArrayListURI
attribute
- * in reference
element
+ * Adds Resource Resolver for retrieving resources at specified {@code URI} attribute
+ * in {@code reference} element
*
* @param resolverSpi the implementation subclass of {@link ResourceResolverSpi} for
* retrieving the resource.
@@ -498,7 +487,7 @@
return;
}
if (perManifestResolvers == null) {
- perManifestResolvers = new ArrayList<ds:Object>
elements
- * Object
{@link Element} supply facility which can contain any kind data
+ * Handles {@code <ds:Object>} elements
+ * {@code Object} {@link Element} supply facility which can contain any kind data
*
- * @author Christian Geuer-Pollmann
* $todo$ if we remove childen, the boolean values are not updated
*/
public class ObjectContainer extends SignatureElementProxy {
@@ -42,7 +41,7 @@
/**
* Constructs {@link ObjectContainer}
*
- * @param doc the {@link Document} in which
Object
element is placed
+ * @param doc the {@link Document} in which {@code Object} element is placed
*/
public ObjectContainer(Document doc) {
super(doc);
@@ -51,7 +50,7 @@
/**
* Constructs {@link ObjectContainer} from {@link Element}
*
- * @param element is Object
element
+ * @param element is {@code Object} element
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
*/
@@ -60,64 +59,63 @@
}
/**
- * Sets the Id
attribute
+ * Sets the {@code Id} attribute
*
- * @param Id Id
attribute
+ * @param Id {@code Id} attribute
*/
public void setId(String Id) {
if (Id != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
- this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute
+ * @return the {@code Id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
- * Sets the MimeType
attribute
+ * Sets the {@code MimeType} attribute
*
- * @param MimeType the MimeType
attribute
+ * @param MimeType the {@code MimeType} attribute
*/
public void setMimeType(String MimeType) {
if (MimeType != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType);
+ setLocalAttribute(Constants._ATT_MIMETYPE, MimeType);
}
}
/**
- * Returns the MimeType
attribute
+ * Returns the {@code MimeType} attribute
*
- * @return the MimeType
attribute
+ * @return the {@code MimeType} attribute
*/
public String getMimeType() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE);
+ return getLocalAttribute(Constants._ATT_MIMETYPE);
}
/**
- * Sets the Encoding
attribute
+ * Sets the {@code Encoding} attribute
*
- * @param Encoding the Encoding
attribute
+ * @param Encoding the {@code Encoding} attribute
*/
public void setEncoding(String Encoding) {
if (Encoding != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding);
+ setLocalAttribute(Constants._ATT_ENCODING, Encoding);
}
}
/**
- * Returns the Encoding
attribute
+ * Returns the {@code Encoding} attribute
*
- * @return the Encoding
attribute
+ * @return the {@code Encoding} attribute
*/
public String getEncoding() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING);
+ return getLocalAttribute(Constants._ATT_ENCODING);
}
/**
@@ -127,10 +125,11 @@
* @return the new node in the tree.
*/
public Node appendChild(Node node) {
- return this.constructionElement.appendChild(node);
+ appendSelf(node);
+ return node;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_OBJECT;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java
@@ -26,14 +26,15 @@
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
+import java.util.Base64;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
+import com.sun.org.apache.xml.internal.security.algorithms.Algorithm;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
-import com.sun.org.apache.xml.internal.security.exceptions.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;
@@ -44,7 +45,6 @@
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.InclusiveNamespaces;
-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.SignatureElementProxy;
@@ -59,11 +59,11 @@
import org.w3c.dom.Text;
/**
- * Handles <ds:Reference>
elements.
+ * Handles {@code <ds:Reference>} elements.
*
* This includes:
*
- * Constructs a ds:Reference
from an {@link org.w3c.dom.Element}.
+ * Construct a {@code ds:Reference} from an {@link org.w3c.dom.Element}.
*
*
@@ -100,7 +100,6 @@
* </complexType>
*
*
- * @author Christian Geuer-Pollmann
* @see ObjectContainer
* @see Manifest
*/
@@ -124,16 +123,12 @@
* 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 PrivilegedActionXMLsignature
is placed
+ * @param doc the {@link Document} in which {@code XMLsignature} is placed
* @param baseURI the URI of the resource where the XML instance will be stored
* @param referenceURI URI indicate where is data which will digested
* @param manifest
@@ -165,7 +160,7 @@
) throws XMLSignatureException {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
this.baseURI = baseURI;
this.manifest = manifest;
@@ -178,29 +173,39 @@
// this.manifest.appendChild(this.doc.createTextNode("\n"));
if (transforms != null) {
- this.transforms=transforms;
- this.constructionElement.appendChild(transforms.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ this.transforms = transforms;
+ appendSelf(transforms);
+ addReturnToSelf();
}
- MessageDigestAlgorithm mda =
- MessageDigestAlgorithm.getInstance(this.doc, messageDigestAlgorithm);
+
+ // Create DigestMethod Element without actually instantiating a MessageDigest Object
+ Algorithm digestAlgorithm = new Algorithm(getDocument(), messageDigestAlgorithm) {
+ public String getBaseNamespace() {
+ return Constants.SignatureSpecNS;
+ }
- digestMethodElem = mda.getElement();
- this.constructionElement.appendChild(digestMethodElem);
- XMLUtils.addReturnToElement(this.constructionElement);
+ public String getBaseLocalName() {
+ return Constants._TAG_DIGESTMETHOD;
+ }
+ };
+
+ digestMethodElem = digestAlgorithm.getElement();
+
+ appendSelf(digestMethodElem);
+ addReturnToSelf();
digestValueElement =
- XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_DIGESTVALUE);
+ XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_DIGESTVALUE);
- this.constructionElement.appendChild(digestValueElement);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(digestValueElement);
+ addReturnToSelf();
}
/**
* Build a {@link Reference} from an {@link Element}
*
- * @param element Reference
element
+ * @param element {@code Reference} element
* @param baseURI the URI of the resource where the XML instance was stored
* @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
* We need this because the Manifest has the individual {@link ResourceResolver}s which have
@@ -208,13 +213,13 @@
* @throws XMLSecurityException
*/
protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
- this(element, baseURI, manifest, false);
+ this(element, baseURI, manifest, true);
}
/**
* Build a {@link Reference} from an {@link Element}
*
- * @param element Reference
element
+ * @param element {@code Reference} element
* @param baseURI the URI of the resource where the XML instance was stored
* @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
* @param secureValidation whether secure validation is enabled or not
@@ -228,7 +233,8 @@
this.secureValidation = secureValidation;
this.baseURI = baseURI;
Element el = XMLUtils.getNextElement(element.getFirstChild());
- if (Constants._TAG_TRANSFORMS.equals(el.getLocalName())
+
+ if (el != null && Constants._TAG_TRANSFORMS.equals(el.getLocalName())
&& Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
transforms = new Transforms(el, this.baseURI);
transforms.setSecureValidation(secureValidation);
@@ -239,8 +245,16 @@
}
el = XMLUtils.getNextElement(el.getNextSibling());
}
+
digestMethodElem = el;
+ if (digestMethodElem == null) {
+ throw new XMLSecurityException("signature.Reference.NoDigestMethod");
+ }
+
digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
+ if (digestValueElement == null) {
+ throw new XMLSecurityException("signature.Reference.NoDigestValue");
+ }
this.manifest = manifest;
}
@@ -259,7 +273,7 @@
String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
- if (uri == null) {
+ if ("".equals(uri)) {
return null;
}
@@ -269,82 +283,81 @@
throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
}
- return MessageDigestAlgorithm.getInstance(this.doc, uri);
+ return MessageDigestAlgorithm.getInstance(getDocument(), uri);
}
/**
- * Sets the URI
of this Reference
element
+ * Sets the {@code URI} of this {@code Reference} element
*
- * @param uri the URI
of this Reference
element
+ * @param uri the {@code URI} of this {@code Reference} element
*/
public void setURI(String uri) {
if (uri != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
+ setLocalAttribute(Constants._ATT_URI, uri);
}
}
/**
- * Returns the URI
of this Reference
element
+ * Returns the {@code URI} of this {@code Reference} element
*
- * @return URI the URI
of this Reference
element
+ * @return URI the {@code URI} of this {@code Reference} element
*/
public String getURI() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
+ return getLocalAttribute(Constants._ATT_URI);
}
/**
- * Sets the Id
attribute of this Reference
element
+ * Sets the {@code Id} attribute of this {@code Reference} element
*
- * @param id the Id
attribute of this Reference
element
+ * @param id the {@code Id} attribute of this {@code Reference} element
*/
public void setId(String id) {
if (id != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
- this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ setLocalIdAttribute(Constants._ATT_ID, id);
}
}
/**
- * Returns the Id
attribute of this Reference
element
+ * Returns the {@code Id} attribute of this {@code Reference} element
*
- * @return Id the Id
attribute of this Reference
element
+ * @return Id the {@code Id} attribute of this {@code Reference} element
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
- * Sets the type
atttibute of the Reference indicate whether an
- * ds:Object
, ds:SignatureProperty
, or ds:Manifest
+ * Sets the {@code type} atttibute of the Reference indicate whether an
+ * {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest}
* element.
*
- * @param type the type
attribute of the Reference
+ * @param type the {@code type} attribute of the Reference
*/
public void setType(String type) {
if (type != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
+ setLocalAttribute(Constants._ATT_TYPE, type);
}
}
/**
- * Return the type
atttibute of the Reference indicate whether an
- * ds:Object
, ds:SignatureProperty
, or ds:Manifest
+ * Return the {@code type} atttibute of the Reference indicate whether an
+ * {@code ds:Object}, {@code ds:SignatureProperty}, or {@code ds:Manifest}
* element
*
- * @return the type
attribute of the Reference
+ * @return the {@code type} attribute of the Reference
*/
public String getType() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+ return getLocalAttribute(Constants._ATT_TYPE);
}
/**
* Method isReferenceToObject
*
- * This returns true if the Type
attribute of the
- * Reference
element points to a #Object
element
+ * This returns true if the {@code Type} attribute of the
+ * {@code Reference} element points to a {@code #Object} element
*
* @return true if the Reference type indicates that this Reference points to an
- * Object
+ * {@code Object}
*/
public boolean typeIsReferenceToObject() {
if (Reference.OBJECT_URI.equals(this.getType())) {
@@ -357,8 +370,8 @@
/**
* Method isReferenceToManifest
*
- * This returns true if the Type
attribute of the
- * Reference
element points to a #Manifest
element
+ * This returns true if the {@code Type} attribute of the
+ * {@code Reference} element points to a {@code #Manifest} element
*
* @return true if the Reference type indicates that this Reference points to a
* {@link Manifest}
@@ -383,8 +396,8 @@
n = n.getNextSibling();
}
- String base64codedValue = Base64.encode(digestValue);
- Text t = this.doc.createTextNode(base64codedValue);
+ String base64codedValue = Base64.getMimeEncoder().encodeToString(digestValue);
+ Text t = createText(base64codedValue);
digestValueElement.appendChild(t);
}
@@ -410,7 +423,7 @@
throws ReferenceNotInitializedException {
try {
Attr uriAttr =
- this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+ getElement().getAttributeNodeNS(null, Constants._ATT_URI);
ResourceResolver resolver =
ResourceResolver.getInstance(
@@ -420,7 +433,7 @@
return resolver.resolve(uriAttr, this.baseURI, secureValidation);
} catch (ResourceResolverException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
+ throw new ReferenceNotInitializedException(ex);
}
}
@@ -442,15 +455,15 @@
return output;
} catch (ResourceResolverException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (CanonicalizationException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (InvalidCanonicalizerException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (TransformationException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
}
}
@@ -483,35 +496,37 @@
Transforms transforms = this.getTransforms();
if (transforms != null) {
- doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+ 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;
+ || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)
+ || uri.equals(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS)
+ || uri.equals(Transforms.TRANSFORM_C14N11_WITH_COMMENTS)) {
+ break;
}
output = t.performTransform(output, null);
}
- output.setSourceURI(input.getSourceURI());
+ output.setSourceURI(input.getSourceURI());
}
return output;
} catch (IOException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (ResourceResolverException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (CanonicalizationException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (InvalidCanonicalizerException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (TransformationException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
}
}
@@ -528,23 +543,23 @@
Transform c14nTransform = null;
if (transforms != null) {
- doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+ 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;
+ break;
}
}
}
- SetURI
Attribute.
+ * {@code URI} Attribute.
* @param os where to write the transformation can be null.
* @return the element to digest
*
@@ -605,7 +620,7 @@
this.transformsOutput = output;
return output;
} catch (XMLSecurityException ex) {
- throw new ReferenceNotInitializedException("empty", ex);
+ throw new ReferenceNotInitializedException(ex);
}
}
@@ -622,14 +637,17 @@
Iterator<ds:SignatureProperties>
elements
- * This Element holds {@link SignatureProperty} that contian additional information items
+ * Handles {@code <ds:SignatureProperties>} elements
+ * This Element holds {@link SignatureProperty} properties that contain additional information items
* concerning the generation of the signature.
* for example, data-time stamp, serial number of cryptographic hardware.
*
- * @author Christian Geuer-Pollmann
*/
public class SignatureProperties extends SignatureElementProxy {
@@ -48,17 +47,17 @@
public SignatureProperties(Document doc) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
}
/**
* Constructs {@link SignatureProperties} from {@link Element}
- * @param element SignatureProperties
element
- * @param BaseURI the URI of the resource where the XML instance was stored
+ * @param element {@code SignatureProperties} element
+ * @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
*/
- public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public SignatureProperties(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
Attr attr = element.getAttributeNodeNS(null, "Id");
if (attr != null) {
@@ -68,7 +67,7 @@
int length = getLength();
for (int i = 0; i < length; i++) {
Element propertyElem =
- XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+ XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
if (propertyAttr != null) {
propertyElem.setIdAttributeNode(propertyAttr, true);
@@ -83,52 +82,51 @@
*/
public int getLength() {
Element[] propertyElems =
- XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
+ XMLUtils.selectDsNodes(getElement(), Constants._TAG_SIGNATUREPROPERTY);
return propertyElems.length;
}
/**
- * Return the i
- * values are 0 to {link@ getSize}-1
.
+ * Return the ith SignatureProperty. Valid {@code i}
+ * values are 0 to {@code {link@ getSize}-1}.
*
* @param i Index of the requested {@link SignatureProperty}
- * @return the Id
attribute
+ * Sets the {@code Id} attribute
*
- * @param Id the Id
attribute
+ * @param Id the {@code Id} attribute
*/
public void setId(String Id) {
if (Id != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
- this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute
+ * @return the {@code Id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
@@ -137,11 +135,11 @@
* @param sp
*/
public void addSignatureProperty(SignatureProperty sp) {
- this.constructionElement.appendChild(sp.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(sp);
+ addReturnToSelf();
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_SIGNATUREPROPERTIES;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
@@ -30,19 +30,18 @@
import org.w3c.dom.Node;
/**
- * Handles <ds:SignatureProperty>
elements
+ * Handles {@code <ds:SignatureProperty>} elements
* Additional information item concerning the generation of the signature(s) can
* be placed in this Element
*
- * @author Christian Geuer-Pollmann
*/
public class SignatureProperty extends SignatureElementProxy {
/**
- * Constructs{@link SignatureProperty} using specified target
attribute
+ * Constructs{@link SignatureProperty} using specified {@code target} attribute
*
- * @param doc the {@link Document} in which XMLsignature
is placed
- * @param target the target
attribute references the Signature
+ * @param doc the {@link Document} in which {@code XMLsignature} is placed
+ * @param target the {@code target} attribute references the {@code Signature}
* element to which the property applies SignatureProperty
*/
public SignatureProperty(Document doc, String target) {
@@ -50,13 +49,13 @@
}
/**
- * Constructs {@link SignatureProperty} using sepcified target
attribute and
- * id
attribute
+ * Constructs {@link SignatureProperty} using sepcified {@code target} attribute and
+ * {@code id} attribute
*
- * @param doc the {@link Document} in which XMLsignature
is placed
- * @param target the target
attribute references the Signature
+ * @param doc the {@link Document} in which {@code XMLsignature} is placed
+ * @param target the {@code target} attribute references the {@code Signature}
* element to which the property applies
- * @param id the id
will be specified by {@link Reference#getURI} in validation
+ * @param id the {@code id} will be specified by {@link Reference#getURI} in validation
*/
public SignatureProperty(Document doc, String target, String id) {
super(doc);
@@ -67,53 +66,52 @@
/**
* Constructs a {@link SignatureProperty} from an {@link Element}
- * @param element SignatureProperty
element
- * @param BaseURI the URI of the resource where the XML instance was stored
+ * @param element {@code SignatureProperty} element
+ * @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
*/
- public SignatureProperty(Element element, String BaseURI) throws XMLSecurityException {
- super(element, BaseURI);
+ public SignatureProperty(Element element, String baseURI) throws XMLSecurityException {
+ super(element, baseURI);
}
/**
- * Sets the id
attribute
+ * Sets the {@code id} attribute
*
- * @param id the id
attribute
+ * @param id the {@code id} attribute
*/
public void setId(String id) {
if (id != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
- this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ setLocalIdAttribute(Constants._ATT_ID, id);
}
}
/**
- * Returns the id
attribute
+ * Returns the {@code id} attribute
*
- * @return the id
attribute
+ * @return the {@code id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
- * Sets the target
attribute
+ * Sets the {@code target} attribute
*
- * @param target the target
attribute
+ * @param target the {@code target} attribute
*/
public void setTarget(String target) {
if (target != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
+ setLocalAttribute(Constants._ATT_TARGET, target);
}
}
/**
- * Returns the target
attribute
+ * Returns the {@code target} attribute
*
- * @return the target
attribute
+ * @return the {@code target} attribute
*/
public String getTarget() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
+ return getLocalAttribute(Constants._ATT_TARGET);
}
/**
@@ -123,10 +121,11 @@
* @return the node in this element.
*/
public Node appendChild(Node node) {
- return this.constructionElement.appendChild(node);
+ appendSelf(node);
+ return node;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_SIGNATUREPROPERTY;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
@@ -24,10 +24,11 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
+
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
-import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
@@ -35,28 +36,27 @@
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
+import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
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.transforms.params.InclusiveNamespaces;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
- * Handles <ds:SignedInfo>
elements
- * This SignedInfo
element includes the canonicalization algorithm,
+ * Handles {@code <ds:SignedInfo>} elements
+ * This {@code SignedInfo} element includes the canonicalization algorithm,
* a signature algorithm, and one or more references.
*
- * @author Christian Geuer-Pollmann
*/
public class SignedInfo extends Manifest {
/** Field signatureAlgorithm */
- private SignatureAlgorithm signatureAlgorithm = null;
+ private SignatureAlgorithm signatureAlgorithm;
/** Field c14nizedBytes */
- private byte[] c14nizedBytes = null;
+ private byte[] c14nizedBytes;
private Element c14nMethod;
private Element signatureMethod;
@@ -65,7 +65,7 @@
* Overwrites {@link Manifest#addDocument} because it creates another
* Element.
*
- * @param doc the {@link Document} in which
XMLsignature
will
+ * @param doc the {@link Document} in which {@code XMLsignature} will
* be placed
* @throws XMLSecurityException
*/
@@ -78,7 +78,7 @@
* Constructs {@link SignedInfo} using given Canonicalization algorithm and
* Signature algorithm.
*
- * @param doc SignedInfo
is placed in this document
+ * @param doc {@code SignedInfo} is placed in this document
* @param signatureMethodURI URI representation of the Digest and
* Signature algorithm
* @param canonicalizationMethodURI URI representation of the
@@ -94,7 +94,7 @@
/**
* Constructor SignedInfo
*
- * @param doc SignedInfo
is placed in this document
+ * @param doc {@code SignedInfo} is placed in this document
* @param signatureMethodURI URI representation of the Digest and
* Signature algorithm
* @param hMACOutputLength
@@ -109,22 +109,22 @@
super(doc);
c14nMethod =
- XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
+ XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_CANONICALIZATIONMETHOD);
c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
- this.constructionElement.appendChild(c14nMethod);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(c14nMethod);
+ addReturnToSelf();
if (hMACOutputLength > 0) {
this.signatureAlgorithm =
- new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
+ new SignatureAlgorithm(getDocument(), signatureMethodURI, hMACOutputLength);
} else {
- this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
+ this.signatureAlgorithm = new SignatureAlgorithm(getDocument(), signatureMethodURI);
}
signatureMethod = this.signatureAlgorithm.getElement();
- this.constructionElement.appendChild(signatureMethod);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(signatureMethod);
+ addReturnToSelf();
}
/**
@@ -139,22 +139,22 @@
super(doc);
// Check this?
this.c14nMethod = canonicalizationMethodElem;
- this.constructionElement.appendChild(c14nMethod);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(c14nMethod);
+ addReturnToSelf();
this.signatureAlgorithm =
new SignatureAlgorithm(signatureMethodElem, null);
signatureMethod = this.signatureAlgorithm.getElement();
- this.constructionElement.appendChild(signatureMethod);
+ appendSelf(signatureMethod);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
}
/**
* Build a {@link SignedInfo} from an {@link Element}
*
- * @param element SignedInfo
+ * @param element {@code SignedInfo}
* @param baseURI the URI of the resource where the XML instance was stored
* @throws XMLSecurityException
* @see
@@ -163,13 +163,13 @@
* Answer
*/
public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
- this(element, baseURI, false);
+ this(element, baseURI, true);
}
/**
* Build a {@link SignedInfo} from an {@link Element}
*
- * @param element SignedInfo
+ * @param element {@code SignedInfo}
* @param baseURI the URI of the resource where the XML instance was stored
* @param secureValidation whether secure validation is enabled or not
* @throws XMLSecurityException
@@ -182,7 +182,7 @@
Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
// Parse the Reference children and Id attribute in the Manifest
- super(reparseSignedInfoElem(element), baseURI, secureValidation);
+ super(reparseSignedInfoElem(element, secureValidation), baseURI, secureValidation);
c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
@@ -190,7 +190,7 @@
new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation);
}
- private static Element reparseSignedInfoElem(Element element)
+ private static Element reparseSignedInfoElem(Element element, boolean secureValidation)
throws XMLSecurityException {
/*
* If a custom canonicalizationMethod is used, canonicalize
@@ -212,27 +212,24 @@
try {
Canonicalizer c14nizer =
Canonicalizer.getInstance(c14nMethodURI);
+ c14nizer.setSecureValidation(secureValidation);
byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
- javax.xml.parsers.DocumentBuilderFactory dbf =
- javax.xml.parsers.DocumentBuilderFactory.newInstance();
- dbf.setNamespaceAware(true);
- dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
- javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
- Document newdoc =
- db.parse(new ByteArrayInputStream(c14nizedBytes));
- Node imported =
- element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
-
- element.getParentNode().replaceChild(imported, element);
-
- return (Element) imported;
+ javax.xml.parsers.DocumentBuilder db =
+ XMLUtils.createDocumentBuilder(false, secureValidation);
+ try (InputStream is = new ByteArrayInputStream(c14nizedBytes)) {
+ Document newdoc = db.parse(is);
+ Node imported = element.getOwnerDocument().importNode(
+ newdoc.getDocumentElement(), true);
+ element.getParentNode().replaceChild(imported, element);
+ return (Element) imported;
+ }
} catch (ParserConfigurationException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
} catch (IOException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
} catch (SAXException ex) {
- throw new XMLSecurityException("empty", ex);
+ throw new XMLSecurityException(ex);
}
}
return element;
@@ -253,7 +250,7 @@
/**
* Tests core validation process
*
- * @param followManifests defines whether the verification process has to verify referenced ds:Manifest
s, too
+ * @param followManifests defines whether the verification process has to verify referenced {@code ds:Manifest}s, too
* @return true if verification was successful
* @throws MissingResourceFailureException
* @throws XMLSecurityException
@@ -266,7 +263,7 @@
/**
* Returns getCanonicalizedOctetStream
*
- * @return the canonicalization result octet stream of SignedInfo
element
+ * @return the canonicalization result octet stream of {@code SignedInfo} element
* @throws CanonicalizationException
* @throws InvalidCanonicalizerException
* @throws XMLSecurityException
@@ -276,9 +273,14 @@
if (this.c14nizedBytes == null) {
Canonicalizer c14nizer =
Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+ c14nizer.setSecureValidation(isSecureValidation());
- this.c14nizedBytes =
- c14nizer.canonicalizeSubtree(this.constructionElement);
+ String inclusiveNamespaces = this.getInclusiveNamespaces();
+ if (inclusiveNamespaces == null) {
+ this.c14nizedBytes = c14nizer.canonicalizeSubtree(getElement());
+ } else {
+ this.c14nizedBytes = c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces);
+ }
}
// make defensive copy
@@ -297,13 +299,14 @@
if (this.c14nizedBytes == null) {
Canonicalizer c14nizer =
Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+ c14nizer.setSecureValidation(isSecureValidation());
c14nizer.setWriter(os);
String inclusiveNamespaces = this.getInclusiveNamespaces();
if (inclusiveNamespaces == null) {
- c14nizer.canonicalizeSubtree(this.constructionElement);
+ c14nizer.canonicalizeSubtree(getElement());
} else {
- c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
+ c14nizer.canonicalizeSubtree(getElement(), inclusiveNamespaces);
}
} else {
try {
@@ -358,13 +361,13 @@
return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
}
- protected SignatureAlgorithm getSignatureAlgorithm() {
+ public SignatureAlgorithm getSignatureAlgorithm() {
return signatureAlgorithm;
}
/**
* Method getBaseLocalName
- * @inheritDoc
+ * {@inheritDoc}
*
*/
public String getBaseLocalName() {
@@ -372,7 +375,7 @@
}
public String getInclusiveNamespaces() {
- String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ String c14nMethodURI = getCanonicalizationMethodURI();
if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
return null;
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
@@ -27,6 +27,7 @@
import java.security.Key;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
+import java.util.Base64;
import javax.crypto.SecretKey;
@@ -34,12 +35,10 @@
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
-import com.sun.org.apache.xml.internal.security.exceptions.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.content.X509Data;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
-import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.I18n;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
@@ -52,11 +51,10 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
- * Handles <ds:Signature>
elements.
+ * Handles {@code <ds:Signature>} elements.
* This is the main class that deals with creating and verifying signatures.
*
* ds:Signature
Element and adds an empty
- * ds:SignedInfo
.
- * The ds:SignedInfo
is initialized with the specified Signature
+ * This creates a new {@code ds:Signature} Element and adds an empty
+ * {@code ds:SignedInfo}.
+ * The {@code ds:SignedInfo} is initialized with the specified Signature
* algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED
* by the spec. This method's main use is for creating a new signature.
*
@@ -250,31 +283,31 @@
String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
- this.constructionElement.setAttributeNS(
+ getElement().setAttributeNS(
Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
);
} else {
- this.constructionElement.setAttributeNS(
+ getElement().setAttributeNS(
Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
);
}
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
this.baseURI = baseURI;
this.signedInfo =
new SignedInfo(
- this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI
+ getDocument(), signatureMethodURI, hmacOutputLength, canonicalizationMethodURI
);
- this.constructionElement.appendChild(this.signedInfo.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(this.signedInfo);
+ addReturnToSelf();
// create an empty SignatureValue; this is filled by setSignatureValueElement
signatureValueElement =
- XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
+ XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_SIGNATUREVALUE);
- this.constructionElement.appendChild(signatureValueElement);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(signatureValueElement);
+ addReturnToSelf();
}
/**
@@ -295,29 +328,29 @@
String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS);
if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) {
- this.constructionElement.setAttributeNS(
+ getElement().setAttributeNS(
Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS
);
} else {
- this.constructionElement.setAttributeNS(
+ getElement().setAttributeNS(
Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS
);
}
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
this.baseURI = baseURI;
this.signedInfo =
- new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem);
+ new SignedInfo(getDocument(), SignatureMethodElem, CanonicalizationMethodElem);
- this.constructionElement.appendChild(this.signedInfo.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(this.signedInfo);
+ addReturnToSelf();
// create an empty SignatureValue; this is filled by setSignatureValueElement
signatureValueElement =
- XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE);
+ XMLUtils.createElementInSignatureSpace(getDocument(), Constants._TAG_SIGNATUREVALUE);
- this.constructionElement.appendChild(signatureValueElement);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(signatureValueElement);
+ addReturnToSelf();
}
/**
@@ -331,7 +364,7 @@
*/
public XMLSignature(Element element, String baseURI)
throws XMLSignatureException, XMLSecurityException {
- this(element, baseURI, false);
+ this(element, baseURI, true);
}
/**
@@ -382,8 +415,8 @@
// If it exists use it, but it's not mandatory
if (keyInfoElem != null
- && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS)
- && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) {
+ && Constants.SignatureSpecNS.equals(keyInfoElem.getNamespaceURI())
+ && Constants._TAG_KEYINFO.equals(keyInfoElem.getLocalName())) {
this.keyInfo = new KeyInfo(keyInfoElem, baseURI);
this.keyInfo.setSecureValidation(secureValidation);
}
@@ -397,20 +430,19 @@
objectElem.setIdAttributeNode(objectAttr, true);
}
- NodeList nodes = objectElem.getChildNodes();
- int length = nodes.getLength();
+ Node firstChild = objectElem.getFirstChild();
// 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;
+ while (firstChild != null) {
+ if (firstChild.getNodeType() == Node.ELEMENT_NODE) {
+ Element childElem = (Element)firstChild;
String tag = childElem.getLocalName();
- if (tag.equals("Manifest")) {
+ if ("Manifest".equals(tag)) {
new Manifest(childElem, baseURI);
- } else if (tag.equals("SignatureProperties")) {
+ } else if ("SignatureProperties".equals(tag)) {
new SignatureProperties(childElem, baseURI);
}
}
+ firstChild = firstChild.getNextSibling();
}
objectElem = XMLUtils.getNextElement(objectElem.getNextSibling());
@@ -420,30 +452,29 @@
}
/**
- * Sets the Id
attribute
+ * Sets the {@code Id} attribute
*
* @param id Id value for the id attribute on the Signature Element
*/
public void setId(String id) {
if (id != null) {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
- this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+ setLocalIdAttribute(Constants._ATT_ID, id);
}
}
/**
- * Returns the Id
attribute
+ * Returns the {@code Id} attribute
*
- * @return the Id
attribute
+ * @return the {@code Id} attribute
*/
public String getId() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+ return getLocalAttribute(Constants._ATT_ID);
}
/**
- * Returns the completely parsed SignedInfo
object.
+ * Returns the completely parsed {@code SignedInfo} object.
*
- * @return the completely parsed SignedInfo
object.
+ * @return the completely parsed {@code SignedInfo} object.
*/
public SignedInfo getSignedInfo() {
return this.signedInfo;
@@ -457,11 +488,8 @@
* @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);
- }
+ String content = XMLUtils.getFullTextChildrenFromElement(signatureValueElement);
+ return Base64.getMimeDecoder().decode(content);
}
/**
@@ -476,13 +504,13 @@
signatureValueElement.removeChild(signatureValueElement.getFirstChild());
}
- String base64codedValue = Base64.encode(bytes);
+ String base64codedValue = Base64.getMimeEncoder().encodeToString(bytes);
if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
base64codedValue = "\n" + base64codedValue + "\n";
}
- Text t = this.doc.createTextNode(base64codedValue);
+ Text t = createText(base64codedValue);
signatureValueElement.appendChild(t);
}
@@ -499,23 +527,23 @@
if (this.state == MODE_SIGN && this.keyInfo == null) {
// create the KeyInfo
- this.keyInfo = new KeyInfo(this.doc);
+ this.keyInfo = new KeyInfo(getDocument());
// get the Element from KeyInfo
Element keyInfoElement = this.keyInfo.getElement();
Element firstObject =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, 0
+ getElement().getFirstChild(), Constants._TAG_OBJECT, 0
);
if (firstObject != null) {
// add it before the object
- this.constructionElement.insertBefore(keyInfoElement, firstObject);
- XMLUtils.addReturnBeforeChild(this.constructionElement, firstObject);
+ getElement().insertBefore(keyInfoElement, firstObject);
+ XMLUtils.addReturnBeforeChild(getElement(), firstObject);
} else {
// add it as the last element to the signature
- this.constructionElement.appendChild(keyInfoElement);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(keyInfoElement);
+ addReturnToSelf();
}
}
@@ -523,7 +551,7 @@
}
/**
- * Appends an Object (not a java.lang.Object
but an Object
+ * Appends an Object (not a {@code java.lang.Object} but an Object
* element) to the Signature. Please note that this is only possible
* when signing.
*
@@ -537,25 +565,25 @@
// "signature.operationOnlyBeforeSign");
//}
- this.constructionElement.appendChild(object.getElement());
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(object);
+ addReturnToSelf();
//} catch (XMLSecurityException ex) {
- // throw new XMLSignatureException("empty", ex);
+ // throw new XMLSignatureException(ex);
//}
}
/**
- * Returns the i
th
ds:Object
child of the signature
- * or null if no such ds:Object
element exists.
+ * Returns the {@code i}th {@code ds:Object} child of the signature
+ * or null if no such {@code ds:Object} element exists.
*
* @param i
- * @return the i
th
ds:Object
child of the signature
- * or null if no such ds:Object
element exists.
+ * @return the {@code i}th {@code ds:Object} child of the signature
+ * or null if no such {@code ds:Object} element exists.
*/
public ObjectContainer getObjectItem(int i) {
Element objElem =
XMLUtils.selectDsNode(
- this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i
+ getFirstChild(), Constants._TAG_OBJECT, i
);
try {
@@ -566,9 +594,9 @@
}
/**
- * Returns the number of all ds:Object
elements.
+ * Returns the number of all {@code ds:Object} elements.
*
- * @return the number of all ds:Object
elements.
+ * @return the number of all {@code ds:Object} elements.
*/
public int getObjectLength() {
return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT);
@@ -590,44 +618,33 @@
);
}
- try {
- //Create a SignatureAlgorithm object
- SignedInfo si = this.getSignedInfo();
- SignatureAlgorithm sa = si.getSignatureAlgorithm();
- OutputStream so = null;
- try {
- // initialize SignatureAlgorithm for signing
- sa.initSign(signingKey);
+ //Create a SignatureAlgorithm object
+ SignedInfo si = this.getSignedInfo();
+ SignatureAlgorithm sa = si.getSignatureAlgorithm();
+ try (SignerOutputStream output = new SignerOutputStream(sa);
+ OutputStream so = new UnsyncBufferedOutputStream(output)) {
- // 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);
- }
- }
- }
- }
+ // generate digest values for all References in this SignedInfo
+ si.generateDigestValues();
+
+ // initialize SignatureAlgorithm for signing
+ sa.initSign(signingKey);
+
+ // get the canonicalized bytes from SignedInfo
+ si.signInOctetStream(so);
// set them on the SignatureValue element
this.setSignatureValueElement(sa.sign());
} catch (XMLSignatureException ex) {
throw ex;
} catch (CanonicalizationException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (InvalidCanonicalizerException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
} catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
+ } catch (IOException ex) {
+ throw new XMLSignatureException(ex);
}
}
@@ -699,28 +716,23 @@
//create a SignatureAlgorithms from the SignatureMethod inside
//SignedInfo. This is used to validate the signature.
SignatureAlgorithm sa = si.getSignatureAlgorithm();
+ LOG.debug("signatureMethodURI = {}", sa.getAlgorithmURI());
+ LOG.debug("jceSigAlgorithm = {}", sa.getJCEAlgorithmString());
+ LOG.debug("jceSigProvider = {}", sa.getJCEProviderName());
+ LOG.debug("PublicKey = {}", pk);
+
byte sigBytes[] = null;
- try {
+ try (SignerOutputStream so = new SignerOutputStream(sa);
+ OutputStream bos = new UnsyncBufferedOutputStream(so)) {
+
sa.initVerify(pk);
- 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);
- }
// Get the canonicalized (normalized) SignedInfo
- SignerOutputStream so = new SignerOutputStream(sa);
- OutputStream bos = new UnsyncBufferedOutputStream(so);
-
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);
- }
+ LOG.debug(ex.getMessage(), ex);
// Impossible...
} catch (XMLSecurityException ex) {
throw ex;
@@ -729,7 +741,7 @@
// 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.");
+ LOG.warn("Signature verification failed.");
return false;
}
@@ -737,7 +749,7 @@
} catch (XMLSignatureException ex) {
throw ex;
} catch (XMLSecurityException ex) {
- throw new XMLSignatureException("empty", ex);
+ throw new XMLSignatureException(ex);
}
}
@@ -820,7 +832,7 @@
* @throws XMLSecurityException
*/
public void addKeyInfo(X509Certificate cert) throws XMLSecurityException {
- X509Data x509data = new X509Data(this.doc);
+ X509Data x509data = new X509Data(getDocument());
x509data.addCertificate(cert);
this.getKeyInfo().add(x509data);
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java
@@ -28,7 +28,6 @@
* All XML Signature related exceptions inherit herefrom.
*
* @see MissingResourceFailureException InvalidDigestValueException InvalidSignatureValueException
- * @author Christian Geuer-Pollmann
*/
public class XMLSignatureException extends XMLSecurityException {
@@ -45,6 +44,10 @@
super();
}
+ public XMLSignatureException(Exception ex) {
+ super(ex);
+ }
+
/**
* Constructor XMLSignatureException
*
@@ -67,21 +70,31 @@
/**
* Constructor XMLSignatureException
*
+ * @param originalException
* @param msgID
- * @param originalException
*/
+ public XMLSignatureException(Exception originalException, String msgID) {
+ super(originalException, msgID);
+ }
+
+ @Deprecated
public XMLSignatureException(String msgID, Exception originalException) {
- super(msgID, originalException);
+ this(originalException, msgID);
}
/**
* Constructor XMLSignatureException
*
+ * @param originalException
* @param msgID
* @param exArgs
- * @param originalException
*/
- public XMLSignatureException(String msgID, Object exArgs[], Exception originalException) {
- super(msgID, exArgs, originalException);
+ public XMLSignatureException(Exception originalException, String msgID, Object exArgs[]) {
+ super(originalException, msgID, exArgs);
+ }
+
+ @Deprecated
+ public XMLSignatureException(String msgID, Object[] exArgs, Exception originalException) {
+ this(originalException, msgID, exArgs);
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java
@@ -27,20 +27,19 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
-import javax.xml.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;
-import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerBase;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer20010315OmitComments;
-import com.sun.org.apache.xml.internal.security.c14n.implementations.Canonicalizer11_OmitComments;
+import com.sun.org.apache.xml.internal.security.c14n.implementations.CanonicalizerBase;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
@@ -51,7 +50,6 @@
/**
* Class XMLSignatureInput
*
- * @author Christian Geuer-Pollmann
* $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set?
*/
public class XMLSignatureInput {
@@ -68,19 +66,19 @@
* Some InputStreams do not support the {@link java.io.InputStream#reset}
* method, so we read it in completely and work on our Proxy.
*/
- private InputStream inputOctetStreamProxy = null;
+ private InputStream inputOctetStreamProxy;
/**
* The original NodeSet for this XMLSignatureInput
*/
- private SetXMLSignatureInput
from an octet stream. The
+ * Constructs a {@code XMLSignatureInput} from an octet stream. The
* stream is directly read.
*
* @param inputOctetStream
@@ -161,6 +163,15 @@
}
/**
+ * Construct a {@code XMLSignatureInput} from a known digest value in Base64.
+ * This makes it possible to compare the element digest with the provided digest value.
+ * @param preCalculatedDigest digest value in base64.
+ */
+ public XMLSignatureInput(String preCalculatedDigest) {
+ this.preCalculatedDigest = preCalculatedDigest;
+ }
+
+ /**
* Check if the structure needs to be expanded.
* @return true if so.
*/
@@ -286,8 +297,7 @@
* @return true if the object has been set up with a Node set
*/
public boolean isNodeSet() {
- return ((inputOctetStreamProxy == null
- && inputNodeSet != null) || isNodeSet);
+ return inputOctetStreamProxy == null && inputNodeSet != null || isNodeSet;
}
/**
@@ -296,8 +306,8 @@
* @return true if the object has been set up with an Element
*/
public boolean isElement() {
- return (inputOctetStreamProxy == null && subNode != null
- && inputNodeSet == null && !isNodeSet);
+ return inputOctetStreamProxy == null && subNode != null
+ && inputNodeSet == null && !isNodeSet;
}
/**
@@ -306,8 +316,8 @@
* @return true if the object has been set up with an octet stream
*/
public boolean isOctetStream() {
- return ((inputOctetStreamProxy != null || bytes != null)
- && (inputNodeSet == null && subNode == null));
+ return (inputOctetStreamProxy != null || bytes != null)
+ && inputNodeSet == null && subNode == null;
}
/**
@@ -327,7 +337,15 @@
* @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;
+ }
+
+ /**
+ * Determines if the object has been set up with a pre-calculated digest.
+ * @return
+ */
+ public boolean isPreCalculatedDigest() {
+ return preCalculatedDigest != null;
}
/**
@@ -377,7 +395,7 @@
/**
* Method toString
- * @inheritDoc
+ * {@inheritDoc}
*/
public String toString() {
if (isNodeSet()) {
@@ -556,13 +574,7 @@
void convertToNodes() throws CanonicalizationException,
ParserConfigurationException, IOException, SAXException {
- if (dfactory == null) {
- dfactory = DocumentBuilderFactory.newInstance();
- dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
- dfactory.setValidating(false);
- dfactory.setNamespaceAware(true);
- }
- DocumentBuilder db = dfactory.newDocumentBuilder();
+ DocumentBuilder db = XMLUtils.createDocumentBuilder(false, secureValidation);
// select all nodes, also the comments.
try {
db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
@@ -570,16 +582,20 @@
Document doc = db.parse(this.getOctetStream());
this.subNode = doc;
} catch (SAXException ex) {
+ byte[] result = null;
// if a not-wellformed nodeset exists, put a container around it...
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
- baos.write("
- *
*
* @param name
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/package.html
deleted file mode 100644
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/package.html
+++ /dev/null
@@ -1,3 +0,0 @@
-&
<
"
#x9
, #xA, and #xD,
+ * #xD
- * is represented by the character reference 
)ReferenceData
type containing a node-set.
+ * An abstract representation of a {@code ReferenceData} type containing a node-set.
*/
public interface ReferenceNodeSetData extends ReferenceData {
/**
* Returns a read-only iterator over the nodes contained in this
- * NodeSetData
in
+ * {@code NodeSetData} in
*
* document order. Attempts to modify the returned iterator
- * via the remove
method throw
- * UnsupportedOperationException
.
+ * via the {@code remove} method throw
+ * {@code UnsupportedOperationException}.
*
- * @return an Iterator
over the nodes in this
- * NodeSetData
in document order
+ * @return an {@code Iterator} over the nodes in this
+ * {@code NodeSetData} in document order
*/
IteratorReferenceData
type containing an OctetStream.
+ * A representation of a {@code ReferenceData} type containing an OctetStream.
*/
public class ReferenceOctetStreamData implements ReferenceData {
private InputStream octetStream;
@@ -39,11 +39,11 @@
private String mimeType;
/**
- * Creates a new ReferenceOctetStreamData
.
+ * Creates a new {@code ReferenceOctetStreamData}.
*
* @param octetStream the input stream containing the octets
- * @throws NullPointerException if octetStream
is
- * null
+ * @throws NullPointerException if {@code octetStream} is
+ * {@code null}
*/
public ReferenceOctetStreamData(InputStream octetStream) {
if (octetStream == null) {
@@ -53,15 +53,15 @@
}
/**
- * Creates a new ReferenceOctetStreamData
.
+ * Creates a new {@code ReferenceOctetStreamData}.
*
* @param octetStream the input stream containing the octets
* @param uri the URI String identifying the data object (may be
- * null
)
+ * {@code null})
* @param mimeType the MIME type associated with the data object (may be
- * null
)
- * @throws NullPointerException if octetStream
is
- * null
+ * {@code null})
+ * @throws NullPointerException if {@code octetStream} is
+ * {@code null}
*/
public ReferenceOctetStreamData(InputStream octetStream, String uri,
String mimeType) {
@@ -74,9 +74,9 @@
}
/**
- * Returns the input stream of this ReferenceOctetStreamData
.
+ * Returns the input stream of this {@code ReferenceOctetStreamData}.
*
- * @return the input stream of this ReferenceOctetStreamData
.
+ * @return the input stream of this {@code ReferenceOctetStreamData}.
*/
public InputStream getOctetStream() {
return octetStream;
@@ -84,9 +84,9 @@
/**
* Returns the URI String identifying the data object represented by this
- * ReferenceOctetStreamData
.
+ * {@code ReferenceOctetStreamData}.
*
- * @return the URI String or null
if not applicable
+ * @return the URI String or {@code null} if not applicable
*/
public String getURI() {
return uri;
@@ -94,9 +94,9 @@
/**
* Returns the MIME type associated with the data object represented by this
- * ReferenceOctetStreamData
.
+ * {@code ReferenceOctetStreamData}.
*
- * @return the MIME type or null
if not applicable
+ * @return the MIME type or {@code null} if not applicable
*/
public String getMimeType() {
return mimeType;
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java
@@ -21,7 +21,7 @@
* under the License.
*/
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id$
@@ -37,7 +37,7 @@
import org.w3c.dom.Node;
/**
- * A representation of a ReferenceNodeSetData
type containing a node-set.
+ * A representation of a {@code ReferenceNodeSetData} type containing a node-set.
* This is a subtype of NodeSetData that represents a dereferenced
* same-document URI as the root of a subdocument. The main reason is
* for efficiency and performance, as some transforms can operate
@@ -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
- *
- *
- * @param resourceName The name of the resource to load
- * @param callingClass The Class object of the calling object
- */
- static URL getResource(String resourceName, Class> callingClass) {
- URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
- if (url == null && resourceName.startsWith("/")) {
- //certain classloaders need it without the leading /
- url =
- Thread.currentThread().getContextClassLoader().getResource(
- resourceName.substring(1)
- );
- }
-
- ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader();
- if (cluClassloader == null) {
- cluClassloader = ClassLoader.getSystemClassLoader();
- }
- if (url == null) {
- url = cluClassloader.getResource(resourceName);
- }
- if (url == null && resourceName.startsWith("/")) {
- //certain classloaders need it without the leading /
- url = cluClassloader.getResource(resourceName.substring(1));
- }
-
- if (url == null) {
- ClassLoader cl = callingClass.getClassLoader();
-
- if (cl != null) {
- url = cl.getResource(resourceName);
- }
- }
-
- if (url == null) {
- url = callingClass.getResource(resourceName);
- }
-
- if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
- return getResource('/' + resourceName, callingClass);
- }
-
- return url;
- }
-
- /**
- * Load a given resources. This method will try to load the resources
- * using the following methods (in order):
- *
- *
- *
- * @param resourceName The name of the resource to load
- * @param callingClass The Class object of the calling object
- */
- static List
*
ds:Transform
element.
+ * Implements the behaviour of the {@code ds:Transform} element.
*
- * This Transform
(Factory) class acts as the Factory and Proxy of
+ * This {@code Transform}(Factory) class acts as the Factory and Proxy of
* the implementing class that supports the functionality of a Transform
* algorithm.
* Implements the Factory and Proxy pattern for ds:Transform algorithms.
*
- * @author Christian Geuer-Pollmann
* @see Transforms
* @see TransformSpi
*/
public final class Transform extends SignatureElementProxy {
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(Transform.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(Transform.class);
/** All available Transform classes are registered here */
private static MapTransform algorithm
URI.
+ * {@code Transform algorithm} URI.
*
* @param doc the proxy {@link Document}
- * @param algorithmURI Transform algorithm
URI representation,
+ * @param algorithmURI {@code Transform algorithm} URI representation,
* such as specified in
* Transform algorithm
* @throws InvalidTransformException
@@ -95,12 +94,12 @@
/**
* Generates a Transform object that implements the specified
- * Transform algorithm
URI.
+ * {@code Transform algorithm} URI.
*
- * @param algorithmURI Transform algorithm
URI representation,
+ * @param algorithmURI {@code Transform algorithm} URI representation,
* such as specified in
* Transform algorithm
- * @param contextChild the child element of Transform
element
+ * @param contextChild the child element of {@code Transform} element
* @param doc the proxy {@link Document}
* @throws InvalidTransformException
*/
@@ -123,10 +122,10 @@
/**
* Constructs {@link Transform}
*
- * @param doc the {@link Document} in which Transform
will be
+ * @param doc the {@link Document} in which {@code Transform} will be
* placed
- * @param algorithmURI URI representation of Transform algorithm
- * @param contextNodes the child node list of Transform
element
+ * @param algorithmURI URI representation of {@code Transform algorithm}
+ * @param contextNodes the child node list of {@code Transform} element
* @throws InvalidTransformException
*/
public Transform(Document doc, String algorithmURI, NodeList contextNodes)
@@ -136,15 +135,15 @@
}
/**
- * @param element ds:Transform
element
- * @param BaseURI the URI of the resource where the XML instance was stored
+ * @param element {@code ds:Transform} element
+ * @param baseURI the URI of the resource where the XML instance was stored
* @throws InvalidTransformException
* @throws TransformationException
* @throws XMLSecurityException
*/
- public Transform(Element element, String BaseURI)
+ public Transform(Element element, String baseURI)
throws InvalidTransformException, TransformationException, XMLSecurityException {
- super(element, BaseURI);
+ super(element, baseURI);
// retrieve Algorithm Attribute from ds:Transform
String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);
@@ -164,12 +163,12 @@
} catch (InstantiationException ex) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
- "signature.Transform.UnknownTransform", exArgs, ex
+ ex, "signature.Transform.UnknownTransform", exArgs
);
} catch (IllegalAccessException ex) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
- "signature.Transform.UnknownTransform", exArgs, ex
+ ex, "signature.Transform.UnknownTransform", exArgs
);
}
}
@@ -177,8 +176,8 @@
/**
* Registers implementing class of the Transform algorithm with algorithmURI
*
- * @param algorithmURI algorithmURI URI representation of Transform algorithm
- * @param implementingClass implementingClass
the implementing
+ * @param algorithmURI algorithmURI URI representation of {@code Transform algorithm}
+ * @param implementingClass {@code implementingClass} the implementing
* class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
@@ -205,8 +204,8 @@
/**
* Registers implementing class of the Transform algorithm with algorithmURI
*
- * @param algorithmURI algorithmURI URI representation of Transform algorithm
- * @param implementingClass implementingClass
the implementing
+ * @param algorithmURI algorithmURI URI representation of {@code Transform algorithm}
+ * @param implementingClass {@code implementingClass} the implementing
* class of {@link TransformSpi}
* @throws AlgorithmAlreadyRegisteredException if specified algorithmURI
* is already registered
@@ -270,7 +269,7 @@
* @return the URI representation of Transformation algorithm
*/
public String getURI() {
- return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+ return getLocalAttribute(Constants._ATT_ALGORITHM);
}
/**
@@ -311,21 +310,22 @@
XMLSignatureInput result = null;
try {
+ transformSpi.secureValidation = secureValidation;
result = transformSpi.enginePerformTransform(input, os, this);
} catch (ParserConfigurationException ex) {
Object exArgs[] = { this.getURI(), "ParserConfigurationException" };
throw new CanonicalizationException(
- "signature.Transform.ErrorDuringTransform", exArgs, ex);
+ ex, "signature.Transform.ErrorDuringTransform", exArgs);
} catch (SAXException ex) {
Object exArgs[] = { this.getURI(), "SAXException" };
throw new CanonicalizationException(
- "signature.Transform.ErrorDuringTransform", exArgs, ex);
+ ex, "signature.Transform.ErrorDuringTransform", exArgs);
}
return result;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_TRANSFORM;
}
@@ -336,7 +336,7 @@
private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes)
throws InvalidTransformException {
- this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI);
+ setLocalAttribute(Constants._ATT_ALGORITHM, algorithmURI);
Class extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
if (transformSpiClass == null) {
@@ -349,28 +349,34 @@
} catch (InstantiationException ex) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
- "signature.Transform.UnknownTransform", exArgs, ex
+ ex, "signature.Transform.UnknownTransform", exArgs
);
} catch (IllegalAccessException ex) {
Object exArgs[] = { algorithmURI };
throw new InvalidTransformException(
- "signature.Transform.UnknownTransform", exArgs, ex
+ ex, "signature.Transform.UnknownTransform", exArgs
);
}
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
- + newTransformSpi.getClass() + "\"");
- log.log(java.util.logging.Level.FINE, "The NodeList is " + contextNodes);
- }
+ LOG.debug("Create URI \"{}\" class \"{}\"", algorithmURI, newTransformSpi.getClass());
+ LOG.debug("The NodeList is {}", contextNodes);
// 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));
+ int length = contextNodes.getLength();
+ for (int i = 0; i < length; i++) {
+ appendSelf(contextNodes.item(i).cloneNode(true));
}
}
return newTransformSpi;
}
+ public boolean isSecureValidation() {
+ return secureValidation;
+ }
+
+ public void setSecureValidation(boolean secureValidation) {
+ this.secureValidation = secureValidation;
+ }
+
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java
@@ -36,10 +36,11 @@
* have to be overridden are the
* {@link #enginePerformTransform(XMLSignatureInput, Transform)} method.
*
- * @author Christian Geuer-Pollmann
*/
public abstract class TransformSpi {
+ protected boolean secureValidation;
+
/**
* The mega method which MUST be implemented by the Transformation Algorithm.
*
@@ -104,9 +105,9 @@
}
/**
- * Returns the URI representation of Transformation algorithm
+ * Returns the URI representation of {@code Transformation algorithm}
*
- * @return the URI representation of Transformation algorithm
+ * @return the URI representation of {@code Transformation algorithm}
*/
protected abstract String engineGetURI();
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java
@@ -26,7 +26,6 @@
/**
*
- * @author Christian Geuer-Pollmann
*/
public class TransformationException extends XMLSecurityException {
/**
@@ -42,6 +41,10 @@
super();
}
+ public TransformationException(Exception ex) {
+ super(ex);
+ }
+
/**
* Constructor TransformationException
*
@@ -64,21 +67,31 @@
/**
* Constructor TransformationException
*
+ * @param originalException
* @param msgID
- * @param originalException
*/
+ public TransformationException(Exception originalException, String msgID) {
+ super(originalException, msgID);
+ }
+
+ @Deprecated
public TransformationException(String msgID, Exception originalException) {
- super(msgID, originalException);
+ this(originalException, msgID);
}
/**
* Constructor TransformationException
*
+ * @param originalException
* @param msgID
* @param exArgs
- * @param originalException
*/
- public TransformationException(String msgID, Object exArgs[], Exception originalException) {
- super(msgID, exArgs, originalException);
+ public TransformationException(Exception originalException, String msgID, Object exArgs[]) {
+ super(originalException, msgID, exArgs);
+ }
+
+ @Deprecated
+ public TransformationException(String msgID, Object[] exArgs, Exception originalException) {
+ this(originalException, msgID, exArgs);
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java
@@ -43,11 +43,10 @@
* Holder of the {@link com.sun.org.apache.xml.internal.security.transforms.Transform} steps to
* be performed on the data.
* The input to the first Transform is the result of dereferencing the
- * URI
attribute of the Reference
element.
+ * {@code URI} attribute of the {@code Reference} element.
* The output from the last Transform is the input for the
- * DigestMethod algorithm
+ * {@code DigestMethod algorithm}
*
- * @author Christian Geuer-Pollmann
* @see Transform
* @see com.sun.org.apache.xml.internal.security.signature.Reference
*/
@@ -101,43 +100,42 @@
public static final String TRANSFORM_XPATH2FILTER
= "http://www.w3.org/2002/06/xmldsig-filter2";
- /** {@link org.apache.commons.logging} logging facility */
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(Transforms.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(Transforms.class);
private Element[] transforms;
- protected Transforms() { };
+ protected Transforms() { }
private boolean secureValidation;
/**
* Constructs {@link Transforms}.
*
- * @param doc the {@link Document} in which XMLSignature
will
+ * @param doc the {@link Document} in which {@code XMLSignature} will
* be placed
*/
public Transforms(Document doc) {
super(doc);
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
}
/**
* Constructs {@link Transforms} from {@link Element} which is
- * Transforms
Element
+ * {@code Transforms} Element
*
- * @param element is Transforms
element
- * @param BaseURI the URI where the XML instance was stored
+ * @param element is {@code Transforms} element
+ * @param baseURI the URI where the XML instance was stored
* @throws DOMException
* @throws InvalidTransformException
* @throws TransformationException
* @throws XMLSecurityException
* @throws XMLSignatureException
*/
- public Transforms(Element element, String BaseURI)
+ public Transforms(Element element, String baseURI)
throws DOMException, XMLSignatureException, InvalidTransformException,
TransformationException, XMLSecurityException {
- super(element, BaseURI);
+ super(element, baseURI);
int numberOfTransformElems = this.getLength();
@@ -157,7 +155,7 @@
}
/**
- * Adds the Transform
with the specified Transform
+ * Adds the {@code Transform} with the specified
Transform
* algorithm URI
*
* @param transformURI the URI form of transform that indicates which
@@ -166,20 +164,18 @@
*/
public void addTransform(String transformURI) throws TransformationException {
try {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
- }
+ LOG.debug("Transforms.addTransform({})", transformURI);
- Transform transform = new Transform(this.doc, transformURI);
+ Transform transform = new Transform(getDocument(), transformURI);
this.addTransform(transform);
} catch (InvalidTransformException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
}
}
/**
- * Adds the Transform
with the specified Transform
+ * Adds the {@code Transform} with the specified
Transform
* algorithm URI
*
* @param transformURI the URI form of transform that indicates which
@@ -190,20 +186,18 @@
public void addTransform(String transformURI, Element contextElement)
throws TransformationException {
try {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")");
- }
+ LOG.debug("Transforms.addTransform({})", transformURI);
- Transform transform = new Transform(this.doc, transformURI, contextElement);
+ Transform transform = new Transform(getDocument(), transformURI, contextElement);
this.addTransform(transform);
} catch (InvalidTransformException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
}
}
/**
- * Adds the Transform
with the specified Transform
+ * Adds the {@code Transform} with the specified
Transform
* algorithm URI
.
*
* @param transformURI the URI form of transform that indicates which
@@ -215,10 +209,10 @@
throws TransformationException {
try {
- Transform transform = new Transform(this.doc, transformURI, contextNodes);
+ Transform transform = new Transform(getDocument(), transformURI, contextNodes);
this.addTransform(transform);
} catch (InvalidTransformException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
}
}
@@ -228,22 +222,20 @@
* @param transform {@link Transform} object
*/
private void addTransform(Transform transform) {
- if (log.isLoggable(java.util.logging.Level.FINE)) {
- log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")");
- }
+ LOG.debug("Transforms.addTransform({})", transform.getURI());
Element transformElement = transform.getElement();
- this.constructionElement.appendChild(transformElement);
- XMLUtils.addReturnToElement(this.constructionElement);
+ appendSelf(transformElement);
+ addReturnToSelf();
}
/**
- * Applies all included Transform
s to xmlSignatureInput and
+ * Applies all included {@code Transform}s to xmlSignatureInput and
* returns the result of these transformations.
*
- * @param xmlSignatureInput the input for the Transform
s
- * @return the result of the Transforms
+ * @param xmlSignatureInput the input for the {@code Transform}s
+ * @return the result of the {@code Transforms}
* @throws TransformationException
*/
public XMLSignatureInput performTransforms(
@@ -253,12 +245,12 @@
}
/**
- * Applies all included Transform
s to xmlSignatureInput and
+ * Applies all included {@code Transform}s to xmlSignatureInput and
* returns the result of these transformations.
*
- * @param xmlSignatureInput the input for the Transform
s
+ * @param xmlSignatureInput the input for the {@code Transform}s
* @param os where to output the last transformation.
- * @return the result of the Transforms
+ * @return the result of the {@code Transforms}
* @throws TransformationException
*/
public XMLSignatureInput performTransforms(
@@ -268,26 +260,24 @@
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 " + uri + " transform");
- }
+ LOG.debug("Perform the ({})th {} transform", i, t.getURI());
checkSecureValidation(t);
xmlSignatureInput = t.performTransform(xmlSignatureInput);
}
if (last >= 0) {
Transform t = this.item(last);
+ LOG.debug("Perform the ({})th {} transform", last, t.getURI());
checkSecureValidation(t);
xmlSignatureInput = t.performTransform(xmlSignatureInput, os);
}
return xmlSignatureInput;
} catch (IOException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
} catch (CanonicalizationException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
} catch (InvalidCanonicalizerException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
}
}
@@ -300,6 +290,7 @@
"signature.Transform.ForbiddenTransform", exArgs
);
}
+ transform.setSecureValidation(secureValidation);
}
/**
@@ -308,34 +299,34 @@
* @return the number of transformations
*/
public int getLength() {
- if (transforms == null) {
- transforms =
- XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform");
- }
+ initTransforms();
return transforms.length;
}
/**
- * Return the {@link Transform}
.
- * Valid i
values are 0 to {@link #getLength}-1
.
+ * Return the ith {@code {@link Transform}}.
+ * Valid {@code i} values are 0 to {@code {@link #getLength}-1}.
*
* @param i index of {@link Transform} to return
- * @return the http://www.w3.org/2000/09/xmldsig#base64
decoding
+ * Implements the {@code http://www.w3.org/2000/09/xmldsig#base64} decoding
* transform.
*
* http://www.w3.org/TR/2001/REC-xml-c14n-20010315
+ * Implements the {@code http://www.w3.org/TR/2001/REC-xml-c14n-20010315}
* transform.
*
- * @author Christian Geuer-Pollmann
*/
public class TransformC14N extends TransformSpi {
@@ -44,7 +43,7 @@
Transforms.TRANSFORM_C14N_OMIT_COMMENTS;
/**
- * @inheritDoc
+ * {@inheritDoc}
*/
protected String engineGetURI() {
return TransformC14N.implementedTransformURI;
@@ -54,12 +53,14 @@
XMLSignatureInput input, OutputStream os, Transform transformObject
) throws CanonicalizationException {
Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments();
+ c14n.setSecureValidation(secureValidation);
if (os != null) {
c14n.setWriter(os);
}
byte[] result = null;
result = c14n.engineCanonicalize(input);
XMLSignatureInput output = new XMLSignatureInput(result);
+ output.setSecureValidation(secureValidation);
if (os != null) {
output.setOutputStream(os);
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java
@@ -32,10 +32,9 @@
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
/**
- * Implements the http://www.w3.org/2006/12/xml-c14n11
+ * Implements the {@code http://www.w3.org/2006/12/xml-c14n11}
* (C14N 1.1) transform.
*
- * @author Sean Mullan
*/
public class TransformC14N11 extends TransformSpi {
@@ -47,12 +46,14 @@
XMLSignatureInput input, OutputStream os, Transform transform
) throws CanonicalizationException {
Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments();
+ c14n.setSecureValidation(secureValidation);
if (os != null) {
c14n.setWriter(os);
}
byte[] result = null;
result = c14n.engineCanonicalize(input);
XMLSignatureInput output = new XMLSignatureInput(result);
+ output.setSecureValidation(secureValidation);
if (os != null) {
output.setOutputStream(os);
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java
@@ -32,10 +32,9 @@
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
/**
- * Implements the http://www.w3.org/2006/12/xml-c14n-11#WithComments
+ * Implements the {@code http://www.w3.org/2006/12/xml-c14n-11#WithComments}
* (C14N 1.1 With Comments) transform.
*
- * @author Sean Mullan
*/
public class TransformC14N11_WithComments extends TransformSpi {
@@ -48,6 +47,7 @@
) throws CanonicalizationException {
Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments();
+ c14n.setSecureValidation(secureValidation);
if (os != null) {
c14n.setWriter(os);
}
@@ -55,6 +55,7 @@
byte[] result = null;
result = c14n.engineCanonicalize(input);
XMLSignatureInput output = new XMLSignatureInput(result);
+ output.setSecureValidation(secureValidation);
if (os != null) {
output.setOutputStream(os);
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java
@@ -48,7 +48,7 @@
/**
* Method engineGetURI
*
- * @inheritDoc
+ * {@inheritDoc}
*/
protected String engineGetURI() {
return implementedTransformURI;
@@ -79,18 +79,20 @@
Canonicalizer20010315ExclOmitComments c14n =
new Canonicalizer20010315ExclOmitComments();
+ c14n.setSecureValidation(secureValidation);
if (os != null) {
c14n.setWriter(os);
}
byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
XMLSignatureInput output = new XMLSignatureInput(result);
+ output.setSecureValidation(secureValidation);
if (os != null) {
output.setOutputStream(os);
}
return output;
} catch (XMLSecurityException ex) {
- throw new CanonicalizationException("empty", ex);
+ throw new CanonicalizationException(ex);
}
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java
@@ -36,10 +36,9 @@
import org.w3c.dom.Element;
/**
- * Implements the http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments
+ * Implements the {@code http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments}
* transform.
*
- * @author Christian Geuer-Pollmann
*/
public class TransformC14NExclusiveWithComments extends TransformSpi {
@@ -49,7 +48,7 @@
/**
* Method engineGetURI
- *@inheritDoc
+ *{@inheritDoc}
*
*/
protected String engineGetURI() {
@@ -82,15 +81,17 @@
Canonicalizer20010315ExclWithComments c14n =
new Canonicalizer20010315ExclWithComments();
+ c14n.setSecureValidation(secureValidation);
if (os != null) {
c14n.setWriter(os);
}
byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
XMLSignatureInput output = new XMLSignatureInput(result);
+ output.setSecureValidation(secureValidation);
return output;
} catch (XMLSecurityException ex) {
- throw new CanonicalizationException("empty", ex);
+ throw new CanonicalizationException(ex);
}
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java
@@ -32,10 +32,9 @@
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
/**
- * Implements the http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments
+ * Implements the {@code http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments}
* transform.
*
- * @author Christian Geuer-Pollmann
*/
public class TransformC14NWithComments extends TransformSpi {
@@ -43,17 +42,18 @@
public static final String implementedTransformURI =
Transforms.TRANSFORM_C14N_WITH_COMMENTS;
- /** @inheritDoc */
+ /** {@inheritDoc} */
protected String engineGetURI() {
return implementedTransformURI;
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
protected XMLSignatureInput enginePerformTransform(
XMLSignatureInput input, OutputStream os, Transform transformObject
) throws CanonicalizationException {
Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments();
+ c14n.setSecureValidation(secureValidation);
if (os != null) {
c14n.setWriter(os);
}
@@ -61,6 +61,7 @@
byte[] result = null;
result = c14n.engineCanonicalize(input);
XMLSignatureInput output = new XMLSignatureInput(result);
+ output.setSecureValidation(secureValidation);
if (os != null) {
output.setOutputStream(os);
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java
@@ -36,10 +36,9 @@
import org.w3c.dom.Node;
/**
- * Implements the http://www.w3.org/2000/09/xmldsig#enveloped-signature
+ * Implements the {@code http://www.w3.org/2000/09/xmldsig#enveloped-signature}
* transform.
*
- * @author Christian Geuer-Pollmann
*/
public class TransformEnvelopedSignature extends TransformSpi {
@@ -50,14 +49,14 @@
/**
* Method engineGetURI
*
- * @inheritDoc
+ * {@inheritDoc}
*/
protected String engineGetURI() {
return implementedTransformURI;
}
/**
- * @inheritDoc
+ * {@inheritDoc}
*/
protected XMLSignatureInput enginePerformTransform(
XMLSignatureInput input, OutputStream os, Transform transformObject
@@ -136,7 +135,7 @@
return -1;
}
return 1;
- //return !XMLUtils.isDescendantOrSelf(exclude,n);
+ //return !XMLUtils.isDescendantOrSelf(exclude, n);
}
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java
@@ -44,10 +44,9 @@
/**
* Class TransformXPath
*
- * Implements the http://www.w3.org/TR/1999/REC-xpath-19991116
+ * Implements the {@code http://www.w3.org/TR/1999/REC-xpath-19991116}
* transform.
*
- * @author Christian Geuer-Pollmann
* @see XPath
*
*/
@@ -59,7 +58,7 @@
/**
* Method engineGetURI
*
- * @inheritDoc
+ * {@inheritDoc}
*/
protected String engineGetURI() {
return implementedTransformURI;
@@ -67,7 +66,7 @@
/**
* Method enginePerformTransform
- * @inheritDoc
+ * {@inheritDoc}
* @param input
*
* @throws TransformationException
@@ -96,14 +95,14 @@
throw new TransformationException("xml.WrongContent", exArgs);
}
- Node xpathnode = xpathElement.getChildNodes().item(0);
- String str = XMLUtils.getStrFromNode(xpathnode);
- input.setNeedsToBeExpanded(needsCircumvent(str));
+ Node xpathnode = xpathElement.getFirstChild();
if (xpathnode == null) {
throw new DOMException(
DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath"
);
}
+ String str = XMLUtils.getStrFromNode(xpathnode);
+ input.setNeedsToBeExpanded(needsCircumvent(str));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
@@ -111,7 +110,7 @@
input.setNodeSet(true);
return input;
} catch (DOMException ex) {
- throw new TransformationException("empty", ex);
+ throw new TransformationException(ex);
}
}
@@ -120,7 +119,7 @@
* @return true if needs to be circumvent for bug.
*/
private boolean needsCircumvent(String str) {
- return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1);
+ return str.indexOf("namespace") != -1 || str.indexOf("name()") != -1;
}
static class XPathNodeFilter implements NodeFilter {
@@ -151,7 +150,7 @@
Object[] eArgs = {currentNode};
throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e);
} catch (Exception e) {
- Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())};
+ Object[] eArgs = {currentNode, currentNode.getNodeType()};
throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e);
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java
@@ -66,7 +66,7 @@
/**
* Method engineGetURI
*
- * @inheritDoc
+ * {@inheritDoc}
*/
protected String engineGetURI() {
return implementedTransformURI;
@@ -74,7 +74,7 @@
/**
* Method enginePerformTransform
- * @inheritDoc
+ * {@inheritDoc}
* @param input
*
* @throws TransformationException
@@ -83,9 +83,9 @@
XMLSignatureInput input, OutputStream os, Transform transformObject
) throws TransformationException {
try {
- Listhttp://www.w3.org/TR/1999/REC-xslt-19991116
+ * Implements the {@code http://www.w3.org/TR/1999/REC-xslt-19991116}
* transform.
*
- * @author Christian Geuer-Pollmann
*/
public class TransformXSLT extends TransformSpi {
@@ -60,17 +60,17 @@
public static final String implementedTransformURI =
Transforms.TRANSFORM_XSLT;
- static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform";
+ static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform";
static final String defaultXSLTSpecNSprefix = "xslt";
- static final String XSLTSTYLESHEET = "stylesheet";
+ static final String XSLTSTYLESHEET = "stylesheet";
- private static java.util.logging.Logger log =
- java.util.logging.Logger.getLogger(TransformXSLT.class.getName());
+ private static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(TransformXSLT.class);
/**
* Method engineGetURI
*
- * @inheritDoc
+ * {@inheritDoc}
*/
protected String engineGetURI() {
return implementedTransformURI;
@@ -101,8 +101,6 @@
* 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;
/*
@@ -114,15 +112,16 @@
* 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);
+ try (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);
@@ -135,33 +134,34 @@
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());
+ LOG.warn("Unable to set Xalan line-separator property: " + e.getMessage());
}
- if (baos == null) {
- ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
- StreamResult outputTarget = new StreamResult(baos1);
+ try (InputStream is = new ByteArrayInputStream(input.getBytes())) {
+ Source xmlSource = new StreamSource(is);
+ if (baos == null) {
+ try (ByteArrayOutputStream baos1 = new ByteArrayOutputStream()) {
+ StreamResult outputTarget = new StreamResult(baos1);
+ transformer.transform(xmlSource, outputTarget);
+ XMLSignatureInput output = new XMLSignatureInput(baos1.toByteArray());
+ output.setSecureValidation(secureValidation);
+ return output;
+ }
+ }
+ 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.setSecureValidation(secureValidation);
output.setOutputStream(baos);
return output;
} catch (XMLSecurityException ex) {
- Object exArgs[] = { ex.getMessage() };
-
- throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+ throw new TransformationException(ex);
} catch (TransformerConfigurationException ex) {
- Object exArgs[] = { ex.getMessage() };
-
- throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+ throw new TransformationException(ex);
} catch (TransformerException ex) {
- Object exArgs[] = { ex.getMessage() };
-
- throw new TransformationException("generic.EmptyMessage", exArgs, ex);
+ throw new TransformationException(ex);
}
}
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/package.html b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/package.html
deleted file mode 100644
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/package.html
+++ /dev/null
@@ -1,3 +0,0 @@
-
+ *
* It implements the {@link Element} interface
* and can be used directly in a DOM tree.
*
- * @author Christian Geuer-Pollmann
*/
public class InclusiveNamespaces extends ElementProxy implements TransformParam {
@@ -82,27 +81,27 @@
StringBuilder sb = new StringBuilder();
for (String prefix : prefixList) {
- if (prefix.equals("xmlns")) {
+ if ("xmlns".equals(prefix)) {
sb.append("#default ");
} else {
- sb.append(prefix + " ");
+ sb.append(prefix);
+ sb.append(" ");
}
}
- this.constructionElement.setAttributeNS(
- null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim());
+ setLocalAttribute(InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim());
}
/**
* Constructor InclusiveNamespaces
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- public InclusiveNamespaces(Element element, String BaseURI)
+ public InclusiveNamespaces(Element element, String baseURI)
throws XMLSecurityException {
- super(element, BaseURI);
+ super(element, baseURI);
}
/**
@@ -111,21 +110,21 @@
* @return The Inclusive Namespace string
*/
public String getInclusiveNamespaces() {
- return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST);
+ return getLocalAttribute(InclusiveNamespaces._ATT_EC_PREFIXLIST);
}
/**
- * Decodes the inclusiveNamespaces
String and returns all
- * selected namespace prefixes as a Set. The #default
+ * Decodes the {@code inclusiveNamespaces} String and returns all
+ * selected namespace prefixes as a Set. The {@code #default}
* namespace token is represented as an empty namespace prefix
- * ("xmlns"
).
- *
- * The String inclusiveNamespaces=" xenc ds #default"
+ * ({@code "xmlns"}).
+ *
+ * The String {@code inclusiveNamespaces=" xenc ds #default"}
* is returned as a Set containing the following Strings:
*
- *
*
* @param inclusiveNamespaces
@@ -134,7 +133,7 @@
public static SortedSetxmlns
xenc
ds
true
if the Filter
attribute has value "intersect".
+ * Returns {@code true} if the {@code Filter} attribute has value "intersect".
*
- * @return true
if the Filter
attribute has value "intersect".
+ * @return {@code true} if the {@code Filter} attribute has value "intersect".
*/
public boolean isIntersect() {
- return this.constructionElement.getAttributeNS(
- null, XPath2FilterContainer._ATT_FILTER
+ return getLocalAttribute(XPath2FilterContainer._ATT_FILTER
).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT);
}
/**
- * Returns true
if the Filter
attribute has value "subtract".
+ * Returns {@code true} if the {@code Filter} attribute has value "subtract".
*
- * @return true
if the Filter
attribute has value "subtract".
+ * @return {@code true} if the {@code Filter} attribute has value "subtract".
*/
public boolean isSubtract() {
- return this.constructionElement.getAttributeNS(
- null, XPath2FilterContainer._ATT_FILTER
+ return getLocalAttribute(XPath2FilterContainer._ATT_FILTER
).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT);
}
/**
- * Returns true
if the Filter
attribute has value "union".
+ * Returns {@code true} if the {@code Filter} attribute has value "union".
*
- * @return true
if the Filter
attribute has value "union".
+ * @return {@code true} if the {@code Filter} attribute has value "union".
*/
public boolean isUnion() {
- return this.constructionElement.getAttributeNS(
- null, XPath2FilterContainer._ATT_FILTER
+ return getLocalAttribute(XPath2FilterContainer._ATT_FILTER
).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION);
}
@@ -255,18 +249,15 @@
* Filter String. We must use this stupid hook to enable the here() function
* to work.
*
- * $todo$ I dunno whether this crashes: true
if the Filter
attribute has value "intersect".
+ * Returns {@code true} if the {@code Filter} attribute has value "intersect".
*
- * @return true
if the Filter
attribute has value "intersect".
+ * @return {@code true} if the {@code Filter} attribute has value "intersect".
*/
public boolean isIntersect() {
- return this.constructionElement.getAttributeNS(
- null, XPath2FilterContainer04._ATT_FILTER
+ return getLocalAttribute(XPath2FilterContainer04._ATT_FILTER
).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT);
}
/**
- * Returns true
if the Filter
attribute has value "subtract".
+ * Returns {@code true} if the {@code Filter} attribute has value "subtract".
*
- * @return true
if the Filter
attribute has value "subtract".
+ * @return {@code true} if the {@code Filter} attribute has value "subtract".
*/
public boolean isSubtract() {
- return this.constructionElement.getAttributeNS(
- null, XPath2FilterContainer04._ATT_FILTER
+ return getLocalAttribute(XPath2FilterContainer04._ATT_FILTER
).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT);
}
/**
- * Returns true
if the Filter
attribute has value "union".
+ * Returns {@code true} if the {@code Filter} attribute has value "union".
*
- * @return true
if the Filter
attribute has value "union".
+ * @return {@code true} if the {@code Filter} attribute has value "union".
*/
public boolean isUnion() {
- return this.constructionElement.getAttributeNS(
- null, XPath2FilterContainer04._ATT_FILTER
+ return getLocalAttribute(XPath2FilterContainer04._ATT_FILTER
).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION);
}
@@ -224,28 +216,26 @@
* Filter String. We must use this stupid hook to enable the here() function
* to work.
*
- * $todo$ I dunno whether this crashes: ds:XPath
Element. It implements the {@link org.w3c.dom.Element} interface
+ * the {@code ds:XPath} Element. It implements the {@link org.w3c.dom.Element} interface
* and can be used directly in a DOM tree.
*
- * @author Christian Geuer-Pollmann
*/
public class XPathContainer extends SignatureElementProxy implements TransformParam {
@@ -49,33 +48,32 @@
}
/**
- * Sets the TEXT value of the ds:XPath
Element.
+ * Sets the TEXT value of the {@code ds:XPath} Element.
*
* @param xpath
*/
public void setXPath(String xpath) {
- if (this.constructionElement.getChildNodes() != null) {
- NodeList nl = this.constructionElement.getChildNodes();
-
- for (int i = 0; i < nl.getLength(); i++) {
- this.constructionElement.removeChild(nl.item(i));
- }
+ Node childNode = getElement().getFirstChild();
+ while (childNode != null) {
+ Node nodeToBeRemoved = childNode;
+ childNode = childNode.getNextSibling();
+ getElement().removeChild(nodeToBeRemoved);
}
- Text xpathText = this.doc.createTextNode(xpath);
- this.constructionElement.appendChild(xpathText);
+ Text xpathText = createText(xpath);
+ appendSelf(xpathText);
}
/**
- * Returns the TEXT value of the ds:XPath
Element.
+ * Returns the TEXT value of the {@code ds:XPath} Element.
*
- * @return the TEXT value of the ds:XPath
Element.
+ * @return the TEXT value of the {@code ds:XPath} Element.
*/
public String getXPath() {
return this.getTextFromTextChild();
}
- /** @inheritDoc */
+ /** {@inheritDoc} */
public String getBaseLocalName() {
return Constants._TAG_XPATH;
}
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java
@@ -35,7 +35,6 @@
* Implements the parameters for a custom Transform which has a better performance
* than the xfilter2.
*
- * @author $Author: coheigea $
*/
public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam {
@@ -87,52 +86,48 @@
super(doc);
if (includeSlashPolicy) {
- this.constructionElement.setAttributeNS(
- null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"
- );
+ setLocalAttribute(XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true");
} else {
- this.constructionElement.setAttributeNS(
- null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"
- );
+ setLocalAttribute(XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false");
}
- if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) {
+ if (includeButSearch != null && includeButSearch.trim().length() > 0) {
Element includeButSearchElem =
ElementProxy.createElementForFamily(
doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH
);
includeButSearchElem.appendChild(
- this.doc.createTextNode(indentXPathText(includeButSearch))
+ createText(indentXPathText(includeButSearch))
);
- XMLUtils.addReturnToElement(this.constructionElement);
- this.constructionElement.appendChild(includeButSearchElem);
+ addReturnToSelf();
+ appendSelf(includeButSearchElem);
}
- if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) {
+ 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)));
+ createText(indentXPathText(excludeButSearch)));
- XMLUtils.addReturnToElement(this.constructionElement);
- this.constructionElement.appendChild(excludeButSearchElem);
+ addReturnToSelf();
+ appendSelf(excludeButSearchElem);
}
- if ((exclude != null) && (exclude.trim().length() > 0)) {
+ if (exclude != null && exclude.trim().length() > 0) {
Element excludeElem =
ElementProxy.createElementForFamily(
doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE);
- excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude)));
- XMLUtils.addReturnToElement(this.constructionElement);
- this.constructionElement.appendChild(excludeElem);
+ excludeElem.appendChild(createText(indentXPathText(exclude)));
+ addReturnToSelf();
+ appendSelf(excludeElem);
}
- XMLUtils.addReturnToElement(this.constructionElement);
+ addReturnToSelf();
}
/**
@@ -142,7 +137,7 @@
* @return the string with enters
*/
static String indentXPathText(String xp) {
- if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) {
+ if (xp.length() > 2 && !Character.isWhitespace(xp.charAt(0))) {
return "\n" + xp + "\n";
}
return xp;
@@ -152,12 +147,12 @@
* Constructor XPathFilterCHGPContainer
*
* @param element
- * @param BaseURI
+ * @param baseURI
* @throws XMLSecurityException
*/
- private XPathFilterCHGPContainer(Element element, String BaseURI)
+ private XPathFilterCHGPContainer(Element element, String baseURI)
throws XMLSecurityException {
- super(element, BaseURI);
+ super(element, baseURI);
}
/**
@@ -182,15 +177,15 @@
* Creates a XPathFilterCHGPContainer from an existing Element; needed for verification.
*
* @param element
- * @param BaseURI
+ * @param baseURI
*
* @throws XMLSecurityException
* @return the created object.
*/
public static XPathFilterCHGPContainer getInstance(
- Element element, String BaseURI
+ Element element, String baseURI
) throws XMLSecurityException {
- return new XPathFilterCHGPContainer(element, BaseURI);
+ return new XPathFilterCHGPContainer(element, baseURI);
}
/**
@@ -206,7 +201,7 @@
Element xElem =
XMLUtils.selectNode(
- this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+ getElement().getFirstChild(), this.getBaseNamespace(), type, 0
);
return XMLUtils.getFullTextChildrenFromElement(xElem);
@@ -245,8 +240,7 @@
* @return the string
*/
public boolean getIncludeSlashPolicy() {
- return this.constructionElement.getAttributeNS(
- null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true");
+ return getLocalAttribute(XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true");
}
/**
@@ -265,7 +259,7 @@
}
return XMLUtils.selectNodeText(
- this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0
+ getFirstChild(), this.getBaseNamespace(), type, 0
);
}
@@ -299,7 +293,7 @@
/**
* Method getBaseLocalName
*
- * @inheritDoc
+ * {@inheritDoc}
*/
public final String getBaseLocalName() {
return XPathFilterCHGPContainer._TAG_XPATHCHGP;
@@ -308,7 +302,7 @@
/**
* Method getBaseNamespace
*
- * @inheritDoc
+ * {@inheritDoc}
*/
public final String getBaseNamespace() {
return TRANSFORM_XPATHFILTERCHGP;
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java
@@ -39,12 +39,10 @@
* Optimized code. (raw version taken from oreilly.jonathan.util,
* and currently org.apache.xerces.ds.util.Base64)
*
- * @author Raul Benito(Of the xerces copy, and little adaptations).
- * @author Anli Shundi
- * @author Christian Geuer-Pollmann
* @see RFC 2045
* @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode
*/
+@Deprecated
public class Base64 {
/** Field BASE64DEFAULTLENGTH */
@@ -105,9 +103,9 @@
* N.B.: {@link BigInteger}
's toByteArray
* returns eventually longer arrays because of the leading sign-bit.
*
- * @param big
BigInteger
to be converted
- * @param bitlen
int
the desired length in bits of the representation
- * @return a byte array with
bitlen
bits of big
+ * @param big {@code BigInteger} to be converted
+ * @param bitlen {@code int} the desired length in bits of the representation
+ * @return a byte array with {@code bitlen} bits of {@code big}
*/
static final byte[] getBytes(BigInteger big, int bitlen) {
@@ -120,8 +118,8 @@
byte[] bigBytes = big.toByteArray();
- if (((big.bitLength() % 8) != 0)
- && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+ if (big.bitLength() % 8 != 0
+ && big.bitLength() / 8 + 1 == bitlen / 8) {
return bigBytes;
}
@@ -129,7 +127,7 @@
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
@@ -144,27 +142,28 @@
}
/**
- * Encode in Base64 the given {@link BigInteger}
.
+ * Encode in Base64 the given {@code {@link BigInteger}}.
*
* @param big
* @return String with Base64 encoding
*/
public static final String encode(BigInteger big) {
- return encode(getBytes(big, big.bitLength()));
+ byte[] bytes = XMLUtils.getBytes(big, big.bitLength());
+ return XMLUtils.encodeToString(bytes);
}
/**
- * Returns a byte-array representation of a
{@link BigInteger}
.
+ * Returns a byte-array representation of a {@code {@link BigInteger}}.
* No sign-bit is output.
*
- * N.B.:
{@link BigInteger}
's toByteArray
+ * N.B.: {@code {@link BigInteger}}'s toByteArray
* returns eventually longer arrays because of the leading sign-bit.
*
- * @param big
BigInteger
to be converted
- * @param bitlen
int
the desired length in bits of the representation
- * @return a byte array with
bitlen
bits of big
+ * @param big {@code BigInteger} to be converted
+ * @param bitlen {@code int} the desired length in bits of the representation
+ * @return a byte array with {@code bitlen} bits of {@code big}
*/
- public static final byte[] encode(BigInteger big, int bitlen) {
+ public static final byte[] encode(BigInteger big, int bitlen) {
//round bitlen
bitlen = ((bitlen + 7) >> 3) << 3;
@@ -175,8 +174,8 @@
byte[] bigBytes = big.toByteArray();
- if (((big.bitLength() % 8) != 0)
- && (((big.bitLength() / 8) + 1) == (bitlen / 8))) {
+ if (big.bitLength() % 8 != 0
+ && big.bitLength() / 8 + 1 == bitlen / 8) {
return bigBytes;
}
@@ -184,7 +183,7 @@
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
@@ -211,10 +210,9 @@
}
/**
- * Method decodeBigIntegerFromText
- *
- * @param text
- * @return the biginter obtained from the text node
+ * Decode a base 64 string into a {@link BigInteger}
+ * @param base64str Base 64 encoded string.
+ * @return a decoded BigInteger
* @throws Base64DecodingException
*/
public static final BigInteger decodeBigIntegerFromText(Text text)
@@ -246,8 +244,8 @@
/**
* Method decode
*
- * Takes the Text
children of the Element and interprets
- * them as input for the Base64.decode()
function.
+ * Takes the {@code Text} children of the Element and interprets
+ * them as input for the {@code Base64.decode()} function.
*
* @param element
* @return the byte obtained of the decoding the element
@@ -305,8 +303,8 @@
* Encode a byte array and fold lines at the standard 76th character unless
* ignore line breaks property is set.
*
- * @param binaryData byte[]
to be base64 encoded
- * @return the
String
with encoded data
+ * @param binaryData {@code byte[]} to be base64 encoded
+ * @return the {@code String} with encoded data
*/
public static final String encode(byte[] binaryData) {
return XMLUtils.ignoreLineBreaks()
@@ -328,11 +326,9 @@
throws IOException, Base64DecodingException {
byte[] retBytes = null;
- UnsyncByteArrayOutputStream baos = null;
+ UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream();
try {
- baos = new UnsyncByteArrayOutputStream();
String line;
-
while (null != (line = reader.readLine())) {
byte[] bytes = decode(line);
baos.write(bytes);
@@ -345,12 +341,12 @@
return retBytes;
}
- protected static final boolean isWhiteSpace(byte octect) {
- return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
+ protected static final boolean isWhiteSpace(byte octet) {
+ return octet == 0x20 || octet == 0xd || octet == 0xa || octet == 0x9;
}
- protected static final boolean isPad(byte octect) {
- return (octect == PAD);
+ protected static final boolean isPad(byte octet) {
+ return octet == PAD;
}
/**
@@ -363,11 +359,11 @@
* Encode a byte array in Base64 format and return an optionally
* wrapped line.
*
- * @param binaryData
byte[]
data to be encoded
- * @param length int
length of wrapped lines; No wrapping if less than 4.
- * @return a
String
with encoded data
+ * @param binaryData {@code byte[]} data to be encoded
+ * @param length {@code int} length of wrapped lines; No wrapping if less than 4.
+ * @return a {@code String} with encoded data
*/
- public static final String encode(byte[] binaryData,int length) {
+ public static final String encode(byte[] binaryData, int length) {
if (length < 4) {
length = Integer.MAX_VALUE;
}
@@ -381,14 +377,14 @@
return "";
}
- long fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
+ long fewerThan24bits = lengthDataBits % ((long) TWENTYFOURBITGROUP);
int numberTriplets = (int) (lengthDataBits / TWENTYFOURBITGROUP);
int numberQuartet = fewerThan24bits != 0L ? numberTriplets + 1 : numberTriplets;
int quartesPerLine = length / 4;
int numberLines = (numberQuartet - 1) / quartesPerLine;
char encodedData[] = null;
- encodedData = new char[numberQuartet * 4 + numberLines];
+ encodedData = new char[numberQuartet * 4 + numberLines * 2];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
@@ -401,8 +397,8 @@
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
- l = (byte)(b2 & 0x0f);
- k = (byte)(b1 & 0x03);
+ l = (byte)(b2 & 0x0f);
+ k = (byte)(b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0);
@@ -417,6 +413,7 @@
i++;
}
+ encodedData[encodedIndex++] = 0xd;
encodedData[encodedIndex++] = 0xa;
}
@@ -425,8 +422,8 @@
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
- l = (byte)(b2 & 0x0f);
- k = (byte)(b1 & 0x03);
+ l = (byte)(b2 & 0x0f);
+ k = (byte)(b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0);
@@ -510,7 +507,7 @@
//should be divisible by four
}
- int numberQuadruple = (len / FOURBYTE);
+ int numberQuadruple = len / FOURBYTE;
if (numberQuadruple == 0) {
return new byte[0];
@@ -529,7 +526,7 @@
//first last bits.
b1 = base64Alphabet[base64Data[dataIndex++]];
b2 = base64Alphabet[base64Data[dataIndex++]];
- if ((b1==-1) || (b2==-1)) {
+ if (b1 == -1 || b2 == -1) {
//if found "no data" just return null
throw new Base64DecodingException("decoding.general");
}
@@ -538,7 +535,7 @@
byte d3, d4;
b3 = base64Alphabet[d3 = base64Data[dataIndex++]];
b4 = base64Alphabet[d4 = base64Data[dataIndex++]];
- if ((b3 == -1) || (b4 == -1) ) {
+ 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
@@ -573,10 +570,7 @@
b3 = base64Alphabet[base64Data[dataIndex++]];
b4 = base64Alphabet[base64Data[dataIndex++]];
- if ((b1 == -1) ||
- (b2 == -1) ||
- (b3 == -1) ||
- (b4 == -1)) {
+ if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1) {
//if found "no data" just return null
throw new Base64DecodingException("decoding.general");
}
@@ -600,7 +594,7 @@
throws Base64DecodingException, IOException {
byte[] bytes = new byte[base64Data.length()];
int len = getBytesInternal(base64Data, bytes);
- decode(bytes,os,len);
+ decode(bytes, os, len);
}
/**
@@ -613,7 +607,7 @@
*/
public static final void decode(byte[] base64Data, OutputStream os)
throws Base64DecodingException, IOException {
- decode(base64Data,os,-1);
+ decode(base64Data, os, -1);
}
protected static final void decode(byte[] base64Data, OutputStream os, int len)
@@ -628,7 +622,7 @@
//should be divisible by four
}
- int numberQuadruple = (len / FOURBYTE);
+ int numberQuadruple = len / FOURBYTE;
if (numberQuadruple == 0) {
return;
@@ -641,28 +635,25 @@
int dataIndex = 0;
//the begin
- for (i=numberQuadruple - 1; i > 0; i--) {
+ 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 (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1) {
//if found "no data" just return null
throw new Base64DecodingException("decoding.general");
}
os.write((byte)(b1 << 2 | b2 >> 4));
os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf)));
- os.write( (byte)(b3 << 6 | b4));
+ os.write((byte)(b3 << 6 | b4));
}
b1 = base64Alphabet[base64Data[dataIndex++]];
b2 = base64Alphabet[base64Data[dataIndex++]];
// first last bits.
- if ((b1 == -1) || (b2 == -1) ) {
+ if (b1 == -1 || b2 == -1) {
//if found "no data" just return null
throw new Base64DecodingException("decoding.general");
}
@@ -670,7 +661,7 @@
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 (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");
@@ -707,7 +698,7 @@
//byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
- int index=0;
+ int index = 0;
byte[] data = new byte[4];
int read;
//the begin
@@ -748,7 +739,7 @@
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
- if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters
+ 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");
@@ -777,7 +768,7 @@
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
- * @return the new length
+ * @return the new length
*/
protected static final int removeWhiteSpace(byte[] data) {
if (data == null) {
diff --git a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java
--- a/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java
+++ b/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java
@@ -23,208 +23,22 @@
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
+ * This class is extremely useful for loading 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 static final com.sun.org.slf4j.internal.Logger LOG =
+ com.sun.org.slf4j.internal.LoggerFactory.getLogger(ClassLoaderUtils.class);
private ClassLoaderUtils() {
}
/**
- * Load a given resource. This method will try to load the resource
- * using the following methods (in order):
- *
- *