1 7 package org.jboss.crypto.digest; 8 9 import java.io.ByteArrayOutputStream ; 10 import java.security.MessageDigest ; 11 import java.security.MessageDigestSpi ; 12 import java.security.NoSuchAlgorithmException ; 13 import java.security.ProviderException ; 14 import java.util.Arrays ; 15 16 26 public class SHAReverseInterleave extends MessageDigestSpi 27 { 28 private static final int SHA_HASH_LEN = 20; 29 30 private ByteArrayOutputStream evenBytes; 31 private ByteArrayOutputStream oddBytes; 32 private int count; 33 private boolean skipLeadingZeros; 34 private MessageDigest sha; 35 36 40 public SHAReverseInterleave() 41 { 42 try 43 { 44 sha = MessageDigest.getInstance("SHA"); 45 } 46 catch(NoSuchAlgorithmException e) 47 { 48 throw new ProviderException ("Failed to obtain SHA MessageDigest"); 49 } 50 evenBytes = new ByteArrayOutputStream (); 51 oddBytes = new ByteArrayOutputStream (); 52 engineReset(); 53 } 54 55 protected int engineGetDigestLength() 56 { 57 return 2 * SHA_HASH_LEN; 58 } 59 60 70 protected byte[] engineDigest() 71 { 72 byte[] E = evenBytes.toByteArray(); 73 int length = E.length; 75 if( count % 2 == 1 ) 76 length --; 77 byte[] tmp = new byte[length]; 79 for(int i = 0; i < length; i ++) 80 { 81 tmp[i] = E[E.length - i - 1]; 82 System.out.println("E["+i+"] = "+tmp[i]); 83 } 84 E = tmp; 85 byte[] G = sha.digest(E); 86 87 byte[] F = oddBytes.toByteArray(); 88 tmp = new byte[F.length]; 90 for(int i = 0; i < F.length; i ++) 91 { 92 tmp[i] = F[F.length - i - 1]; 93 System.out.println("F["+i+"] = "+tmp[i]); 94 } 95 F = tmp; 96 sha.reset(); 97 byte[] H = sha.digest(F); 98 length = G.length + H.length; 99 byte[] digest = new byte[length]; 100 for(int i = 0; i < G.length; ++i) 101 digest[2 * i] = G[i]; 102 for(int i = 0; i < H.length; ++i) 103 digest[2 * i + 1] = H[i]; 104 engineReset(); 105 return digest; 106 } 107 108 111 protected void engineReset() 112 { 113 skipLeadingZeros = true; 114 count = 0; 115 evenBytes.reset(); 116 oddBytes.reset(); 117 sha.reset(); 118 } 119 120 125 protected void engineUpdate(byte input) 126 { 127 if( skipLeadingZeros == true && input == 0 ) 128 return; 129 skipLeadingZeros = false; 130 if( count % 2 == 0 ) 131 evenBytes.write(input); 132 else 133 oddBytes.write(input); 134 count ++; 135 } 136 137 146 protected void engineUpdate(byte[] input, int offset, int len) 147 { 148 for(int i = offset; i < offset+len; i ++) 149 engineUpdate(input[i]); 150 } 151 152 } 153 | Popular Tags |