1 2 package ch.ethz.ssh2.crypto.digest; 3 4 10 public final class HMAC implements Digest 11 { 12 Digest md; 13 byte[] k_xor_ipad; 14 byte[] k_xor_opad; 15 16 byte[] tmp; 17 18 int size; 19 20 public HMAC(Digest md, byte[] key, int size) 21 { 22 this.md = md; 23 this.size = size; 24 25 tmp = new byte[md.getDigestLength()]; 26 27 final int BLOCKSIZE = 64; 28 29 k_xor_ipad = new byte[BLOCKSIZE]; 30 k_xor_opad = new byte[BLOCKSIZE]; 31 32 if (key.length > BLOCKSIZE) 33 { 34 md.reset(); 35 md.update(key); 36 md.digest(tmp); 37 key = tmp; 38 } 39 40 System.arraycopy(key, 0, k_xor_ipad, 0, key.length); 41 System.arraycopy(key, 0, k_xor_opad, 0, key.length); 42 43 for (int i = 0; i < BLOCKSIZE; i++) 44 { 45 k_xor_ipad[i] ^= 0x36; 46 k_xor_opad[i] ^= 0x5C; 47 } 48 md.update(k_xor_ipad); 49 } 50 51 public final int getDigestLength() 52 { 53 return size; 54 } 55 56 public final void update(byte b) 57 { 58 md.update(b); 59 } 60 61 public final void update(byte[] b) 62 { 63 md.update(b); 64 } 65 66 public final void update(byte[] b, int off, int len) 67 { 68 md.update(b, off, len); 69 } 70 71 public final void reset() 72 { 73 md.reset(); 74 md.update(k_xor_ipad); 75 } 76 77 public final void digest(byte[] out) 78 { 79 digest(out, 0); 80 } 81 82 public final void digest(byte[] out, int off) 83 { 84 md.digest(tmp); 85 86 md.update(k_xor_opad); 87 md.update(tmp); 88 89 md.digest(tmp); 90 91 System.arraycopy(tmp, 0, out, off, size); 92 93 md.update(k_xor_ipad); 94 } 95 } 96 | Popular Tags |