1 package org.bouncycastle.crypto.digests;
4 * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
6 * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
7 * is the "endienness" of the word processing!
9 public class SHA1Digest
12 private static final int DIGEST_LENGTH = 20;
14 private int H1, H2, H3, H4, H5;
16 private int[] X = new int[80];
20 * Standard constructor
28 * Copy constructor. This will copy the state of the provided
31 public SHA1Digest(SHA1Digest t)
41 System.arraycopy(t.X, 0, X, 0, t.X.length);
45 public String getAlgorithmName()
50 public int getDigestSize()
55 protected void processWord(
59 X[xOff++] = ((in[inOff] & 0xff) << 24) | ((in[inOff + 1] & 0xff) << 16)
60 | ((in[inOff + 2] & 0xff) << 8) | ((in[inOff + 3] & 0xff));
68 private void unpackWord(
73 out[outOff] = (byte)(word >>> 24);
74 out[outOff + 1] = (byte)(word >>> 16);
75 out[outOff + 2] = (byte)(word >>> 8);
76 out[outOff + 3] = (byte)word;
79 protected void processLength(
87 X[14] = (int)(bitLength >>> 32);
88 X[15] = (int)(bitLength & 0xffffffff);
97 unpackWord(H1, out, outOff);
98 unpackWord(H2, out, outOff + 4);
99 unpackWord(H3, out, outOff + 8);
100 unpackWord(H4, out, outOff + 12);
101 unpackWord(H5, out, outOff + 16);
105 return DIGEST_LENGTH;
109 * reset the chaining variables
122 for (int i = 0; i != X.length; i++)
129 // Additive constants
131 private static final int Y1 = 0x5a827999;
132 private static final int Y2 = 0x6ed9eba1;
133 private static final int Y3 = 0x8f1bbcdc;
134 private static final int Y4 = 0xca62c1d6;
141 return ((u & v) | ((~u) & w));
157 return ((u & v) | (u & w) | (v & w));
160 private int rotateLeft(
164 return (x << n) | (x >>> (32 - n));
167 protected void processBlock()
170 // expand 16 word block into 80 word block.
172 for (int i = 16; i <= 79; i++)
174 X[i] = rotateLeft((X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]), 1);
178 // set up working variables.
189 for (int j = 0; j <= 19; j++)
191 int t = rotateLeft(A, 5) + f(B, C, D) + E + X[j] + Y1;
195 C = rotateLeft(B, 30);
203 for (int j = 20; j <= 39; j++)
205 int t = rotateLeft(A, 5) + h(B, C, D) + E + X[j] + Y2;
209 C = rotateLeft(B, 30);
217 for (int j = 40; j <= 59; j++)
219 int t = rotateLeft(A, 5) + g(B, C, D) + E + X[j] + Y3;
223 C = rotateLeft(B, 30);
231 for (int j = 60; j <= 79; j++)
233 int t = rotateLeft(A, 5) + h(B, C, D) + E + X[j] + Y4;
237 C = rotateLeft(B, 30);
249 // reset the offset and clean out the word buffer.
252 for (int i = 0; i != X.length; i++)