1 17 18 19 20 package org.apache.fop.util; 21 22 import java.security.MessageDigest ; 23 import java.security.NoSuchAlgorithmException ; 24 import java.util.Iterator ; 25 import java.util.Map ; 26 import java.util.TreeMap ; 27 28 import org.xml.sax.Attributes ; 29 import org.xml.sax.SAXException ; 30 import org.xml.sax.SAXNotRecognizedException ; 31 import org.xml.sax.SAXNotSupportedException ; 32 import org.xml.sax.helpers.XMLFilterImpl ; 33 34 43 public class DigestFilter extends XMLFilterImpl { 44 45 private MessageDigest digest; 46 private byte value[]; 47 private boolean isNamespaceAware; 48 49 public DigestFilter(String algorithm) throws NoSuchAlgorithmException { 50 digest = MessageDigest.getInstance(algorithm); 51 } 52 53 public byte[] getDigestValue() { 54 return value; 55 } 56 57 public String getDigestString() { 58 if (value != null) { 59 StringBuffer buffer = new StringBuffer (2 * value.length); 60 for (int i = 0; i < value.length; i++) { 61 int val = value[i]; 62 int hi = (val >> 4) & 0xF; 63 int lo = val & 0xF; 64 if (hi < 10) { 65 buffer.append((char) (hi + 0x30)); 66 } else { 67 buffer.append((char) (hi + 0x61 - 10)); 68 } 69 if (lo < 10) { 70 buffer.append((char) (lo + 0x30)); 71 } else { 72 buffer.append((char) (lo + 0x61 - 10)); 73 } 74 } 75 return buffer.toString(); 76 } else { 77 return null; 78 } 79 } 80 81 84 public void characters(char[] chars, int start, int length) 85 throws SAXException { 86 digest.update(new String (chars, start, length).getBytes()); 87 super.characters(chars, start, length); 88 } 89 90 93 public void endDocument() throws SAXException { 94 value = digest.digest(); 95 super.endDocument(); 96 } 97 98 101 public void startElement( 102 String url, 103 String localName, 104 String qName, 105 Attributes attr) 106 throws SAXException { 107 Map map = new TreeMap (); 108 if (isNamespaceAware) { 109 digest.update(url.getBytes()); 110 digest.update(localName.getBytes()); 111 for (int i = 0; i < attr.getLength(); i++) { 112 map.put( 113 attr.getLocalName(i) + attr.getURI(i), 114 attr.getValue(i)); 115 } 116 } else { 117 digest.update(qName.getBytes()); 118 for (int i = 0; i < attr.getLength(); i++) { 119 map.put(attr.getQName(i), attr.getValue(i)); 120 } 121 } 122 for (Iterator i = map.entrySet().iterator(); i.hasNext();) { 123 Map.Entry entry = (Map.Entry )i.next(); 124 digest.update(((String )entry.getKey()).getBytes()); 125 digest.update(((String )entry.getValue()).getBytes()); 126 } 127 super.startElement(url, localName, qName, attr); 128 } 129 130 131 134 public void setFeature(String feature, boolean value) 135 throws SAXNotRecognizedException , SAXNotSupportedException { 136 if(feature.equals("http://xml.org/sax/features/namespaces")) { 137 isNamespaceAware = value; 138 } 139 super.setFeature(feature, value); 140 } 141 142 } 143 | Popular Tags |