提交 e9ae111a 编写于 作者: W wetmore

Merge

...@@ -23,10 +23,6 @@ ...@@ -23,10 +23,6 @@
# have any questions. # have any questions.
# #
#
# Makefile for building com/sun
#
BUILDDIR = ../../.. BUILDDIR = ../../..
include $(BUILDDIR)/common/Defs.gmk include $(BUILDDIR)/common/Defs.gmk
......
...@@ -23,10 +23,6 @@ ...@@ -23,10 +23,6 @@
# have any questions. # have any questions.
# #
#
# Makefile for building com/sun
#
BUILDDIR = ../../../.. BUILDDIR = ../../../..
include $(BUILDDIR)/common/Defs.gmk include $(BUILDDIR)/common/Defs.gmk
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
# #
# #
# Makefile for building JNDI service provider toolkit # Makefile for building JNDI DNS name service provider
# #
BUILDDIR = ../../../../.. BUILDDIR = ../../../../..
......
...@@ -20,12 +20,9 @@ ...@@ -20,12 +20,9 @@
*/ */
package com.sun.org.apache.xml.internal.security; package com.sun.org.apache.xml.internal.security;
import java.io.InputStream; import java.io.InputStream;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
...@@ -51,7 +48,7 @@ import org.w3c.dom.Node; ...@@ -51,7 +48,7 @@ import org.w3c.dom.Node;
* done by calling {@link Init#init} which should be done in any static block * done by calling {@link Init#init} which should be done in any static block
* of the files of this library. We ensure that this call is only executed once. * of the files of this library. We ensure that this call is only executed once.
* *
* @author $Author: raul $ * @author $Author: mullan $
*/ */
public final class Init { public final class Init {
...@@ -113,20 +110,19 @@ public final class Init { ...@@ -113,20 +110,19 @@ public final class Init {
dbf.setValidating(false); dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder(); DocumentBuilder db = dbf.newDocumentBuilder();
// We don't allow users to override the Apache XML Security // We don't allow users to override the Apache XML Security
// configuration in the JRE. Users should use the standard security // configuration in the JRE. Users should use the standard security
// provider mechanism instead if implementing their own // provider mechanism instead if implementing their own
// transform or canonicalization algorithms. // transform or canonicalization algorithms.
// String cfile = System.getProperty("com.sun.org.apache.xml.internal.security.resource.config"); // InputStream is = Class.forName("com.sun.org.apache.xml.internal.security.Init").getResourceAsStream("resource/config.xml");
// InputStream is =
// Class.forName("com.sun.org.apache.xml.internal.security.Init")
// .getResourceAsStream(cfile != null ? cfile : "resource/config.xml");
InputStream is = (InputStream) AccessController.doPrivileged( InputStream is = (InputStream) AccessController.doPrivileged(
new PrivilegedAction() { new PrivilegedAction() {
public Object run() { public Object run() {
// String cfile = System.getProperty
// ("com.sun.org.apache.xml.internal.security.resource.config");
return getClass().getResourceAsStream return getClass().getResourceAsStream
("resource/config.xml"); // (cfile != null ? cfile : "resource/config.xml");
("resource/config.xml");
} }
}); });
...@@ -167,7 +163,7 @@ public final class Init { ...@@ -167,7 +163,7 @@ public final class Init {
// //
// if (tag.equals("ResourceBundles")){ // if (tag.equals("ResourceBundles")){
// XX_configure_i18n_start = System.currentTimeMillis(); // XX_configure_i18n_start = System.currentTimeMillis();
// Element resource=(Element)el; // Element resource=(Element)el;
// /* configure internationalization */ // /* configure internationalization */
// Attr langAttr = resource.getAttributeNode("defaultLanguageCode"); // Attr langAttr = resource.getAttributeNode("defaultLanguageCode");
// Attr countryAttr = resource.getAttributeNode("defaultCountryCode"); // Attr countryAttr = resource.getAttributeNode("defaultCountryCode");
...@@ -202,11 +198,11 @@ public final class Init { ...@@ -202,11 +198,11 @@ public final class Init {
if (currMeth.getDeclaringClass().getName() if (currMeth.getDeclaringClass().getName()
.equals(JAVACLASS)) { .equals(JAVACLASS)) {
log.log(java.util.logging.Level.FINE, currMeth.getDeclaringClass().toString()); log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
} }
}*/ }*/
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", " log.log(java.util.logging.Level.FINE, "Canonicalizer.register(" + URI + ", "
+ JAVACLASS + ")"); + JAVACLASS + ")");
Canonicalizer.register(URI, JAVACLASS); Canonicalizer.register(URI, JAVACLASS);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
...@@ -233,9 +229,8 @@ public final class Init { ...@@ -233,9 +229,8 @@ public final class Init {
"JAVACLASS"); "JAVACLASS");
try { try {
Class.forName(JAVACLASS); Class.forName(JAVACLASS);
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS log.log(java.util.logging.Level.FINE, "Transform.register(" + URI + ", " + JAVACLASS + ")");
+ ")");
Transform.register(URI, JAVACLASS); Transform.register(URI, JAVACLASS);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
Object exArgs[] = { URI, JAVACLASS }; Object exArgs[] = { URI, JAVACLASS };
...@@ -284,12 +279,11 @@ public final class Init { ...@@ -284,12 +279,11 @@ public final class Init {
// //
// if (currMeth.getDeclaringClass().getName() // if (currMeth.getDeclaringClass().getName()
// .equals(JAVACLASS)) { // .equals(JAVACLASS)) {
// log.log(java.util.logging.Level.FINE, currMeth.getDeclaringClass().toString()); // log.log(java.util.logging.Level.FINE, currMeth.getDe claringClass().toString());
// } // }
// } // }
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " log.log(java.util.logging.Level.FINE, "SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")");
+ JAVACLASS + ")");
SignatureAlgorithm.register(URI, JAVACLASS); SignatureAlgorithm.register(URI, JAVACLASS);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
Object exArgs[] = { URI, JAVACLASS }; Object exArgs[] = { URI, JAVACLASS };
...@@ -320,13 +314,11 @@ public final class Init { ...@@ -320,13 +314,11 @@ public final class Init {
"DESCRIPTION"); "DESCRIPTION");
if ((Description != null) && (Description.length() > 0)) { if ((Description != null) && (Description.length() > 0)) {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
+ Description);
} else { } else {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
+ ": For unknown purposes");
} }
try { try {
ResourceResolver.register(JAVACLASS); ResourceResolver.register(JAVACLASS);
...@@ -359,13 +351,11 @@ public final class Init { ...@@ -359,13 +351,11 @@ public final class Init {
"DESCRIPTION"); "DESCRIPTION");
if ((Description != null) && (Description.length() > 0)) { if ((Description != null) && (Description.length() > 0)) {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": " + Description);
+ Description);
} else { } else {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS log.log(java.util.logging.Level.FINE, "Register Resolver: " + JAVACLASS + ": For unknown purposes");
+ ": For unknown purposes");
} }
KeyResolver.register(JAVACLASS); KeyResolver.register(JAVACLASS);
...@@ -376,8 +366,8 @@ public final class Init { ...@@ -376,8 +366,8 @@ public final class Init {
if (tag.equals("PrefixMappings")){ if (tag.equals("PrefixMappings")){
XX_configure_reg_prefixes_start = System.currentTimeMillis(); XX_configure_reg_prefixes_start = System.currentTimeMillis();
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:"); log.log(java.util.logging.Level.FINE, "Now I try to bind prefixes:");
Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"PrefixMapping"); Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS,"PrefixMapping");
...@@ -386,8 +376,8 @@ public final class Init { ...@@ -386,8 +376,8 @@ public final class Init {
"namespace"); "namespace");
String prefix = nl[i].getAttributeNS(null, String prefix = nl[i].getAttributeNS(null,
"prefix"); "prefix");
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace); log.log(java.util.logging.Level.FINE, "Now I try to bind " + prefix + " to " + namespace);
com.sun.org.apache.xml.internal.security.utils.ElementProxy com.sun.org.apache.xml.internal.security.utils.ElementProxy
.setDefaultPrefix(namespace, prefix); .setDefaultPrefix(namespace, prefix);
} }
...@@ -398,19 +388,19 @@ public final class Init { ...@@ -398,19 +388,19 @@ public final class Init {
long XX_init_end = System.currentTimeMillis(); long XX_init_end = System.currentTimeMillis();
//J- //J-
if (true) { if (log.isLoggable(java.util.logging.Level.FINE)) {
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "XX_init " + ((int)(XX_init_end - XX_init_start)) + " ms"); log.log(java.util.logging.Level.FINE, "XX_init " + ((int)(XX_init_end - XX_init_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_prng " + ((int)(XX_prng_end - XX_prng_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_prng " + ((int)(XX_prng_end - XX_prng_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_parsing " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_parsing " + ((int)(XX_parsing_end - XX_parsing_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_i18n " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_i18n " + ((int)(XX_configure_i18n_end- XX_configure_i18n_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_c14n " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_c14n " + ((int)(XX_configure_reg_c14n_end- XX_configure_reg_c14n_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_jcemapper " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_jcemapper " + ((int)(XX_configure_reg_jcemapper_end- XX_configure_reg_jcemapper_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyInfo " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyInfo " + ((int)(XX_configure_reg_keyInfo_end- XX_configure_reg_keyInfo_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyResolver " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_keyResolver " + ((int)(XX_configure_reg_keyResolver_end- XX_configure_reg_keyResolver_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_prefixes " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_prefixes " + ((int)(XX_configure_reg_prefixes_end- XX_configure_reg_prefixes_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_resourceresolver " + ((int)(XX_configure_reg_resourceresolver_end- XX_configure_reg_resourceresolver_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_sigalgos " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_sigalgos " + ((int)(XX_configure_reg_sigalgos_end- XX_configure_reg_sigalgos_start)) + " ms");
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, " XX_configure_reg_transforms " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms"); log.log(java.util.logging.Level.FINE, " XX_configure_reg_transforms " + ((int)(XX_configure_reg_transforms_end- XX_configure_reg_transforms_start)) + " ms");
} }
} catch (Exception e) { } catch (Exception e) {
log.log(java.util.logging.Level.SEVERE, "Bad: ", e); log.log(java.util.logging.Level.SEVERE, "Bad: ", e);
......
...@@ -24,7 +24,7 @@ package com.sun.org.apache.xml.internal.security.algorithms; ...@@ -24,7 +24,7 @@ package com.sun.org.apache.xml.internal.security.algorithms;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants; 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.SignatureElementProxy;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
...@@ -33,11 +33,7 @@ import org.w3c.dom.Element; ...@@ -33,11 +33,7 @@ import org.w3c.dom.Element;
* The Algorithm class which stores the Algorithm URI as a string. * The Algorithm class which stores the Algorithm URI as a string.
* *
*/ */
public abstract class Algorithm extends ElementProxy { public abstract class Algorithm extends SignatureElementProxy {
/** {@link java.util.logging} logging facility */
static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(Algorithm.class.getName());
/** /**
* *
...@@ -79,7 +75,7 @@ public abstract class Algorithm extends ElementProxy { ...@@ -79,7 +75,7 @@ public abstract class Algorithm extends ElementProxy {
*/ */
protected void setAlgorithmURI(String algorithmURI) { protected void setAlgorithmURI(String algorithmURI) {
if ((this._state == MODE_CREATE) && (algorithmURI != null)) { if ( (algorithmURI != null)) {
this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM,
algorithmURI); algorithmURI);
} }
......
...@@ -35,7 +35,7 @@ import org.w3c.dom.Element; ...@@ -35,7 +35,7 @@ import org.w3c.dom.Element;
/** /**
* This class maps algorithm identifier URIs to JAVA JCE class names. * This class maps algorithm identifier URIs to JAVA JCE class names.
* *
* @author $Author: raul $ * @author $Author: mullan $
*/ */
public class JCEMapper { public class JCEMapper {
...@@ -45,9 +45,9 @@ public class JCEMapper { ...@@ -45,9 +45,9 @@ public class JCEMapper {
private static Map uriToJCEName = new HashMap(); private static Map uriToJCEName;
private static Map algorithmsMap = new HashMap(); private static Map algorithmsMap;
private static String providerName = null; private static String providerName = null;
/** /**
...@@ -63,6 +63,8 @@ public class JCEMapper { ...@@ -63,6 +63,8 @@ public class JCEMapper {
static void loadAlgorithms( Element algorithmsEl) { static void loadAlgorithms( Element algorithmsEl) {
Element[] algorithms = XMLUtils.selectNodes(algorithmsEl.getFirstChild(),Init.CONF_NS,"Algorithm"); Element[] algorithms = XMLUtils.selectNodes(algorithmsEl.getFirstChild(),Init.CONF_NS,"Algorithm");
uriToJCEName = new HashMap( algorithms.length * 2);
algorithmsMap = new HashMap( algorithms.length * 2);
for (int i = 0 ;i < algorithms.length ;i ++) { for (int i = 0 ;i < algorithms.length ;i ++) {
Element el = algorithms[i]; Element el = algorithms[i];
String id = el.getAttribute("URI"); String id = el.getAttribute("URI");
...@@ -70,6 +72,7 @@ public class JCEMapper { ...@@ -70,6 +72,7 @@ public class JCEMapper {
uriToJCEName.put(id, jceName); uriToJCEName.put(id, jceName);
algorithmsMap.put(id, new Algorithm(el)); algorithmsMap.put(id, new Algorithm(el));
} }
} }
static Algorithm getAlgorithmMapping(String algoURI) { static Algorithm getAlgorithmMapping(String algoURI) {
...@@ -84,8 +87,8 @@ public class JCEMapper { ...@@ -84,8 +87,8 @@ public class JCEMapper {
* *
*/ */
public static String translateURItoJCEID(String AlgorithmURI) { public static String translateURItoJCEID(String AlgorithmURI) {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI); log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
String jceName = (String) uriToJCEName.get(AlgorithmURI); String jceName = (String) uriToJCEName.get(AlgorithmURI);
return jceName; return jceName;
...@@ -100,8 +103,8 @@ public class JCEMapper { ...@@ -100,8 +103,8 @@ public class JCEMapper {
* *
*/ */
public static String getAlgorithmClassFromURI(String AlgorithmURI) { public static String getAlgorithmClassFromURI(String AlgorithmURI) {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI); log.log(java.util.logging.Level.FINE, "Request for URI " + AlgorithmURI);
return ((Algorithm) algorithmsMap.get(AlgorithmURI)).algorithmClass; return ((Algorithm) algorithmsMap.get(AlgorithmURI)).algorithmClass;
} }
......
...@@ -20,10 +20,10 @@ ...@@ -20,10 +20,10 @@
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
...@@ -41,11 +41,6 @@ import org.w3c.dom.Document; ...@@ -41,11 +41,6 @@ import org.w3c.dom.Document;
*/ */
public class MessageDigestAlgorithm extends Algorithm { public class MessageDigestAlgorithm extends Algorithm {
/** {@link java.util.logging} logging facility */
static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(
MessageDigestAlgorithm.class.getName());
/** Message Digest - NOT RECOMMENDED MD5*/ /** Message Digest - NOT RECOMMENDED MD5*/
public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5"; public static final String ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "md5";
/** Digest - Required SHA1*/ /** Digest - Required SHA1*/
...@@ -76,6 +71,12 @@ public class MessageDigestAlgorithm extends Algorithm { ...@@ -76,6 +71,12 @@ public class MessageDigestAlgorithm extends Algorithm {
this.algorithm = messageDigest; this.algorithm = messageDigest;
} }
static ThreadLocal instances=new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
};
};
/** /**
* Factory method for constructing a message digest algorithm by name. * Factory method for constructing a message digest algorithm by name.
* *
...@@ -86,8 +87,15 @@ public class MessageDigestAlgorithm extends Algorithm { ...@@ -86,8 +87,15 @@ public class MessageDigestAlgorithm extends Algorithm {
*/ */
public static MessageDigestAlgorithm getInstance( public static MessageDigestAlgorithm getInstance(
Document doc, String algorithmURI) throws XMLSignatureException { Document doc, String algorithmURI) throws XMLSignatureException {
MessageDigest md = getDigestInstance(algorithmURI);
return new MessageDigestAlgorithm(doc, md, algorithmURI);
}
String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI); private static MessageDigest getDigestInstance(String algorithmURI) throws XMLSignatureException {
MessageDigest result=(MessageDigest) ((Map)instances.get()).get(algorithmURI);
if (result!=null)
return result;
String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);
if (algorithmID == null) { if (algorithmID == null) {
Object[] exArgs = { algorithmURI }; Object[] exArgs = { algorithmURI };
...@@ -113,8 +121,9 @@ public class MessageDigestAlgorithm extends Algorithm { ...@@ -113,8 +121,9 @@ public class MessageDigestAlgorithm extends Algorithm {
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs); throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
} }
return new MessageDigestAlgorithm(doc, md, algorithmURI); ((Map)instances.get()).put(algorithmURI, md);
} return md;
}
/** /**
* Returns the actual {@link java.security.MessageDigest} algorithm object * Returns the actual {@link java.security.MessageDigest} algorithm object
......
...@@ -25,6 +25,7 @@ import java.security.Key; ...@@ -25,6 +25,7 @@ import java.security.Key;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac; import com.sun.org.apache.xml.internal.security.algorithms.implementations.IntegrityHmac;
import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException; import com.sun.org.apache.xml.internal.security.exceptions.AlgorithmAlreadyRegisteredException;
...@@ -52,9 +53,35 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -52,9 +53,35 @@ public class SignatureAlgorithm extends Algorithm {
/** All available algorithm classes are registered here */ /** All available algorithm classes are registered here */
static HashMap _algorithmHash = null; static HashMap _algorithmHash = null;
static ThreadLocal instancesSigning=new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
};
};
static ThreadLocal instancesVerify=new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
};
};
static ThreadLocal keysSigning=new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
};
};
static ThreadLocal keysVerify=new ThreadLocal() {
protected Object initialValue() {
return new HashMap();
};
};
// boolean isForSigning=false;
/** Field _signatureAlgorithm */ /** Field _signatureAlgorithm */
protected SignatureAlgorithmSpi _signatureAlgorithm = null; protected SignatureAlgorithmSpi _signatureAlgorithm = null;
private String algorithmURI;
/** /**
* Constructor SignatureAlgorithm * Constructor SignatureAlgorithm
* *
...@@ -64,18 +91,49 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -64,18 +91,49 @@ public class SignatureAlgorithm extends Algorithm {
*/ */
public SignatureAlgorithm(Document doc, String algorithmURI) public SignatureAlgorithm(Document doc, String algorithmURI)
throws XMLSecurityException { throws XMLSecurityException {
super(doc, algorithmURI); super(doc, algorithmURI);
this.algorithmURI = algorithmURI;
}
try {
private void initializeAlgorithm(boolean isForSigning) throws XMLSignatureException {
if (_signatureAlgorithm!=null) {
return;
}
_signatureAlgorithm=isForSigning ? getInstanceForSigning(algorithmURI) : getInstanceForVerify(algorithmURI);
this._signatureAlgorithm
.engineGetContextFromElement(this._constructionElement);
}
private static SignatureAlgorithmSpi getInstanceForSigning(String algorithmURI) throws XMLSignatureException {
SignatureAlgorithmSpi result=(SignatureAlgorithmSpi) ((Map)instancesSigning.get()).get(algorithmURI);
if (result!=null) {
result.reset();
return result;
}
result=buildSigner(algorithmURI, result);
((Map)instancesSigning.get()).put(algorithmURI,result);
return result;
}
private static SignatureAlgorithmSpi getInstanceForVerify(String algorithmURI) throws XMLSignatureException {
SignatureAlgorithmSpi result=(SignatureAlgorithmSpi) ((Map)instancesVerify.get()).get(algorithmURI);
if (result!=null) {
result.reset();
return result;
}
result=buildSigner(algorithmURI, result);
((Map)instancesVerify.get()).put(algorithmURI,result);
return result;
}
private static SignatureAlgorithmSpi buildSigner(String algorithmURI, SignatureAlgorithmSpi result) throws XMLSignatureException {
try {
Class implementingClass = Class implementingClass =
SignatureAlgorithm.getImplementingClass(algorithmURI); SignatureAlgorithm.getImplementingClass(algorithmURI);
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \"" log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
+ implementingClass + "\""); + implementingClass + "\"");
result=(SignatureAlgorithmSpi) implementingClass.newInstance();
this._signatureAlgorithm = return result;
(SignatureAlgorithmSpi) implementingClass.newInstance();
} catch (IllegalAccessException ex) { } catch (IllegalAccessException ex) {
Object exArgs[] = { algorithmURI, ex.getMessage() }; Object exArgs[] = { algorithmURI, ex.getMessage() };
...@@ -92,7 +150,7 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -92,7 +150,7 @@ public class SignatureAlgorithm extends Algorithm {
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs, throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
ex); ex);
} }
} }
/** /**
* Constructor SignatureAlgorithm * Constructor SignatureAlgorithm
...@@ -107,7 +165,8 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -107,7 +165,8 @@ public class SignatureAlgorithm extends Algorithm {
throws XMLSecurityException { throws XMLSecurityException {
this(doc, algorithmURI); this(doc, algorithmURI);
this.algorithmURI=algorithmURI;
initializeAlgorithm(true);
this._signatureAlgorithm.engineSetHMACOutputLength(HMACOutputLength); this._signatureAlgorithm.engineSetHMACOutputLength(HMACOutputLength);
((IntegrityHmac)this._signatureAlgorithm) ((IntegrityHmac)this._signatureAlgorithm)
.engineAddContextToElement(this._constructionElement); .engineAddContextToElement(this._constructionElement);
...@@ -124,37 +183,7 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -124,37 +183,7 @@ public class SignatureAlgorithm extends Algorithm {
throws XMLSecurityException { throws XMLSecurityException {
super(element, BaseURI); super(element, BaseURI);
algorithmURI = this.getURI();
String algorithmURI = this.getURI();
try {
Class implementingClass =
SignatureAlgorithm.getImplementingClass(algorithmURI);
if (true)
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Create URI \"" + algorithmURI + "\" class \""
+ implementingClass + "\"");
this._signatureAlgorithm =
(SignatureAlgorithmSpi) implementingClass.newInstance();
this._signatureAlgorithm
.engineGetContextFromElement(this._constructionElement);
} catch (IllegalAccessException 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);
}
} }
/** /**
...@@ -175,7 +204,12 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -175,7 +204,12 @@ public class SignatureAlgorithm extends Algorithm {
* @return the result of the {@link java.security.Signature#getAlgorithm} method * @return the result of the {@link java.security.Signature#getAlgorithm} method
*/ */
public String getJCEAlgorithmString() { public String getJCEAlgorithmString() {
return this._signatureAlgorithm.engineGetJCEAlgorithmString(); try {
return getInstanceForVerify(algorithmURI).engineGetJCEAlgorithmString();
} catch (XMLSignatureException e) {
//Ignore.
return null;
}
} }
/** /**
...@@ -184,7 +218,11 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -184,7 +218,11 @@ public class SignatureAlgorithm extends Algorithm {
* @return The Provider of this Signature Alogrithm * @return The Provider of this Signature Alogrithm
*/ */
public String getJCEProviderName() { public String getJCEProviderName() {
return this._signatureAlgorithm.engineGetJCEProviderName(); try {
return getInstanceForVerify(algorithmURI).engineGetJCEProviderName();
} catch (XMLSignatureException e) {
return null;
}
} }
/** /**
...@@ -231,7 +269,13 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -231,7 +269,13 @@ public class SignatureAlgorithm extends Algorithm {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public void initSign(Key signingKey) throws XMLSignatureException { public void initSign(Key signingKey) throws XMLSignatureException {
this._signatureAlgorithm.engineInitSign(signingKey); initializeAlgorithm(true);
Map map=(Map)keysSigning.get();
if (map.get(this.algorithmURI)==signingKey) {
return;
}
map.put(this.algorithmURI,signingKey);
this._signatureAlgorithm.engineInitSign(signingKey);
} }
/** /**
...@@ -244,6 +288,7 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -244,6 +288,7 @@ public class SignatureAlgorithm extends Algorithm {
*/ */
public void initSign(Key signingKey, SecureRandom secureRandom) public void initSign(Key signingKey, SecureRandom secureRandom)
throws XMLSignatureException { throws XMLSignatureException {
initializeAlgorithm(true);
this._signatureAlgorithm.engineInitSign(signingKey, secureRandom); this._signatureAlgorithm.engineInitSign(signingKey, secureRandom);
} }
...@@ -258,6 +303,7 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -258,6 +303,7 @@ public class SignatureAlgorithm extends Algorithm {
public void initSign( public void initSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec) Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
throws XMLSignatureException { throws XMLSignatureException {
initializeAlgorithm(true);
this._signatureAlgorithm.engineInitSign(signingKey, this._signatureAlgorithm.engineInitSign(signingKey,
algorithmParameterSpec); algorithmParameterSpec);
} }
...@@ -282,7 +328,13 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -282,7 +328,13 @@ public class SignatureAlgorithm extends Algorithm {
* @throws XMLSignatureException * @throws XMLSignatureException
*/ */
public void initVerify(Key verificationKey) throws XMLSignatureException { public void initVerify(Key verificationKey) throws XMLSignatureException {
this._signatureAlgorithm.engineInitVerify(verificationKey); initializeAlgorithm(false);
Map map=(Map)keysVerify.get();
if (map.get(this.algorithmURI)==verificationKey) {
return;
}
map.put(this.algorithmURI,verificationKey);
this._signatureAlgorithm.engineInitVerify(verificationKey);
} }
/** /**
...@@ -320,7 +372,7 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -320,7 +372,7 @@ public class SignatureAlgorithm extends Algorithm {
.getLogger(SignatureAlgorithm.class.getName()); .getLogger(SignatureAlgorithm.class.getName());
} }
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Init() called"); log.log(java.util.logging.Level.FINE, "Init() called");
if (!SignatureAlgorithm._alreadyInitialized) { if (!SignatureAlgorithm._alreadyInitialized) {
SignatureAlgorithm._algorithmHash = new HashMap(10); SignatureAlgorithm._algorithmHash = new HashMap(10);
...@@ -340,8 +392,8 @@ public class SignatureAlgorithm extends Algorithm { ...@@ -340,8 +392,8 @@ public class SignatureAlgorithm extends Algorithm {
throws AlgorithmAlreadyRegisteredException,XMLSignatureException { throws AlgorithmAlreadyRegisteredException,XMLSignatureException {
{ {
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass); log.log(java.util.logging.Level.FINE, "Try to register " + algorithmURI + " " + implementingClass);
// are we already registered? // are we already registered?
Class registeredClassClass = Class registeredClassClass =
......
...@@ -20,27 +20,20 @@ ...@@ -20,27 +20,20 @@
*/ */
package com.sun.org.apache.xml.internal.security.algorithms; package com.sun.org.apache.xml.internal.security.algorithms;
import java.security.Key; import java.security.Key;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* *
* @author $Author: raul $ * @author $Author: mullan $
*/ */
public abstract class SignatureAlgorithmSpi { public abstract class SignatureAlgorithmSpi {
/** {@link java.util.logging} logging facility */
static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureAlgorithmSpi.class.getName());
/** /**
* Returns the URI representation of <code>Transformation algorithm</code> * Returns the URI representation of <code>Transformation algorithm</code>
* *
...@@ -167,20 +160,6 @@ public abstract class SignatureAlgorithmSpi { ...@@ -167,20 +160,6 @@ public abstract class SignatureAlgorithmSpi {
protected abstract void engineSetParameter(AlgorithmParameterSpec params) protected abstract void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException; throws XMLSignatureException;
/** Field _doc */
Document _doc = null;
/**
* Method engineSetDocument
*
* @param doc
*/
protected void engineSetDocument(Document doc) {
this._doc = doc;
}
/** Field _constructionElement */
Element _constructionElement = null;
/** /**
* Method engineGetContextFromElement * Method engineGetContextFromElement
...@@ -188,7 +167,6 @@ public abstract class SignatureAlgorithmSpi { ...@@ -188,7 +167,6 @@ public abstract class SignatureAlgorithmSpi {
* @param element * @param element
*/ */
protected void engineGetContextFromElement(Element element) { protected void engineGetContextFromElement(Element element) {
this._constructionElement = element;
} }
/** /**
...@@ -199,4 +177,7 @@ public abstract class SignatureAlgorithmSpi { ...@@ -199,4 +177,7 @@ public abstract class SignatureAlgorithmSpi {
*/ */
protected abstract void engineSetHMACOutputLength(int HMACOutputLength) protected abstract void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException; throws XMLSignatureException;
public void reset() {
}
} }
...@@ -45,7 +45,7 @@ import org.w3c.dom.Text; ...@@ -45,7 +45,7 @@ import org.w3c.dom.Text;
/** /**
* *
* @author $Author: raul $ * @author $Author: mullan $
*/ */
public abstract class IntegrityHmac extends SignatureAlgorithmSpi { public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
...@@ -74,8 +74,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -74,8 +74,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
public IntegrityHmac() throws XMLSignatureException { public IntegrityHmac() throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI()); String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
if (true) if (log.isLoggable(java.util.logging.Level.FINE))
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID); log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
try { try {
this._macAlgorithm = Mac.getInstance(algorithmID); this._macAlgorithm = Mac.getInstance(algorithmID);
...@@ -99,6 +99,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -99,6 +99,10 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
throw new XMLSignatureException("empty"); throw new XMLSignatureException("empty");
} }
public void reset() {
_HMACOutputLength=0;
}
/** /**
* Proxy method for {@link java.security.Signature#verify(byte[])} * Proxy method for {@link java.security.Signature#verify(byte[])}
* which is executed on the internal {@link java.security.Signature} object. * which is executed on the internal {@link java.security.Signature} object.
...@@ -145,7 +149,20 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -145,7 +149,20 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
try { try {
this._macAlgorithm.init(secretKey); this._macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) { } catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex); // reinstantiate Mac object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Mac mac = this._macAlgorithm;
try {
this._macAlgorithm = Mac.getInstance
(_macAlgorithm.getAlgorithm());
} catch (Exception e) {
// this shouldn't occur, but if it does, restore previous Mac
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
}
this._macAlgorithm = mac;
}
throw new XMLSignatureException("empty", ex);
} }
} }
...@@ -323,7 +340,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -323,7 +340,7 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
*/ */
protected String engineGetJCEAlgorithmString() { protected String engineGetJCEAlgorithmString() {
if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()"); log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
return this._macAlgorithm.getAlgorithm(); return this._macAlgorithm.getAlgorithm();
} }
...@@ -397,7 +414,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -397,7 +414,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA1 * Class IntegrityHmacSHA1
* *
* @author $Author: raul $ * @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA1 extends IntegrityHmac { public static class IntegrityHmacSHA1 extends IntegrityHmac {
...@@ -423,7 +441,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -423,7 +441,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA256 * Class IntegrityHmacSHA256
* *
* @author $Author: raul $ * @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA256 extends IntegrityHmac { public static class IntegrityHmacSHA256 extends IntegrityHmac {
...@@ -449,7 +468,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -449,7 +468,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA384 * Class IntegrityHmacSHA384
* *
* @author $Author: raul $ * @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA384 extends IntegrityHmac { public static class IntegrityHmacSHA384 extends IntegrityHmac {
...@@ -475,7 +495,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -475,7 +495,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacSHA512 * Class IntegrityHmacSHA512
* *
* @author $Author: raul $ * @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacSHA512 extends IntegrityHmac { public static class IntegrityHmacSHA512 extends IntegrityHmac {
...@@ -501,7 +522,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -501,7 +522,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacRIPEMD160 * Class IntegrityHmacRIPEMD160
* *
* @author $Author: raul $ * @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacRIPEMD160 extends IntegrityHmac { public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
...@@ -527,7 +549,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi { ...@@ -527,7 +549,8 @@ public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
/** /**
* Class IntegrityHmacMD5 * Class IntegrityHmacMD5
* *
* @author $Author: raul $ * @author $Author: mullan $
* @version $Revision: 1.5 $
*/ */
public static class IntegrityHmacMD5 extends IntegrityHmac { public static class IntegrityHmacMD5 extends IntegrityHmac {
......
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.sun.org.apache.xml.internal.security.algorithms.implementations;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.AlgorithmParameterSpec;
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: mullan $
*/
public abstract class SignatureECDSA extends SignatureAlgorithmSpi {
/** {@link java.util.logging} logging facility */
static java.util.logging.Logger log =
java.util.logging.Logger.getLogger(SignatureECDSA.class.getName());
/** @inheritDoc */
public abstract String engineGetURI();
/** Field algorithm */
private java.security.Signature _signatureAlgorithm = null;
/**
* Converts an ASN.1 ECDSA value to a XML Signature ECDSA Value.
*
* The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param asn1Bytes
* @return the decode bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/
private static byte[] convertASN1toXMLDSIG(byte asn1Bytes[])
throws IOException {
byte rLength = asn1Bytes[3];
int i;
for (i = rLength; (i > 0) && (asn1Bytes[(4 + rLength) - i] == 0); i--);
byte sLength = asn1Bytes[5 + rLength];
int j;
for (j = sLength;
(j > 0) && (asn1Bytes[(6 + rLength + sLength) - j] == 0); j--);
if ((asn1Bytes[0] != 48) || (asn1Bytes[1] != asn1Bytes.length - 2)
|| (asn1Bytes[2] != 2) || (i > 24)
|| (asn1Bytes[4 + rLength] != 2) || (j > 24)) {
throw new IOException("Invalid ASN.1 format of ECDSA signature");
}
byte xmldsigBytes[] = new byte[48];
System.arraycopy(asn1Bytes, (4 + rLength) - i, xmldsigBytes, 24 - i,
i);
System.arraycopy(asn1Bytes, (6 + rLength + sLength) - j, xmldsigBytes,
48 - j, j);
return xmldsigBytes;
}
/**
* Converts a XML Signature ECDSA Value to an ASN.1 DSA value.
*
* The JAVA JCE ECDSA Signature algorithm creates ASN.1 encoded (r,s) value
* pairs; the XML Signature requires the core BigInteger values.
*
* @param xmldsigBytes
* @return the encoded ASN.1 bytes
*
* @throws IOException
* @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
* @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
*/
private static byte[] convertXMLDSIGtoASN1(byte xmldsigBytes[])
throws IOException {
if (xmldsigBytes.length != 48) {
throw new IOException("Invalid XMLDSIG format of ECDSA signature");
}
int i;
for (i = 24; (i > 0) && (xmldsigBytes[24 - i] == 0); i--);
int j = i;
if (xmldsigBytes[24 - i] < 0) {
j += 1;
}
int k;
for (k = 24; (k > 0) && (xmldsigBytes[48 - k] == 0); k--);
int l = k;
if (xmldsigBytes[48 - k] < 0) {
l += 1;
}
byte asn1Bytes[] = new byte[6 + j + l];
asn1Bytes[0] = 48;
asn1Bytes[1] = (byte) (4 + j + l);
asn1Bytes[2] = 2;
asn1Bytes[3] = (byte) j;
System.arraycopy(xmldsigBytes, 24 - i, asn1Bytes, (4 + j) - i, i);
asn1Bytes[4 + j] = 2;
asn1Bytes[5 + j] = (byte) l;
System.arraycopy(xmldsigBytes, 48 - k, asn1Bytes, (6 + j + l) - k, k);
return asn1Bytes;
}
/**
* Constructor SignatureRSA
*
* @throws XMLSignatureException
*/
public SignatureECDSA() throws XMLSignatureException {
String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Created SignatureECDSA using " + algorithmID);
String provider=JCEMapper.getProviderId();
try {
if (provider==null) {
this._signatureAlgorithm = Signature.getInstance(algorithmID);
} else {
this._signatureAlgorithm = Signature.getInstance(algorithmID,provider);
}
} catch (java.security.NoSuchAlgorithmException ex) {
Object[] exArgs = { algorithmID,
ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
} catch (NoSuchProviderException ex) {
Object[] exArgs = { algorithmID,
ex.getLocalizedMessage() };
throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
}
}
/** @inheritDoc */
protected void engineSetParameter(AlgorithmParameterSpec params)
throws XMLSignatureException {
try {
this._signatureAlgorithm.setParameter(params);
} catch (InvalidAlgorithmParameterException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected boolean engineVerify(byte[] signature)
throws XMLSignatureException {
try {
byte[] jcebytes = SignatureECDSA.convertXMLDSIGtoASN1(signature);
if (log.isLoggable(java.util.logging.Level.FINE))
log.log(java.util.logging.Level.FINE, "Called ECDSA.verify() on " + Base64.encode(signature));
return this._signatureAlgorithm.verify(jcebytes);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
} catch (IOException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
if (!(publicKey instanceof PublicKey)) {
String supplied = publicKey.getClass().getName();
String needed = PublicKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
exArgs);
}
try {
this._signatureAlgorithm.initVerify((PublicKey) publicKey);
} catch (InvalidKeyException ex) {
// reinstantiate Signature object to work around bug in JDK
// see: http://bugs.sun.com/view_bug.do?bug_id=4953555
Signature sig = this._signatureAlgorithm;
try {
this._signatureAlgorithm = Signature.getInstance
(_signatureAlgorithm.getAlgorithm());
} catch (Exception e) {
// this shouldn't occur, but if it does, restore previous
// Signature
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
}
this._signatureAlgorithm = sig;
}
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected byte[] engineSign() throws XMLSignatureException {
try {
byte jcebytes[] = this._signatureAlgorithm.sign();
return SignatureECDSA.convertASN1toXMLDSIG(jcebytes);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
} catch (IOException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected void engineInitSign(Key privateKey, SecureRandom secureRandom)
throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
exArgs);
}
try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey,
secureRandom);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected void engineInitSign(Key privateKey) throws XMLSignatureException {
if (!(privateKey instanceof PrivateKey)) {
String supplied = privateKey.getClass().getName();
String needed = PrivateKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
exArgs);
}
try {
this._signatureAlgorithm.initSign((PrivateKey) privateKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected void engineUpdate(byte[] input) throws XMLSignatureException {
try {
this._signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected void engineUpdate(byte input) throws XMLSignatureException {
try {
this._signatureAlgorithm.update(input);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected void engineUpdate(byte buf[], int offset, int len)
throws XMLSignatureException {
try {
this._signatureAlgorithm.update(buf, offset, len);
} catch (SignatureException ex) {
throw new XMLSignatureException("empty", ex);
}
}
/** @inheritDoc */
protected String engineGetJCEAlgorithmString() {
return this._signatureAlgorithm.getAlgorithm();
}
/** @inheritDoc */
protected String engineGetJCEProviderName() {
return this._signatureAlgorithm.getProvider().getName();
}
/** @inheritDoc */
protected void engineSetHMACOutputLength(int HMACOutputLength)
throws XMLSignatureException {
throw new XMLSignatureException("algorithms.HMACOutputLengthOnlyForHMAC");
}
/** @inheritDoc */
protected void engineInitSign(
Key signingKey, AlgorithmParameterSpec algorithmParameterSpec)
throws XMLSignatureException {
throw new XMLSignatureException(
"algorithms.CannotUseAlgorithmParameterSpecOnRSA");
}
/**
* Class SignatureRSASHA1
*
* @author $Author: mullan $
* @version $Revision: 1.2 $
*/
public static class SignatureECDSASHA1 extends SignatureECDSA {
/**
* Constructor SignatureRSASHA1
*
* @throws XMLSignatureException
*/
public SignatureECDSASHA1() throws XMLSignatureException {
super();
}
/** @inheritDoc */
public String engineGetURI() {
return XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1;
}
}
}
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-2004 The Apache Software Foundation. * Copyright 1999-2004 The Apache Software Foundation.
* *
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-2004 The Apache Software Foundation. * Copyright 1999-2004 The Apache Software Foundation.
* *
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-2004 The Apache Software Foundation. * Copyright 1999-2004 The Apache Software Foundation.
* *
...@@ -21,17 +20,17 @@ ...@@ -21,17 +20,17 @@
*/ */
package com.sun.org.apache.xml.internal.security.c14n.helper; package com.sun.org.apache.xml.internal.security.c14n.helper;
import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.Constants;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import java.io.Serializable;
import java.util.Comparator;
/** /**
* Compares two attributes based on the C14n specification. * Compares two attributes based on the C14n specification.
* *
* <UL> * <UL>
* <LI>Namespace nodes have a lesser document order position than attribute nodes. * <LI>Namespace nodes have a lesser document order position than attribute
* nodes.
* <LI> An element's namespace nodes are sorted lexicographically by * <LI> An element's namespace nodes are sorted lexicographically by
* local name (the default namespace node, if one exists, has no * local name (the default namespace node, if one exists, has no
* local name and is therefore lexicographically least). * local name and is therefore lexicographically least).
...@@ -40,104 +39,89 @@ import org.w3c.dom.Attr; ...@@ -40,104 +39,89 @@ import org.w3c.dom.Attr;
* key (an empty namespace URI is lexicographically least). * key (an empty namespace URI is lexicographically least).
* </UL> * </UL>
* *
* $todo$ Should we implement java.util.Comparator and import java.util.Arrays to use Arrays.sort(intarray);
* @author Christian Geuer-Pollmann * @author Christian Geuer-Pollmann
*/ */
public class AttrCompare implements java.util.Comparator { public class AttrCompare implements Comparator, Serializable {
private final int ATTR0_BEFORE_ATTR1 = -1; private final static long serialVersionUID = -7113259629930576230L;
private final int ATTR1_BEFORE_ATTR0 = 1; private final static int ATTR0_BEFORE_ATTR1 = -1;
private final static int ATTR1_BEFORE_ATTR0 = 1;
private final static String XMLNS=Constants.NamespaceSpecNS; private final static String XMLNS=Constants.NamespaceSpecNS;
/**
* Compares two attributes based on the C14n specification. /**
* * Compares two attributes based on the C14n specification.
* <UL> *
* <LI>Namespace nodes have a lesser document order position than attribute nodes. * <UL>
* <LI> An element's namespace nodes are sorted lexicographically by * <LI>Namespace nodes have a lesser document order position than
* local name (the default namespace node, if one exists, has no * attribute nodes.
* local name and is therefore lexicographically least). * <LI> An element's namespace nodes are sorted lexicographically by
* <LI> An element's attribute nodes are sorted lexicographically with * local name (the default namespace node, if one exists, has no
* namespace URI as the primary key and local name as the secondary * local name and is therefore lexicographically least).
* key (an empty namespace URI is lexicographically least). * <LI> An element's attribute nodes are sorted lexicographically with
* </UL> * namespace URI as the primary key and local name as the secondary
* * key (an empty namespace URI is lexicographically least).
* @param obj0 casted Attr * </UL>
* @param obj1 casted Attr *
* @return returns a negative integer, zero, or a positive integer as obj0 is less than, equal to, or greater than obj1 * @param obj0 casted Attr
* * @param obj1 casted Attr
*/ * @return returns a negative integer, zero, or a positive integer as
public int compare(Object obj0, Object obj1) { * obj0 is less than, equal to, or greater than obj1
*
Attr attr0 = (Attr) obj0; */
Attr attr1 = (Attr) obj1; public int compare(Object obj0, Object obj1) {
String namespaceURI0 = attr0.getNamespaceURI();
String namespaceURI1 = attr1.getNamespaceURI(); Attr attr0 = (Attr) obj0;
Attr attr1 = (Attr) obj1;
boolean isNamespaceAttr0 = String namespaceURI0 = attr0.getNamespaceURI();
XMLNS.equals(namespaceURI0); String namespaceURI1 = attr1.getNamespaceURI();
boolean isNamespaceAttr1 =
XMLNS.equals(namespaceURI1); boolean isNamespaceAttr0 = XMLNS==namespaceURI0;
boolean isNamespaceAttr1 = XMLNS==namespaceURI1;
if (isNamespaceAttr0) {
if (isNamespaceAttr1) { if (isNamespaceAttr0) {
if (isNamespaceAttr1) {
// both are namespaces // both are namespaces
String localname0 = attr0.getLocalName(); String localname0 = attr0.getLocalName();
String localname1 = attr1.getLocalName(); String localname1 = attr1.getLocalName();
if (localname0.equals("xmlns")) { if (localname0.equals("xmlns")) {
localname0 = ""; localname0 = "";
}
if (localname1.equals("xmlns")) {
localname1 = "";
}
return localname0.compareTo(localname1);
} }
// attr0 is a namespace, attr1 is not
return ATTR0_BEFORE_ATTR1;
}
if (localname1.equals("xmlns")) { if (isNamespaceAttr1) {
localname1 = "";
}
return localname0.compareTo(localname1);
}
// attr0 is a namespace, attr1 is not
return ATTR0_BEFORE_ATTR1;
}
if (isNamespaceAttr1) {
// attr1 is a namespace, attr0 is not // attr1 is a namespace, attr0 is not
return ATTR1_BEFORE_ATTR0; return ATTR1_BEFORE_ATTR0;
} }
// none is a namespae
if (namespaceURI0 == null) {
if (namespaceURI1 == null) {
/*
String localName0 = attr0.getLocalName();
String localName1 = attr1.getLocalName();
return localName0.compareTo(localName1);
*/
// none is a namespace
if (namespaceURI0 == null) {
if (namespaceURI1 == null) {
String name0 = attr0.getName(); String name0 = attr0.getName();
String name1 = attr1.getName(); String name1 = attr1.getName();
return name0.compareTo(name1); return name0.compareTo(name1);
}
return ATTR0_BEFORE_ATTR1;
} }
return ATTR0_BEFORE_ATTR1;
} if (namespaceURI1 == null) {
if (namespaceURI1 == null) { return ATTR1_BEFORE_ATTR0;
return ATTR1_BEFORE_ATTR0; }
}
int a = namespaceURI0.compareTo(namespaceURI1);
if (a != 0) {
return a;
}
/*
String localName0 = ;
String localName1 =;*/
return (attr0.getLocalName())
.compareTo( attr1.getLocalName());
} int a = namespaceURI0.compareTo(namespaceURI1);
if (a != 0) {
return a;
}
return (attr0.getLocalName()).compareTo(attr1.getLocalName());
}
} }
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2008 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
* @author Sean Mullan
*/
public class Canonicalizer11_OmitComments extends Canonicalizer11 {
public Canonicalizer11_OmitComments() {
super(false);
}
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS;
}
public final boolean engineGetIncludeComments() {
return false;
}
}
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2008 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/**
* @author Sean Mullan
*/
public class Canonicalizer11_WithComments extends Canonicalizer11 {
public Canonicalizer11_WithComments() {
super(true);
}
public final String engineGetURI() {
return Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS;
}
public final boolean engineGetIncludeComments() {
return true;
}
}
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-2004 The Apache Software Foundation. * Copyright 1999-2004 The Apache Software Foundation.
* *
...@@ -23,20 +22,30 @@ package com.sun.org.apache.xml.internal.security.c14n.implementations; ...@@ -23,20 +22,30 @@ package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; 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.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/** /**
...@@ -44,13 +53,92 @@ import org.w3c.dom.Node; ...@@ -44,13 +53,92 @@ import org.w3c.dom.Node;
* XML Version 1.0</A>, a W3C Recommendation from 15 March 2001. * XML Version 1.0</A>, a W3C Recommendation from 15 March 2001.
* *
* @author Christian Geuer-Pollmann <geuerp@apache.org> * @author Christian Geuer-Pollmann <geuerp@apache.org>
* @version $Revision: 1.5 $
*/ */
public abstract class Canonicalizer20010315 extends CanonicalizerBase { public abstract class Canonicalizer20010315 extends CanonicalizerBase {
boolean firstCall=true; boolean firstCall=true;
final SortedSet result= new TreeSet(COMPARE); final SortedSet result= new TreeSet(COMPARE);
static final String XMLNS_URI=Constants.NamespaceSpecNS; static final String XMLNS_URI=Constants.NamespaceSpecNS;
static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS; static final String XML_LANG_URI=Constants.XML_LANG_SPACE_SpecNS;
/** static class XmlAttrStack {
int currentLevel=0;
int lastlevel=0;
XmlsStackElement cur;
static class XmlsStackElement {
int level;
boolean rendered=false;
List nodes=new ArrayList();
};
List levels=new ArrayList();
void push(int level) {
currentLevel=level;
if (currentLevel==-1)
return;
cur=null;
while (lastlevel>=currentLevel) {
levels.remove(levels.size()-1);
if (levels.size()==0) {
lastlevel=0;
return;
}
lastlevel=((XmlsStackElement)levels.get(levels.size()-1)).level;
}
}
void addXmlnsAttr(Attr n) {
if (cur==null) {
cur=new XmlsStackElement();
cur.level=currentLevel;
levels.add(cur);
lastlevel=currentLevel;
}
cur.nodes.add(n);
}
void getXmlnsAttr(Collection col) {
int size=levels.size()-1;
if (cur==null) {
cur=new XmlsStackElement();
cur.level=currentLevel;
lastlevel=currentLevel;
levels.add(cur);
}
boolean parentRendered=false;
XmlsStackElement e=null;
if (size==-1) {
parentRendered=true;
} else {
e=(XmlsStackElement)levels.get(size);
if (e.rendered && e.level+1==currentLevel)
parentRendered=true;
}
if (parentRendered) {
col.addAll(cur.nodes);
cur.rendered=true;
return;
}
Map loa = new HashMap();
for (;size>=0;size--) {
e=(XmlsStackElement)levels.get(size);
Iterator it=e.nodes.iterator();
while (it.hasNext()) {
Attr n=(Attr)it.next();
if (!loa.containsKey(n.getName()))
loa.put(n.getName(),n);
}
//if (e.rendered)
//break;
};
//cur.nodes.clear();
//cur.nodes.addAll(loa.values());
cur.rendered=true;
col.addAll(loa.values());
}
}
XmlAttrStack xmlattrStack=new XmlAttrStack();
/**
* Constructor Canonicalizer20010315 * Constructor Canonicalizer20010315
* *
* @param includeComments * @param includeComments
...@@ -86,16 +174,16 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -86,16 +174,16 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr N = (Attr) attrs.item(i);
String NName=N.getLocalName();
String NValue=N.getValue();
String NUri =N.getNamespaceURI(); String NUri =N.getNamespaceURI();
if (!XMLNS_URI.equals(NUri)) { if (XMLNS_URI!=NUri) {
//It's not a namespace attr node. Add to the result and continue. //It's not a namespace attr node. Add to the result and continue.
result.add(N); result.add(N);
continue; continue;
} }
String NName=N.getLocalName();
String NValue=N.getValue();
if (XML.equals(NName) if (XML.equals(NName)
&& XML_LANG_URI.equals(NValue)) { && XML_LANG_URI.equals(NValue)) {
//The default mapping for xml must not be output. //The default mapping for xml must not be output.
...@@ -120,64 +208,13 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -120,64 +208,13 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
//Obtain all the namespaces defined in the parents, and added to the output. //Obtain all the namespaces defined in the parents, and added to the output.
ns.getUnrenderedNodes(result); ns.getUnrenderedNodes(result);
//output the attributes in the xml namespace. //output the attributes in the xml namespace.
addXmlAttributesSubtree(E, result); xmlattrStack.getXmlnsAttr(result);
firstCall=false; firstCall=false;
} }
return result.iterator(); return result.iterator();
} }
/**
* Float the xml:* attributes of the parent nodes to the root node of c14n
* @param E the root node.
* @param result the xml:* attributes to output.
*/
private void addXmlAttributesSubtree(Element E, SortedSet result) {
// E is in the node-set
Node parent = E.getParentNode();
Map loa = new HashMap();
if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE)) {
// parent element is not in node set
for (Node ancestor = parent;
(ancestor != null)
&& (ancestor.getNodeType() == Node.ELEMENT_NODE);
ancestor = ancestor.getParentNode()) {
Element el=((Element) ancestor);
if (!el.hasAttributes()) {
continue;
}
// for all ancestor elements
NamedNodeMap ancestorAttrs = el.getAttributes();
for (int i = 0; i < ancestorAttrs.getLength(); i++) {
// for all attributes in the ancestor element
Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i);
if (XML_LANG_URI.equals(
currentAncestorAttr.getNamespaceURI())) {
// do we have an xml:* ?
if (!E.hasAttributeNS(
XML_LANG_URI,
currentAncestorAttr.getLocalName())) {
// the xml:* attr is not in E
if (!loa.containsKey(currentAncestorAttr.getName())) {
loa.put(currentAncestorAttr.getName(),
currentAncestorAttr);
}
}
}
}
}
}
result.addAll( loa.values());
}
/** /**
* Returns the Attr[]s to be outputted for the given element. * Returns the Attr[]s to be outputted for the given element.
* <br> * <br>
...@@ -192,7 +229,8 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -192,7 +229,8 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
*/ */
Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException { Iterator handleAttributes(Element E, NameSpaceSymbTable ns ) throws CanonicalizationException {
// result will contain the attrs which have to be outputted // result will contain the attrs which have to be outputted
boolean isRealVisible=isVisible(E); xmlattrStack.push(ns.getLevel());
boolean isRealVisible=isVisibleDO(E,ns.getLevel())==1;
NamedNodeMap attrs = null; NamedNodeMap attrs = null;
int attrsLength = 0; int attrsLength = 0;
if (E.hasAttributes()) { if (E.hasAttributes()) {
...@@ -204,16 +242,15 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -204,16 +242,15 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
SortedSet result = this.result; SortedSet result = this.result;
result.clear(); result.clear();
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr N = (Attr) attrs.item(i);
String NName=N.getLocalName();
String NValue=N.getValue();
String NUri =N.getNamespaceURI(); String NUri =N.getNamespaceURI();
if (!XMLNS_URI.equals(NUri)) { if (XMLNS_URI!=NUri) {
//A non namespace definition node. //A non namespace definition node.
if (isRealVisible){ if (XML_LANG_URI==NUri) {
xmlattrStack.addXmlnsAttr(N);
} else if (isRealVisible){
//The node is visible add the attribute to the list of output attributes. //The node is visible add the attribute to the list of output attributes.
result.add(N); result.add(N);
} }
...@@ -221,7 +258,8 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -221,7 +258,8 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
continue; continue;
} }
String NName=N.getLocalName();
String NValue=N.getValue();
if ("xml".equals(NName) if ("xml".equals(NName)
&& XML_LANG_URI.equals(NValue)) { && XML_LANG_URI.equals(NValue)) {
/* except omit namespace node with local name xml, which defines /* except omit namespace node with local name xml, which defines
...@@ -232,16 +270,26 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -232,16 +270,26 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
//add the prefix binding to the ns symb table. //add the prefix binding to the ns symb table.
//ns.addInclusiveMapping(NName,NValue,N,isRealVisible); //ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
if (isVisible(N)) { if (isVisible(N)) {
//The xpath select this node output it if needed. if (!isRealVisible && ns.removeMappingIfRender(NName)) {
Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); continue;
if (n!=null) { }
//The xpath select this node output it if needed.
//Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible);
Node n=ns.addMappingAndRender(NName,NValue,N);
if (n!=null) {
result.add(n); result.add(n);
if (C14nHelper.namespaceIsRelative(N)) { if (C14nHelper.namespaceIsRelative(N)) {
Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() }; Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
throw new CanonicalizationException( throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs); "c14n.Canonicalizer.RelativeNamespace", exArgs);
} }
} }
} else {
if (isRealVisible && NName!=XMLNS) {
ns.removeMapping(NName);
} else {
ns.addMapping(NName,NValue,N);
}
} }
} }
if (isRealVisible) { if (isRealVisible) {
...@@ -254,84 +302,21 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -254,84 +302,21 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
} else if ( !isVisible(xmlns)) { } else if ( !isVisible(xmlns)) {
//There is a definition but the xmlns is not selected by the xpath. //There is a definition but the xmlns is not selected by the xpath.
//then xmlns="" //then xmlns=""
n=ns.addMappingAndRenderXNodeSet(XMLNS,"",nullNode,true); n=ns.addMappingAndRender(XMLNS,"",nullNode);
} }
//output the xmlns def if needed. //output the xmlns def if needed.
if (n!=null) { if (n!=null) {
result.add(n); result.add(n);
} }
//Float all xml:* attributes of the unselected parent elements to this one. //Float all xml:* attributes of the unselected parent elements to this one.
addXmlAttributes(E,result); //addXmlAttributes(E,result);
xmlattrStack.getXmlnsAttr(result);
ns.getUnrenderedNodes(result);
} }
return result.iterator(); return result.iterator();
} }
/**
* Float the xml:* attributes of the unselected parent nodes to the ciurrent node.
* @param E
* @param result
*/
private void addXmlAttributes(Element E, SortedSet result) {
/* The processing of an element node E MUST be modified slightly when an
* XPath node-set is given as input and the element's parent is omitted
* from the node-set. The method for processing the attribute axis of an
* element E in the node-set is enhanced. All element nodes along E's
* ancestor axis are examined for nearest occurrences of attributes in
* the xml namespace, such as xml:lang and xml:space (whether or not they
* are in the node-set). From this list of attributes, remove any that are
* in E's attribute axis (whether or not they are in the node-set). Then,
* lexicographically merge this attribute list with the nodes of E's
* attribute axis that are in the node-set. The result of visiting the
* attribute axis is computed by processing the attribute nodes in this
* merged attribute list.
*/
// E is in the node-set
Node parent = E.getParentNode();
Map loa = new HashMap();
if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE)
&&!isVisible(parent)) {
// parent element is not in node set
for (Node ancestor = parent;
(ancestor != null)
&& (ancestor.getNodeType() == Node.ELEMENT_NODE);
ancestor = ancestor.getParentNode()) {
Element el=((Element) ancestor);
if (!el.hasAttributes()) {
continue;
}
// for all ancestor elements
NamedNodeMap ancestorAttrs =el.getAttributes();
for (int i = 0; i < ancestorAttrs.getLength(); i++) {
// for all attributes in the ancestor element
Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i);
if (XML_LANG_URI.equals(
currentAncestorAttr.getNamespaceURI())) {
// do we have an xml:* ?
if (!E.hasAttributeNS(
XML_LANG_URI,
currentAncestorAttr.getLocalName())) {
// the xml:* attr is not in E
if (!loa.containsKey(currentAncestorAttr.getName())) {
loa.put(currentAncestorAttr.getName(),
currentAncestorAttr);
}
}
}
}
}
}
result.addAll(loa.values());
}
/** /**
* Always throws a CanonicalizationException because this is inclusive c14n. * Always throws a CanonicalizationException because this is inclusive c14n.
* *
...@@ -363,4 +348,43 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase { ...@@ -363,4 +348,43 @@ public abstract class Canonicalizer20010315 extends CanonicalizerBase {
throw new CanonicalizationException( throw new CanonicalizationException(
"c14n.Canonicalizer.UnsupportedOperation"); "c14n.Canonicalizer.UnsupportedOperation");
} }
void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
if (!input.isNeedsToBeExpanded())
return;
Document doc = null;
if (input.getSubNode() != null) {
doc=XMLUtils.getOwnerDocument(input.getSubNode());
} else {
doc=XMLUtils.getOwnerDocument(input.getNodeSet());
}
XMLUtils.circumventBug2650(doc);
}
void handleParent(Element e, NameSpaceSymbTable ns) {
if (!e.hasAttributes()) {
return;
}
xmlattrStack.push(-1);
NamedNodeMap attrs = e.getAttributes();
int attrsLength = attrs.getLength();
for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i);
if (Constants.NamespaceSpecNS!=N.getNamespaceURI()) {
//Not a namespace definition, ignore.
if (XML_LANG_URI==N.getNamespaceURI()) {
xmlattrStack.addXmlnsAttr(N);
}
continue;
}
String NName=N.getLocalName();
String NValue=N.getNodeValue();
if (XML.equals(NName)
&& Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
continue;
}
ns.addMapping(NName,NValue,N);
}
}
} }
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-2004 The Apache Software Foundation. * Copyright 1999-2004 The Apache Software Foundation.
* *
...@@ -21,20 +20,26 @@ ...@@ -21,20 +20,26 @@
*/ */
package com.sun.org.apache.xml.internal.security.c14n.implementations; package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set; import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import javax.xml.parsers.ParserConfigurationException;
import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; 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.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces; 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.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/** /**
* Implements &quot; <A * Implements &quot; <A
* HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML * HREF="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/">Exclusive XML
...@@ -47,6 +52,7 @@ import org.w3c.dom.Node; ...@@ -47,6 +52,7 @@ import org.w3c.dom.Node;
* <i>THIS </i> implementation is a complete rewrite of the algorithm. * <i>THIS </i> implementation is a complete rewrite of the algorithm.
* *
* @author Christian Geuer-Pollmann <geuerp@apache.org> * @author Christian Geuer-Pollmann <geuerp@apache.org>
* @version $Revision: 1.5 $
* @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#"> * @see <a href="http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/ Exclusive#">
* XML Canonicalization, Version 1.0</a> * XML Canonicalization, Version 1.0</a>
*/ */
...@@ -55,7 +61,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -55,7 +61,7 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
* This Set contains the names (Strings like "xmlns" or "xmlns:foo") of * This Set contains the names (Strings like "xmlns" or "xmlns:foo") of
* the inclusive namespaces. * the inclusive namespaces.
*/ */
TreeSet _inclusiveNSSet = null; TreeSet _inclusiveNSSet = new TreeSet();
static final String XMLNS_URI=Constants.NamespaceSpecNS; static final String XMLNS_URI=Constants.NamespaceSpecNS;
final SortedSet result = new TreeSet(COMPARE); final SortedSet result = new TreeSet(COMPARE);
/** /**
...@@ -143,10 +149,8 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -143,10 +149,8 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr N = (Attr) attrs.item(i);
String NName=N.getLocalName();
String NNodeValue=N.getNodeValue();
if (!XMLNS_URI.equals(N.getNamespaceURI())) { if (XMLNS_URI!=N.getNamespaceURI()) {
//Not a namespace definition. //Not a namespace definition.
//The Element is output element, add his prefix(if used) to visibyUtilized //The Element is output element, add his prefix(if used) to visibyUtilized
String prefix = N.getPrefix(); String prefix = N.getPrefix();
...@@ -157,6 +161,8 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -157,6 +161,8 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
result.add(N); result.add(N);
continue; continue;
} }
String NName=N.getLocalName();
String NNodeValue=N.getNodeValue();
if (ns.addMapping(NName, NNodeValue,N)) { if (ns.addMapping(NName, NNodeValue,N)) {
//New definition check if it is relative. //New definition check if it is relative.
...@@ -168,17 +174,17 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -168,17 +174,17 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
} }
} }
} }
String prefix;
if (E.getNamespaceURI() != null) { if (E.getNamespaceURI() != null) {
String prefix = E.getPrefix(); prefix = E.getPrefix();
if ((prefix == null) || (prefix.length() == 0)) { if ((prefix == null) || (prefix.length() == 0)) {
visiblyUtilized.add(XMLNS); prefix=XMLNS;
} else {
visiblyUtilized.add(prefix);
} }
} else { } else {
visiblyUtilized.add(XMLNS); prefix=XMLNS;
} }
visiblyUtilized.add(prefix);
//This can be optimezed by I don't have time //This can be optimezed by I don't have time
Iterator it=visiblyUtilized.iterator(); Iterator it=visiblyUtilized.iterator();
...@@ -211,12 +217,6 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -211,12 +217,6 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
} }
/** @inheritDoc */
public byte[] engineCanonicalizeXPathNodeSet(Set xpathNodeSet
) throws CanonicalizationException {
return engineCanonicalizeXPathNodeSet(xpathNodeSet,"");
}
/** /**
* @inheritDoc * @inheritDoc
* @param E * @param E
...@@ -236,21 +236,20 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -236,21 +236,20 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
//The prefix visibly utilized(in the attribute or in the name) in the element //The prefix visibly utilized(in the attribute or in the name) in the element
Set visiblyUtilized =null; Set visiblyUtilized =null;
//It's the output selected. //It's the output selected.
boolean isOutputElement = isVisible(E); boolean isOutputElement=isVisibleDO(E,ns.getLevel())==1;
if (isOutputElement) { if (isOutputElement) {
visiblyUtilized = (Set) this._inclusiveNSSet.clone(); visiblyUtilized = (Set) this._inclusiveNSSet.clone();
} }
for (int i = 0; i < attrsLength; i++) { for (int i = 0; i < attrsLength; i++) {
Attr N = (Attr) attrs.item(i); Attr N = (Attr) attrs.item(i);
String NName=N.getLocalName();
String NNodeValue=N.getNodeValue();
if ( !isVisible(N) ) {
//The node is not in the nodeset(if there is a nodeset)
continue;
}
if (!XMLNS_URI.equals(N.getNamespaceURI())) {
if (XMLNS_URI!=N.getNamespaceURI()) {
if ( !isVisible(N) ) {
//The node is not in the nodeset(if there is a nodeset)
continue;
}
//Not a namespace definition. //Not a namespace definition.
if (isOutputElement) { if (isOutputElement) {
//The Element is output element, add his prefix(if used) to visibyUtilized //The Element is output element, add his prefix(if used) to visibyUtilized
...@@ -263,6 +262,25 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -263,6 +262,25 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
} }
continue; continue;
} }
String NName=N.getLocalName();
if (isOutputElement && !isVisible(N) && NName!=XMLNS) {
ns.removeMappingIfNotRender(NName);
continue;
}
String NNodeValue=N.getNodeValue();
if (!isOutputElement && isVisible(N) && _inclusiveNSSet.contains(NName) && !ns.removeMappingIfRender(NName)) {
Node n=ns.addMappingAndRender(NName,NNodeValue,N);
if (n!=null) {
result.add(n);
if (C14nHelper.namespaceIsRelative(N)) {
Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
throw new CanonicalizationException(
"c14n.Canonicalizer.RelativeNamespace", exArgs);
}
}
}
if (ns.addMapping(NName, NNodeValue,N)) { if (ns.addMapping(NName, NNodeValue,N)) {
...@@ -306,18 +324,20 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase { ...@@ -306,18 +324,20 @@ public abstract class Canonicalizer20010315Excl extends CanonicalizerBase {
} }
result.add(key); result.add(key);
} }
} else /*if (_circunvented)*/ {
Iterator it=this._inclusiveNSSet.iterator();
while (it.hasNext()) {
String s=(String)it.next();
Attr key=ns.getMappingWithoutRendered(s);
if (key==null) {
continue;
}
result.add(key);
}
} }
return result.iterator(); return result.iterator();
} }
void circumventBugIfNeeded(XMLSignatureInput input) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException {
if (!input.isNeedsToBeExpanded() || _inclusiveNSSet.isEmpty())
return;
Document doc = null;
if (input.getSubNode() != null) {
doc=XMLUtils.getOwnerDocument(input.getSubNode());
} else {
doc=XMLUtils.getOwnerDocument(input.getNodeSet());
}
XMLUtils.circumventBug2650(doc);
}
} }
...@@ -28,6 +28,7 @@ import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer; ...@@ -28,6 +28,7 @@ import com.sun.org.apache.xml.internal.security.c14n.Canonicalizer;
/** /**
* Class Canonicalizer20010315ExclWithComments * Class Canonicalizer20010315ExclWithComments
* *
* @version $Revision: 1.5 $
*/ */
public class Canonicalizer20010315ExclWithComments public class Canonicalizer20010315ExclWithComments
extends Canonicalizer20010315Excl { extends Canonicalizer20010315Excl {
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* reserved comment block * reserved comment block
* DO NOT REMOVE OR ALTER! * DO NOT REMOVE OR ALTER!
*/ */
/* /*
* Copyright 1999-2004 The Apache Software Foundation. * Copyright 1999-2004 The Apache Software Foundation.
* *
......
package com.sun.org.apache.xml.internal.security.c14n.implementations;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
public class UtfHelpper {
final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException {
byte []result=(byte[]) cache.get(str);
if (result==null) {
result=getStringInUtf8(str);
cache.put(str,result);
}
out.write(result);
}
final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{
if (c < 0x80) {
out.write(c);
return;
}
if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
//No Surrogates in sun java
out.write(0x3f);
return;
}
int bias;
int write;
char ch;
if (c > 0x07FF) {
ch=(char)(c>>>12);
write=0xE0;
if (ch>0) {
write |= ( ch & 0x0F);
}
out.write(write);
write=0x80;
bias=0x3F;
} else {
write=0xC0;
bias=0x1F;
}
ch=(char)(c>>>6);
if (ch>0) {
write|= (ch & bias);
}
out.write(write);
out.write(0x80 | ((c) & 0x3F));
}
final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{
final int length=str.length();
int i=0;
char c;
while (i<length) {
c=str.charAt(i++);
if (c < 0x80) {
out.write(c);
continue;
}
if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
//No Surrogates in sun java
out.write(0x3f);
continue;
}
char ch;
int bias;
int write;
if (c > 0x07FF) {
ch=(char)(c>>>12);
write=0xE0;
if (ch>0) {
write |= ( ch & 0x0F);
}
out.write(write);
write=0x80;
bias=0x3F;
} else {
write=0xC0;
bias=0x1F;
}
ch=(char)(c>>>6);
if (ch>0) {
write|= (ch & bias);
}
out.write(write);
out.write(0x80 | ((c) & 0x3F));
}
}
public final static byte[] getStringInUtf8(final String str) {
final int length=str.length();
boolean expanded=false;
byte []result=new byte[length];
int i=0;
int out=0;
char c;
while (i<length) {
c=str.charAt(i++);
if ( c < 0x80 ) {
result[out++]=(byte)c;
continue;
}
if ((c >= 0xD800 && c <= 0xDBFF) || (c >= 0xDC00 && c <= 0xDFFF) ){
//No Surrogates in sun java
result[out++]=0x3f;
continue;
}
if (!expanded) {
byte newResult[]=new byte[3*length];
System.arraycopy(result, 0, newResult, 0, out);
result=newResult;
expanded=true;
}
char ch;
int bias;
byte write;
if (c > 0x07FF) {
ch=(char)(c>>>12);
write=(byte)0xE0;
if (ch>0) {
write |= ( ch & 0x0F);
}
result[out++]=write;
write=(byte)0x80;
bias=0x3F;
} else {
write=(byte)0xC0;
bias=0x1F;
}
ch=(char)(c>>>6);
if (ch>0) {
write|= (ch & bias);
}
result[out++]=write;
result[out++]=(byte)(0x80 | ((c) & 0x3F));/**/
}
if (expanded) {
byte newResult[]=new byte[out];
System.arraycopy(result, 0, newResult, 0, out);
result=newResult;
}
return result;
}
}
...@@ -108,84 +108,78 @@ public class XMLCipherInput { ...@@ -108,84 +108,78 @@ public class XMLCipherInput {
return null; return null;
} }
/** /**
* Internal method to get bytes in decryption mode * Internal method to get bytes in decryption mode
* @return the decripted bytes * @return the decripted bytes
* @throws XMLEncryptionException * @throws XMLEncryptionException
*/ */
private byte[] getDecryptBytes() throws XMLEncryptionException {
private byte[] getDecryptBytes() throws XMLEncryptionException {
String base64EncodedEncryptedOctets = null; String base64EncodedEncryptedOctets = null;
if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) { if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
// Fun time! // Fun time!
if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData");
CipherReference cr = _cipherData.getCipherReference(); CipherReference cr = _cipherData.getCipherReference();
// Need to wrap the uri in an Attribute node so that we can // Need to wrap the uri in an Attribute node so that we can
// Pass to the resource resolvers // Pass to the resource resolvers
Attr uriAttr = cr.getURIAsAttr(); Attr uriAttr = cr.getURIAsAttr();
XMLSignatureInput input = null; XMLSignatureInput input = null;
try { try {
ResourceResolver resolver = ResourceResolver resolver =
ResourceResolver.getInstance(uriAttr, null); ResourceResolver.getInstance(uriAttr, null);
input = resolver.resolve(uriAttr, null); input = resolver.resolve(uriAttr, null);
} catch (ResourceResolverException ex) { } catch (ResourceResolverException ex) {
throw new XMLEncryptionException("empty", ex); throw new XMLEncryptionException("empty", ex);
} }
if (input != null) { if (input != null) {
if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\"");
} } else {
else { logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\"");
if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); }
}
// Lets see if there are any transforms
// Lets see if there are any transforms Transforms transforms = cr.getTransforms();
Transforms transforms = cr.getTransforms(); if (transforms != null) {
if (transforms != null) { logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference");
if (logger.isLoggable(java.util.logging.Level.FINE)) logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); try {
try { com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms =
com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms = transforms.getDSTransforms();
transforms.getDSTransforms(); input = dsTransforms.performTransforms(input);
input = dsTransforms.performTransforms(input); } catch (TransformationException ex) {
} catch (TransformationException ex) { throw new XMLEncryptionException("empty", ex);
throw new XMLEncryptionException("empty", ex); }
} }
}
try {
try { return input.getBytes();
return input.getBytes(); } catch (IOException ex) {
} throw new XMLEncryptionException("empty", ex);
catch (IOException ex) { } catch (CanonicalizationException ex) {
throw new XMLEncryptionException("empty", ex); throw new XMLEncryptionException("empty", ex);
} catch (CanonicalizationException ex) { }
throw new XMLEncryptionException("empty", ex);
} // retrieve the cipher text
// retrieve the cipher text
} else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) { } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) {
CipherValue cv = _cipherData.getCipherValue(); base64EncodedEncryptedOctets =
base64EncodedEncryptedOctets = new String(cv.getValue()); _cipherData.getCipherValue().getValue();
} else { } else {
throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); 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); logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets);
byte[] encryptedBytes = null; byte[] encryptedBytes = null;
try { try {
encryptedBytes = Base64.decode(base64EncodedEncryptedOctets); encryptedBytes = Base64.decode(base64EncodedEncryptedOctets);
} catch (Base64DecodingException bde) { } catch (Base64DecodingException bde) {
throw new XMLEncryptionException("empty", bde); throw new XMLEncryptionException("empty", bde);
} }
return (encryptedBytes); return (encryptedBytes);
}
}
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册