View Javadoc
1   /*
2    * GordianKnot: Security Suite
3    * Copyright 2012-2026. Tony Washer
4    *
5    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
6    * use this file except in compliance with the License.  You may obtain a copy
7    * of the License at
8    *
9    *   http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
14   * License for the specific language governing permissions and limitations under
15   * the License.
16   */
17  package io.github.tonywasher.joceanus.gordianknot.impl.ext.digests;
18  
19  import org.bouncycastle.util.Memoable;
20  import org.bouncycastle.util.Pack;
21  
22  /**
23   * Blake2b digest.
24   */
25  @SuppressWarnings("checkstyle:MagicNumber")
26  public class GordianBlake2bDigest
27          extends GordianBlake2Base {
28      /**
29       * Number of Rounds.
30       */
31      private static final int ROUNDS = 12;
32  
33      /**
34       * Block length.
35       */
36      private static final int BLOCK_LENGTH_BYTES = NUMWORDS * Long.BYTES << 1;
37  
38      /**
39       * Blake2b Initialization Vector.
40       */
41      private static final long[] IV = {
42              // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19.
43              // The same as SHA-512 IV.
44  
45              0x6a09e667f3bcc908L, 0xbb67ae8584caa73bL, 0x3c6ef372fe94f82bL,
46              0xa54ff53a5f1d36f1L, 0x510e527fade682d1L, 0x9b05688c2b3e6c1fL,
47              0x1f83d9abfb41bd6bL, 0x5be0cd19137e2179L
48      };
49  
50      /**
51       * The state.
52       */
53      private final long[] theH = new long[NUMWORDS];
54  
55      /**
56       * The workBuffer.
57       */
58      private final long[] theV = new long[NUMWORDS << 1];
59  
60      /**
61       * The messageBuffer.
62       */
63      private final long[] theM = new long[NUMWORDS << 1];
64  
65      /**
66       * Low Counter.
67       */
68      private long t0;
69  
70      /**
71       * High Counter.
72       */
73      private long t1;
74  
75      /**
76       * Constructor.
77       */
78      public GordianBlake2bDigest() {
79          /* Default to 512 bits */
80          this(512);
81      }
82  
83      /**
84       * Constructor.
85       *
86       * @param pLength the digest length in bits.
87       */
88      public GordianBlake2bDigest(final int pLength) {
89          /* Initialise underlying class */
90          super(ROUNDS, BLOCK_LENGTH_BYTES);
91  
92          /* Check digest length */
93          if ((pLength % Byte.SIZE) != 0 || pLength < 0 || pLength > 512) {
94              throw new IllegalArgumentException("Incorrect digest length");
95          }
96          setDigestLength(pLength / Byte.SIZE);
97          activateH();
98      }
99  
100     /**
101      * Constructor.
102      *
103      * @param pSource the source digest.
104      */
105     private GordianBlake2bDigest(final GordianBlake2bDigest pSource) {
106         /* Initialise underlying class */
107         super(pSource);
108 
109         /* Initialise from source */
110         reset((Memoable) pSource);
111     }
112 
113     @Override
114     public String getAlgorithmName() {
115         return "Blake2b-" + getDigestSize() * Byte.SIZE;
116     }
117 
118     @Override
119     public int getByteLength() {
120         return BLOCK_LENGTH_BYTES;
121     }
122 
123     @Override
124     public void reset() {
125         /* Reset counter */
126         t0 = 0L;
127         t1 = 0L;
128 
129         /* reset underlying class */
130         super.reset();
131     }
132 
133     @Override
134     public void reset(final Memoable pSource) {
135         /* Access source */
136         final GordianBlake2bDigest mySource = (GordianBlake2bDigest) pSource;
137 
138         /* reset underlying class */
139         super.reset(mySource);
140 
141         /* Reset counter */
142         t0 = mySource.t0;
143         t1 = mySource.t1;
144 
145         /* Copy state */
146         System.arraycopy(mySource.theH, 0, theH, 0, theH.length);
147     }
148 
149     @Override
150     public GordianBlake2bDigest copy() {
151         return new GordianBlake2bDigest(this);
152     }
153 
154     @Override
155     void adjustCounter(final int pCount) {
156         t0 += pCount;
157         if (t0 == 0) {
158             t1++;
159         }
160     }
161 
162     @Override
163     void completeCounter(final int pCount) {
164         t0 += pCount;
165         if (pCount > 0 && t0 == 0) {
166             t1++;
167         }
168     }
169 
170     @Override
171     void outputDigest(final byte[] pOut,
172                       final int pOutOffset) {
173         /* Loop to provide the output */
174         final int myDigestLen = getDigestSize();
175         for (int i = 0, j = 0; i < NUMWORDS && j < myDigestLen; i++, j += Long.BYTES) {
176             /* Convert the next word to bytes */
177             final byte[] bytes = Pack.longToLittleEndian(theH[i]);
178 
179             if (j + Long.BYTES < myDigestLen) {
180                 System.arraycopy(bytes, 0, pOut, pOutOffset + j, Long.BYTES);
181             } else {
182                 System.arraycopy(bytes, 0, pOut, pOutOffset + j, myDigestLen - j);
183             }
184         }
185     }
186 
187     @Override
188     void activateH() {
189         /* Initialise from IV */
190         System.arraycopy(IV, 0, theH, 0, IV.length);
191 
192         /* Initialise first word */
193         theH[0] ^= getDigestSize() | (getKeyLen() << Byte.SIZE);
194         theH[0] ^= (getFanOut() | (getMaxDepth() << Byte.SIZE)) << Short.SIZE;
195         theH[0] ^= ((long) getLeafLen()) << Integer.SIZE;
196 
197         /* Initialise second word */
198         theH[1] ^= getNodeOffset() | (((long) getXofLen()) << Integer.SIZE);
199 
200         /* Initialise third word */
201         theH[2] ^= (getNodeDepth() | (getInnerLen() << Byte.SIZE));
202 
203         /* Build salt section */
204         final byte[] mySalt = getSalt();
205         if (mySalt != null) {
206             theH[4] ^= Pack.littleEndianToLong(mySalt, 0);
207             theH[5] ^= Pack.littleEndianToLong(mySalt, Long.BYTES);
208         }
209 
210         /* Build personalisation section */
211         final byte[] myPersonal = getPersonal();
212         if (myPersonal != null) {
213             theH[6] ^= Pack.littleEndianToLong(myPersonal, 0);
214             theH[7] ^= Pack.littleEndianToLong(myPersonal, Long.BYTES);
215         }
216 
217         /* Initialise any keyBlock */
218         initKeyBlock();
219     }
220 
221     @Override
222     void initV() {
223         /* Copy in H and IV */
224         System.arraycopy(theH, 0, theV, 0, NUMWORDS);
225         System.arraycopy(IV, 0, theV, NUMWORDS, NUMWORDS);
226 
227         /* Fold in counters */
228         theV[12] ^= t0;
229         theV[13] ^= t1;
230 
231         /* Fold in finalisation flags */
232         if (isLastBlock()) {
233             theV[14] ^= -1L;
234             if (isLastNode()) {
235                 theV[15] ^= -1L;
236             }
237         }
238     }
239 
240     @Override
241     void initM(final byte[] pMessage,
242                final int pMsgPos) {
243         /* Copy message bytes into word array */
244         for (int i = 0; i < NUMWORDS << 1; i++) {
245             theM[i] = Pack.littleEndianToLong(pMessage, pMsgPos + i * Long.BYTES);
246         }
247     }
248 
249     @Override
250     void adjustH() {
251         /* Combine V into H */
252         for (int i = 0; i < NUMWORDS; i++) {
253             theH[i] ^= theV[i] ^ theV[i + NUMWORDS];
254         }
255     }
256 
257     @Override
258     void mixG(final int msgIdx1,
259               final int msgIdx2,
260               final int posA,
261               final int posB,
262               final int posC,
263               final int posD) {
264         /* Perform the Round */
265         theV[posA] += theV[posB] + theM[msgIdx1];
266         theV[posD] = rotr64(theV[posD] ^ theV[posA], 32);
267         theV[posC] += theV[posD];
268         theV[posB] = rotr64(theV[posB] ^ theV[posC], 24);
269         theV[posA] += theV[posB] + theM[msgIdx2];
270         theV[posD] = rotr64(theV[posD] ^ theV[posA], 16);
271         theV[posC] += theV[posD];
272         theV[posB] = rotr64(theV[posB] ^ theV[posC], 63);
273     }
274 
275     /**
276      * Rotate a long right.
277      *
278      * @param x   the value to rotate
279      * @param rot the number of bits to rotate
280      * @return the result
281      */
282     private static long rotr64(final long x,
283                                final int rot) {
284         return x >>> rot | (x << (Long.SIZE - rot));
285     }
286 }