1 /*
   2  * Copyright (c) 2016, 2020, 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 
  26 package sun.security.provider;
  27 
  28 import static sun.security.provider.ByteArrayAccess.*;
  29 import java.nio.*;
  30 import java.util.*;
  31 import java.security.*;
  32 
  33 /**
  34  * This class implements the Secure Hash Algorithm SHA-3 developed by
  35  * the National Institute of Standards and Technology along with the
  36  * National Security Agency as defined in FIPS PUB 202.
  37  *
  38  * <p>It implements java.security.MessageDigestSpi, and can be used
  39  * through Java Cryptography Architecture (JCA), as a pluggable
  40  * MessageDigest implementation.
  41  *
  42  * @since       9
  43  * @author      Valerie Peng
  44  */
  45 abstract class SHA3 extends DigestBase {
  46 
  47     private static final int WIDTH = 200; // in bytes, e.g. 1600 bits
  48     private static final int DM = 5; // dimension of lanes
  49 
  50     private static final int NR = 24; // number of rounds
  51 
  52     // precomputed round constants needed by the step mapping Iota
  53     private static final long[] RC_CONSTANTS = {
  54         0x01L, 0x8082L, 0x800000000000808aL,
  55         0x8000000080008000L, 0x808bL, 0x80000001L,
  56         0x8000000080008081L, 0x8000000000008009L, 0x8aL,
  57         0x88L, 0x80008009L, 0x8000000aL,
  58         0x8000808bL, 0x800000000000008bL, 0x8000000000008089L,
  59         0x8000000000008003L, 0x8000000000008002L, 0x8000000000000080L,
  60         0x800aL, 0x800000008000000aL, 0x8000000080008081L,
  61         0x8000000000008080L, 0x80000001L, 0x8000000080008008L,
  62     };
  63 
  64     private final byte suffix;
  65     private byte[] state = new byte[WIDTH];
  66     private long[] lanes = new long[DM*DM];
  67 
  68     /**
  69      * Creates a new SHA-3 object.
  70      */
  71     SHA3(String name, int digestLength, byte suffix, int c) {
  72         super(name, digestLength, (WIDTH - c));
  73         this.suffix = suffix;
  74     }
  75 
  76     /**
  77      * Core compression function. Processes blockSize bytes at a time
  78      * and updates the state of this object.
  79      */
  80     void implCompress(byte[] b, int ofs) {
  81         for (int i = 0; i < buffer.length; i++) {
  82             state[i] ^= b[ofs++];
  83         }
  84         keccak();
  85     }
  86 
  87     /**
  88      * Return the digest. Subclasses do not need to reset() themselves,
  89      * DigestBase calls implReset() when necessary.
  90      */
  91     void implDigest(byte[] out, int ofs) {
  92         int numOfPadding =
  93             setPaddingBytes(suffix, buffer, (int)(bytesProcessed % buffer.length));
  94         if (numOfPadding < 1) {
  95             throw new ProviderException("Incorrect pad size: " + numOfPadding);
  96         }
  97         for (int i = 0; i < buffer.length; i++) {
  98             state[i] ^= buffer[i];
  99         }
 100         keccak();
 101         System.arraycopy(state, 0, out, ofs, engineGetDigestLength());
 102     }
 103 
 104     /**
 105      * Resets the internal state to start a new hash.
 106      */
 107     void implReset() {
 108         Arrays.fill(state, (byte)0);
 109         Arrays.fill(lanes, 0L);
 110     }
 111 
 112     /**
 113      * Utility function for padding the specified data based on the
 114      * pad10*1 algorithm (section 5.1) and the 2-bit suffix "01" required
 115      * for SHA-3 hash (section 6.1).
 116      */
 117     private static int setPaddingBytes(byte suffix, byte[] in, int len) {
 118         if (len != in.length) {
 119             // erase leftover values
 120             Arrays.fill(in, len, in.length, (byte)0);
 121             // directly store the padding bytes into the input
 122             // as the specified buffer is allocated w/ size = rateR
 123             in[len] |= suffix;
 124             in[in.length - 1] |= (byte) 0x80;
 125         }
 126         return (in.length - len);
 127     }
 128 
 129     /**
 130      * Utility function for transforming the specified byte array 's'
 131      * into array of lanes 'm' as defined in section 3.1.2.
 132      */
 133     private static void bytes2Lanes(byte[] s, long[] m) {
 134         int sOfs = 0;
 135         // Conversion traverses along x-axis before y-axis
 136         for (int y = 0; y < DM; y++, sOfs += 40) {
 137             b2lLittle(s, sOfs, m, DM*y, 40);
 138         }
 139     }
 140 
 141     /**
 142      * Utility function for transforming the specified array of
 143      * lanes 'm' into a byte array 's' as defined in section 3.1.3.
 144      */
 145     private static void lanes2Bytes(long[] m, byte[] s) {
 146         int sOfs = 0;
 147         // Conversion traverses along x-axis before y-axis
 148         for (int y = 0; y < DM; y++, sOfs += 40) {
 149             l2bLittle(m, DM*y, s, sOfs, 40);
 150         }
 151     }
 152 
 153     /**
 154      * Step mapping Theta as defined in section 3.2.1 .
 155      */
 156     private static long[] smTheta(long[] a) {
 157         long c0 = a[0]^a[5]^a[10]^a[15]^a[20];
 158         long c1 = a[1]^a[6]^a[11]^a[16]^a[21];
 159         long c2 = a[2]^a[7]^a[12]^a[17]^a[22];
 160         long c3 = a[3]^a[8]^a[13]^a[18]^a[23];
 161         long c4 = a[4]^a[9]^a[14]^a[19]^a[24];
 162         long d0 = c4 ^ Long.rotateLeft(c1, 1);
 163         long d1 = c0 ^ Long.rotateLeft(c2, 1);
 164         long d2 = c1 ^ Long.rotateLeft(c3, 1);
 165         long d3 = c2 ^ Long.rotateLeft(c4, 1);
 166         long d4 = c3 ^ Long.rotateLeft(c0, 1);
 167         for (int y = 0; y < a.length; y += DM) {
 168             a[y] ^= d0;
 169             a[y+1] ^= d1;
 170             a[y+2] ^= d2;
 171             a[y+3] ^= d3;
 172             a[y+4] ^= d4;
 173         }
 174         return a;
 175     }
 176 
 177     /**
 178      * Merged Step mapping Rho (section 3.2.2) and Pi (section 3.2.3).
 179      * for performance. Optimization is achieved by precalculating
 180      * shift constants for the following loop
 181      *   int xNext, yNext;
 182      *   for (int t = 0, x = 1, y = 0; t <= 23; t++, x = xNext, y = yNext) {
 183      *        int numberOfShift = ((t + 1)*(t + 2)/2) % 64;
 184      *        a[y][x] = Long.rotateLeft(a[y][x], numberOfShift);
 185      *        xNext = y;
 186      *        yNext = (2 * x + 3 * y) % DM;
 187      *   }
 188      * and with inplace permutation.
 189      */
 190     private static long[] smPiRho(long[] a) {
 191         long tmp = Long.rotateLeft(a[10], 3);
 192         a[10] = Long.rotateLeft(a[1], 1);
 193         a[1] = Long.rotateLeft(a[6], 44);
 194         a[6] = Long.rotateLeft(a[9], 20);
 195         a[9] = Long.rotateLeft(a[22], 61);
 196         a[22] = Long.rotateLeft(a[14], 39);
 197         a[14] = Long.rotateLeft(a[20], 18);
 198         a[20] = Long.rotateLeft(a[2], 62);
 199         a[2] = Long.rotateLeft(a[12], 43);
 200         a[12] = Long.rotateLeft(a[13], 25);
 201         a[13] = Long.rotateLeft(a[19], 8);
 202         a[19] = Long.rotateLeft(a[23], 56);
 203         a[23] = Long.rotateLeft(a[15], 41);
 204         a[15] = Long.rotateLeft(a[4], 27);
 205         a[4] = Long.rotateLeft(a[24], 14);
 206         a[24] = Long.rotateLeft(a[21], 2);
 207         a[21] = Long.rotateLeft(a[8], 55);
 208         a[8] = Long.rotateLeft(a[16], 45);
 209         a[16] = Long.rotateLeft(a[5], 36);
 210         a[5] = Long.rotateLeft(a[3], 28);
 211         a[3] = Long.rotateLeft(a[18], 21);
 212         a[18] = Long.rotateLeft(a[17], 15);
 213         a[17] = Long.rotateLeft(a[11], 10);
 214         a[11] = Long.rotateLeft(a[7], 6);
 215         a[7] = tmp;
 216         return a;
 217     }
 218 
 219     /**
 220      * Step mapping Chi as defined in section 3.2.4.
 221      */
 222     private static long[] smChi(long[] a) {
 223         for (int y = 0; y < a.length; y+=DM) {
 224             long ay0 = a[y];
 225             long ay1 = a[y+1];
 226             long ay2 = a[y+2];
 227             long ay3 = a[y+3];
 228             long ay4 = a[y+4];
 229             a[y] = ay0 ^ ((~ay1) & ay2);
 230             a[y+1] = ay1 ^ ((~ay2) & ay3);
 231             a[y+2] = ay2 ^ ((~ay3) & ay4);
 232             a[y+3] = ay3 ^ ((~ay4) & ay0);
 233             a[y+4] = ay4 ^ ((~ay0) & ay1);
 234         }
 235         return a;
 236     }
 237 
 238     /**
 239      * Step mapping Iota as defined in section 3.2.5.
 240      */
 241     private static long[] smIota(long[] a, int rndIndex) {
 242         a[0] ^= RC_CONSTANTS[rndIndex];
 243         return a;
 244     }
 245 
 246     /**
 247      * The function Keccak as defined in section 5.2 with
 248      * rate r = 1600 and capacity c = (digest length x 2).
 249      */
 250     private void keccak() {
 251         // convert the 200-byte state into 25 lanes
 252         bytes2Lanes(state, lanes);
 253         // process the lanes through step mappings
 254         for (int ir = 0; ir < NR; ir++) {
 255             smIota(smChi(smPiRho(smTheta(lanes))), ir);
 256         }
 257         // convert the resulting 25 lanes back into 200-byte state
 258         lanes2Bytes(lanes, state);
 259     }
 260 
 261     public Object clone() throws CloneNotSupportedException {
 262         SHA3 copy = (SHA3) super.clone();
 263         copy.state = copy.state.clone();
 264         copy.lanes = new long[DM*DM];
 265         return copy;
 266     }
 267 
 268     /**
 269      * SHA3-224 implementation class.
 270      */
 271     public static final class SHA224 extends SHA3 {
 272         public SHA224() {
 273             super("SHA3-224", 28, (byte)0x06, 56);
 274         }
 275     }
 276 
 277     /**
 278      * SHA3-256 implementation class.
 279      */
 280     public static final class SHA256 extends SHA3 {
 281         public SHA256() {
 282             super("SHA3-256", 32, (byte)0x06, 64);
 283         }
 284     }
 285 
 286     /**
 287      * SHAs-384 implementation class.
 288      */
 289     public static final class SHA384 extends SHA3 {
 290         public SHA384() {
 291             super("SHA3-384", 48, (byte)0x06, 96);
 292         }
 293     }
 294 
 295     /**
 296      * SHA3-512 implementation class.
 297      */
 298     public static final class SHA512 extends SHA3 {
 299         public SHA512() {
 300             super("SHA3-512", 64, (byte)0x06, 128);
 301         }
 302     }
 303 }