1/*
2 * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.security.provider;
27
28import java.util.Objects;
29
30import jdk.internal.HotSpotIntrinsicCandidate;
31import static sun.security.provider.ByteArrayAccess.*;
32
33/**
34 * This class implements the Secure Hash Algorithm SHA-384 and SHA-512
35 * developed by the National Institute of Standards and Technology along
36 * with the National Security Agency.
37 *
38 * The two algorithms are almost identical. This file contains a base
39 * class SHA5 and two nested static subclasses as the classes to be used
40 * by the JCA framework.
41 *
42 * <p>It implements java.security.MessageDigestSpi, and can be used
43 * through Java Cryptography Architecture (JCA), as a pluggable
44 * MessageDigest implementation.
45 *
46 * @since       1.4.2
47 * @author      Valerie Peng
48 * @author      Andreas Sterbenz
49 */
50abstract class SHA5 extends DigestBase {
51
52    private static final int ITERATION = 80;
53    // Constants for each round/iteration
54    private static final long[] ROUND_CONSTS = {
55        0x428A2F98D728AE22L, 0x7137449123EF65CDL, 0xB5C0FBCFEC4D3B2FL,
56        0xE9B5DBA58189DBBCL, 0x3956C25BF348B538L, 0x59F111F1B605D019L,
57        0x923F82A4AF194F9BL, 0xAB1C5ED5DA6D8118L, 0xD807AA98A3030242L,
58        0x12835B0145706FBEL, 0x243185BE4EE4B28CL, 0x550C7DC3D5FFB4E2L,
59        0x72BE5D74F27B896FL, 0x80DEB1FE3B1696B1L, 0x9BDC06A725C71235L,
60        0xC19BF174CF692694L, 0xE49B69C19EF14AD2L, 0xEFBE4786384F25E3L,
61        0x0FC19DC68B8CD5B5L, 0x240CA1CC77AC9C65L, 0x2DE92C6F592B0275L,
62        0x4A7484AA6EA6E483L, 0x5CB0A9DCBD41FBD4L, 0x76F988DA831153B5L,
63        0x983E5152EE66DFABL, 0xA831C66D2DB43210L, 0xB00327C898FB213FL,
64        0xBF597FC7BEEF0EE4L, 0xC6E00BF33DA88FC2L, 0xD5A79147930AA725L,
65        0x06CA6351E003826FL, 0x142929670A0E6E70L, 0x27B70A8546D22FFCL,
66        0x2E1B21385C26C926L, 0x4D2C6DFC5AC42AEDL, 0x53380D139D95B3DFL,
67        0x650A73548BAF63DEL, 0x766A0ABB3C77B2A8L, 0x81C2C92E47EDAEE6L,
68        0x92722C851482353BL, 0xA2BFE8A14CF10364L, 0xA81A664BBC423001L,
69        0xC24B8B70D0F89791L, 0xC76C51A30654BE30L, 0xD192E819D6EF5218L,
70        0xD69906245565A910L, 0xF40E35855771202AL, 0x106AA07032BBD1B8L,
71        0x19A4C116B8D2D0C8L, 0x1E376C085141AB53L, 0x2748774CDF8EEB99L,
72        0x34B0BCB5E19B48A8L, 0x391C0CB3C5C95A63L, 0x4ED8AA4AE3418ACBL,
73        0x5B9CCA4F7763E373L, 0x682E6FF3D6B2B8A3L, 0x748F82EE5DEFB2FCL,
74        0x78A5636F43172F60L, 0x84C87814A1F0AB72L, 0x8CC702081A6439ECL,
75        0x90BEFFFA23631E28L, 0xA4506CEBDE82BDE9L, 0xBEF9A3F7B2C67915L,
76        0xC67178F2E372532BL, 0xCA273ECEEA26619CL, 0xD186B8C721C0C207L,
77        0xEADA7DD6CDE0EB1EL, 0xF57D4F7FEE6ED178L, 0x06F067AA72176FBAL,
78        0x0A637DC5A2C898A6L, 0x113F9804BEF90DAEL, 0x1B710B35131C471BL,
79        0x28DB77F523047D84L, 0x32CAAB7B40C72493L, 0x3C9EBE0A15C9BEBCL,
80        0x431D67C49C100D4CL, 0x4CC5D4BECB3E42B6L, 0x597F299CFC657E2AL,
81        0x5FCB6FAB3AD6FAECL, 0x6C44198C4A475817L
82    };
83
84    // buffer used by implCompress()
85    private long[] W;
86
87    // state of this object
88    private long[] state;
89
90    // initial state value. different between SHA-384 and SHA-512
91    private final long[] initialHashes;
92
93    /**
94     * Creates a new SHA object.
95     */
96    SHA5(String name, int digestLength, long[] initialHashes) {
97        super(name, digestLength, 128);
98        this.initialHashes = initialHashes;
99        state = new long[8];
100        W = new long[80];
101        implReset();
102    }
103
104    final void implReset() {
105        System.arraycopy(initialHashes, 0, state, 0, state.length);
106    }
107
108    final void implDigest(byte[] out, int ofs) {
109        long bitsProcessed = bytesProcessed << 3;
110
111        int index = (int)bytesProcessed & 0x7f;
112        int padLen = (index < 112) ? (112 - index) : (240 - index);
113        engineUpdate(padding, 0, padLen + 8);
114
115        i2bBig4((int)(bitsProcessed >>> 32), buffer, 120);
116        i2bBig4((int)bitsProcessed, buffer, 124);
117        implCompress(buffer, 0);
118
119        int len = engineGetDigestLength();
120        if (len == 28) {
121            // Special case for SHA-512/224
122            l2bBig(state, 0, out, ofs, 24);
123            i2bBig4((int)(state[3] >> 32), out, ofs + 24);
124        } else {
125            l2bBig(state, 0, out, ofs, len);
126        }
127    }
128
129    /**
130     * logical function ch(x,y,z) as defined in spec:
131     * @return (x and y) xor ((complement x) and z)
132     * @param x long
133     * @param y long
134     * @param z long
135     */
136    private static long lf_ch(long x, long y, long z) {
137        return (x & y) ^ ((~x) & z);
138    }
139
140    /**
141     * logical function maj(x,y,z) as defined in spec:
142     * @return (x and y) xor (x and z) xor (y and z)
143     * @param x long
144     * @param y long
145     * @param z long
146     */
147    private static long lf_maj(long x, long y, long z) {
148        return (x & y) ^ (x & z) ^ (y & z);
149    }
150
151    /**
152     * logical function R(x,s) - right shift
153     * @return x right shift for s times
154     * @param x long
155     * @param s int
156     */
157    private static long lf_R(long x, int s) {
158        return (x >>> s);
159    }
160
161    /**
162     * logical function S(x,s) - right rotation
163     * @return x circular right shift for s times
164     * @param x long
165     * @param s int
166     */
167    private static long lf_S(long x, int s) {
168        return (x >>> s) | (x << (64 - s));
169    }
170
171    /**
172     * logical function sigma0(x) - xor of results of right rotations
173     * @return S(x,28) xor S(x,34) xor S(x,39)
174     * @param x long
175     */
176    private static long lf_sigma0(long x) {
177        return lf_S(x, 28) ^ lf_S(x, 34) ^ lf_S(x, 39);
178    }
179
180    /**
181     * logical function sigma1(x) - xor of results of right rotations
182     * @return S(x,14) xor S(x,18) xor S(x,41)
183     * @param x long
184     */
185    private static long lf_sigma1(long x) {
186        return lf_S(x, 14) ^ lf_S(x, 18) ^ lf_S(x, 41);
187    }
188
189    /**
190     * logical function delta0(x) - xor of results of right shifts/rotations
191     * @return long
192     * @param x long
193     */
194    private static long lf_delta0(long x) {
195        return lf_S(x, 1) ^ lf_S(x, 8) ^ lf_R(x, 7);
196    }
197
198    /**
199     * logical function delta1(x) - xor of results of right shifts/rotations
200     * @return long
201     * @param x long
202     */
203    private static long lf_delta1(long x) {
204        return lf_S(x, 19) ^ lf_S(x, 61) ^ lf_R(x, 6);
205    }
206
207    /**
208     * Compute the hash for the current block.
209     *
210     * This is in the same vein as Peter Gutmann's algorithm listed in
211     * the back of Applied Cryptography, Compact implementation of
212     * "old" NIST Secure Hash Algorithm.
213     */
214    final void implCompress(byte[] buf, int ofs) {
215        implCompressCheck(buf, ofs);
216        implCompress0(buf, ofs);
217    }
218
219    private void implCompressCheck(byte[] buf, int ofs) {
220        Objects.requireNonNull(buf);
221
222        // The checks performed by the method 'b2iBig128'
223        // are sufficient for the case when the method
224        // 'implCompressImpl' is replaced with a compiler
225        // intrinsic.
226        b2lBig128(buf, ofs, W);
227    }
228
229    // The method 'implCompressImpl' seems not to use its parameters.
230    // The method can, however, be replaced with a compiler intrinsic
231    // that operates directly on the array 'buf' (starting from
232    // offset 'ofs') and not on array 'W', therefore 'buf' and 'ofs'
233    // must be passed as parameter to the method.
234    @HotSpotIntrinsicCandidate
235    private final void implCompress0(byte[] buf, int ofs) {
236        // The first 16 longs are from the byte stream, compute the rest of
237        // the W[]'s
238        for (int t = 16; t < ITERATION; t++) {
239            W[t] = lf_delta1(W[t-2]) + W[t-7] + lf_delta0(W[t-15])
240                   + W[t-16];
241        }
242
243        long a = state[0];
244        long b = state[1];
245        long c = state[2];
246        long d = state[3];
247        long e = state[4];
248        long f = state[5];
249        long g = state[6];
250        long h = state[7];
251
252        for (int i = 0; i < ITERATION; i++) {
253            long T1 = h + lf_sigma1(e) + lf_ch(e,f,g) + ROUND_CONSTS[i] + W[i];
254            long T2 = lf_sigma0(a) + lf_maj(a,b,c);
255            h = g;
256            g = f;
257            f = e;
258            e = d + T1;
259            d = c;
260            c = b;
261            b = a;
262            a = T1 + T2;
263        }
264        state[0] += a;
265        state[1] += b;
266        state[2] += c;
267        state[3] += d;
268        state[4] += e;
269        state[5] += f;
270        state[6] += g;
271        state[7] += h;
272    }
273
274    public Object clone() throws CloneNotSupportedException {
275        SHA5 copy = (SHA5) super.clone();
276        copy.state = copy.state.clone();
277        copy.W = new long[80];
278        return copy;
279    }
280
281    /**
282     * SHA-512 implementation class.
283     */
284    public static final class SHA512 extends SHA5 {
285
286        private static final long[] INITIAL_HASHES = {
287            0x6a09e667f3bcc908L, 0xbb67ae8584caa73bL,
288            0x3c6ef372fe94f82bL, 0xa54ff53a5f1d36f1L,
289            0x510e527fade682d1L, 0x9b05688c2b3e6c1fL,
290            0x1f83d9abfb41bd6bL, 0x5be0cd19137e2179L
291        };
292
293        public SHA512() {
294            super("SHA-512", 64, INITIAL_HASHES);
295        }
296    }
297
298    /**
299     * SHA-384 implementation class.
300     */
301    public static final class SHA384 extends SHA5 {
302
303        private static final long[] INITIAL_HASHES = {
304            0xcbbb9d5dc1059ed8L, 0x629a292a367cd507L,
305            0x9159015a3070dd17L, 0x152fecd8f70e5939L,
306            0x67332667ffc00b31L, 0x8eb44a8768581511L,
307            0xdb0c2e0d64f98fa7L, 0x47b5481dbefa4fa4L
308        };
309
310        public SHA384() {
311            super("SHA-384", 48, INITIAL_HASHES);
312        }
313    }
314    public static final class SHA512_224 extends SHA5 {
315
316        private static final long[] INITIAL_HASHES = {
317                0x8C3D37C819544DA2L, 0x73E1996689DCD4D6L,
318                0x1DFAB7AE32FF9C82L, 0x679DD514582F9FCFL,
319                0x0F6D2B697BD44DA8L, 0x77E36F7304C48942L,
320                0x3F9D85A86A1D36C8L, 0x1112E6AD91D692A1L
321        };
322
323        public SHA512_224() {
324            super("SHA-512/224", 28, INITIAL_HASHES);
325        }
326    }
327
328    public static final class SHA512_256 extends SHA5 {
329
330        private static final long[] INITIAL_HASHES = {
331                0x22312194FC2BF72CL, 0x9F555FA3C84C64C2L,
332                0x2393B86B6F53B151L, 0x963877195940EABDL,
333                0x96283EE2A88EFFE3L, 0xBE5E1E2553863992L,
334                0x2B0199FC2C85B8AAL, 0x0EB72DDC81C52CA2L
335        };
336
337        public SHA512_256() {
338            super("SHA-512/256", 32, INITIAL_HASHES);
339        }
340    }
341}
342