Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/java.base/share/classes/com/sun/crypto/provider/ChaCha20Cipher.java
67773 views
1
/*
2
* Copyright (c) 2018, 2021, 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 com.sun.crypto.provider;
27
28
import java.io.ByteArrayOutputStream;
29
import java.io.IOException;
30
import java.lang.invoke.MethodHandles;
31
import java.lang.invoke.VarHandle;
32
import java.nio.ByteBuffer;
33
import java.nio.ByteOrder;
34
import java.security.*;
35
import java.security.spec.AlgorithmParameterSpec;
36
import java.util.Arrays;
37
import java.util.Objects;
38
import javax.crypto.*;
39
import javax.crypto.spec.ChaCha20ParameterSpec;
40
import javax.crypto.spec.IvParameterSpec;
41
import javax.crypto.spec.SecretKeySpec;
42
import sun.security.util.DerValue;
43
44
/**
45
* Implementation of the ChaCha20 cipher, as described in RFC 7539.
46
*
47
* @since 11
48
*/
49
abstract class ChaCha20Cipher extends CipherSpi {
50
// Mode constants
51
private static final int MODE_NONE = 0;
52
private static final int MODE_AEAD = 1;
53
54
// Constants used in setting up the initial state
55
private static final int STATE_CONST_0 = 0x61707865;
56
private static final int STATE_CONST_1 = 0x3320646e;
57
private static final int STATE_CONST_2 = 0x79622d32;
58
private static final int STATE_CONST_3 = 0x6b206574;
59
60
// The keystream block size in bytes and as integers
61
private static final int KEYSTREAM_SIZE = 64;
62
private static final int KS_SIZE_INTS = KEYSTREAM_SIZE / Integer.BYTES;
63
private static final int CIPHERBUF_BASE = 1024;
64
65
// The initialization state of the cipher
66
private boolean initialized;
67
68
// The mode of operation for this object
69
protected int mode;
70
71
// The direction (encrypt vs. decrypt) for the data flow
72
private int direction;
73
74
// Has all AAD data been provided (i.e. have we called our first update)
75
private boolean aadDone = false;
76
77
// The key's encoding in bytes for this object
78
private byte[] keyBytes;
79
80
// The nonce used for this object
81
private byte[] nonce;
82
83
// The counter
84
private static final long MAX_UINT32 = 0x00000000FFFFFFFFL;
85
private long finalCounterValue;
86
private long counter;
87
88
// Two arrays, both implemented as 16-element integer arrays:
89
// The base state, created at initialization time, and a working
90
// state which is a clone of the start state, and is then modified
91
// with the counter and the ChaCha20 block function.
92
private final int[] startState = new int[KS_SIZE_INTS];
93
private final byte[] keyStream = new byte[KEYSTREAM_SIZE];
94
95
// The offset into the current keystream
96
private int keyStrOffset;
97
98
// AEAD-related fields and constants
99
private static final int TAG_LENGTH = 16;
100
private long aadLen;
101
private long dataLen;
102
103
// Have a buffer of zero padding that can be read all or in part
104
// by the authenticator.
105
private static final byte[] padBuf = new byte[TAG_LENGTH];
106
107
// Create a buffer for holding the AAD and Ciphertext lengths
108
private final byte[] lenBuf = new byte[TAG_LENGTH];
109
110
// The authenticator (Poly1305) when running in AEAD mode
111
protected String authAlgName;
112
private Poly1305 authenticator;
113
114
// The underlying engine for doing the ChaCha20/Poly1305 work
115
private ChaChaEngine engine;
116
117
// Use this VarHandle for converting the state elements into little-endian
118
// integer values for the ChaCha20 block function.
119
private static final VarHandle asIntLittleEndian =
120
MethodHandles.byteArrayViewVarHandle(int[].class,
121
ByteOrder.LITTLE_ENDIAN);
122
123
// Use this VarHandle for converting the AAD and data lengths into
124
// little-endian long values for AEAD tag computations.
125
private static final VarHandle asLongLittleEndian =
126
MethodHandles.byteArrayViewVarHandle(long[].class,
127
ByteOrder.LITTLE_ENDIAN);
128
129
// Use this for pulling in 8 bytes at a time as longs for XOR operations
130
private static final VarHandle asLongView =
131
MethodHandles.byteArrayViewVarHandle(long[].class,
132
ByteOrder.nativeOrder());
133
134
/**
135
* Default constructor.
136
*/
137
protected ChaCha20Cipher() { }
138
139
/**
140
* Set the mode of operation. Since this is a stream cipher, there
141
* is no mode of operation in the block-cipher sense of things. The
142
* protected {@code mode} field will only accept a value of {@code None}
143
* (case-insensitive).
144
*
145
* @param mode The mode value
146
*
147
* @throws NoSuchAlgorithmException if a mode of operation besides
148
* {@code None} is provided.
149
*/
150
@Override
151
protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
152
if (mode.equalsIgnoreCase("None") == false) {
153
throw new NoSuchAlgorithmException("Mode must be None");
154
}
155
}
156
157
/**
158
* Set the padding scheme. Padding schemes do not make sense with stream
159
* ciphers, but allow {@code NoPadding}. See JCE spec.
160
*
161
* @param padding The padding type. The only allowed value is
162
* {@code NoPadding} case insensitive).
163
*
164
* @throws NoSuchPaddingException if a padding scheme besides
165
* {@code NoPadding} is provided.
166
*/
167
@Override
168
protected void engineSetPadding(String padding)
169
throws NoSuchPaddingException {
170
if (padding.equalsIgnoreCase("NoPadding") == false) {
171
throw new NoSuchPaddingException("Padding must be NoPadding");
172
}
173
}
174
175
/**
176
* Returns the block size. For a stream cipher like ChaCha20, this
177
* value will always be zero.
178
*
179
* @return This method always returns 0. See the JCE Specification.
180
*/
181
@Override
182
protected int engineGetBlockSize() {
183
return 0;
184
}
185
186
/**
187
* Get the output size required to hold the result of the next update or
188
* doFinal operation. In simple stream-cipher
189
* mode, the output size will equal the input size. For ChaCha20-Poly1305
190
* for encryption the output size will be the sum of the input length
191
* and tag length. For decryption, the output size will be the input
192
* length plus any previously unprocessed data minus the tag
193
* length, minimum zero.
194
*
195
* @param inputLen the length in bytes of the input
196
*
197
* @return the output length in bytes.
198
*/
199
@Override
200
protected int engineGetOutputSize(int inputLen) {
201
return engine.getOutputSize(inputLen, true);
202
}
203
204
/**
205
* Get the nonce value used.
206
*
207
* @return the nonce bytes. For ChaCha20 this will be a 12-byte value.
208
*/
209
@Override
210
protected byte[] engineGetIV() {
211
return (nonce != null) ? nonce.clone() : null;
212
}
213
214
/**
215
* Get the algorithm parameters for this cipher. For the ChaCha20
216
* cipher, this will always return {@code null} as there currently is
217
* no {@code AlgorithmParameters} implementation for ChaCha20. For
218
* ChaCha20-Poly1305, a {@code ChaCha20Poly1305Parameters} object will be
219
* created and initialized with the configured nonce value and returned
220
* to the caller.
221
*
222
* @return a {@code null} value if the ChaCha20 cipher is used (mode is
223
* MODE_NONE), or a {@code ChaCha20Poly1305Parameters} object containing
224
* the nonce if the mode is MODE_AEAD.
225
*/
226
@Override
227
protected AlgorithmParameters engineGetParameters() {
228
AlgorithmParameters params = null;
229
if (mode == MODE_AEAD) {
230
// In a pre-initialized state or any state without a nonce value
231
// this call should cause a random nonce to be generated, but
232
// not attached to the object.
233
byte[] nonceData = (initialized || nonce != null) ? nonce :
234
createRandomNonce(null);
235
try {
236
// Place the 12-byte nonce into a DER-encoded OCTET_STRING
237
params = AlgorithmParameters.getInstance("ChaCha20-Poly1305");
238
params.init((new DerValue(
239
DerValue.tag_OctetString, nonceData).toByteArray()));
240
} catch (NoSuchAlgorithmException | IOException exc) {
241
throw new RuntimeException(exc);
242
}
243
}
244
245
return params;
246
}
247
248
/**
249
* Initialize the engine using a key and secure random implementation. If
250
* a SecureRandom object is provided it will be used to create a random
251
* nonce value. If the {@code random} parameter is null an internal
252
* secure random source will be used to create the random nonce.
253
* The counter value will be set to 1.
254
*
255
* @param opmode the type of operation to do. This value may not be
256
* {@code Cipher.DECRYPT_MODE} or {@code Cipher.UNWRAP_MODE} mode
257
* because it must generate random parameters like the nonce.
258
* @param key a 256-bit key suitable for ChaCha20
259
* @param random a {@code SecureRandom} implementation used to create the
260
* random nonce. If {@code null} is used for the random object,
261
* then an internal secure random source will be used to create the
262
* nonce.
263
*
264
* @throws UnsupportedOperationException if the mode of operation
265
* is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
266
* (currently unsupported).
267
* @throws InvalidKeyException if the key is of the wrong type or is
268
* not 256-bits in length. This will also be thrown if the opmode
269
* parameter is {@code Cipher.DECRYPT_MODE}.
270
* {@code Cipher.UNWRAP_MODE} would normally be disallowed in this
271
* context but it is preempted by the UOE case above.
272
*/
273
@Override
274
protected void engineInit(int opmode, Key key, SecureRandom random)
275
throws InvalidKeyException {
276
if (opmode != Cipher.DECRYPT_MODE) {
277
byte[] newNonce = createRandomNonce(random);
278
counter = 1;
279
init(opmode, key, newNonce);
280
} else {
281
throw new InvalidKeyException("Default parameter generation " +
282
"disallowed in DECRYPT and UNWRAP modes");
283
}
284
}
285
286
/**
287
* Initialize the engine using a key and secure random implementation.
288
*
289
* @param opmode the type of operation to do. This value must be either
290
* {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
291
* @param key a 256-bit key suitable for ChaCha20
292
* @param params a {@code ChaCha20ParameterSpec} that will provide
293
* the nonce and initial block counter value.
294
* @param random a {@code SecureRandom} implementation, this parameter
295
* is not used in this form of the initializer.
296
*
297
* @throws UnsupportedOperationException if the mode of operation
298
* is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
299
* (currently unsupported).
300
* @throws InvalidKeyException if the key is of the wrong type or is
301
* not 256-bits in length. This will also be thrown if the opmode
302
* parameter is not {@code Cipher.ENCRYPT_MODE} or
303
* {@code Cipher.DECRYPT_MODE} (excepting the UOE case above).
304
* @throws InvalidAlgorithmParameterException if {@code params} is
305
* not a {@code ChaCha20ParameterSpec}
306
* @throws NullPointerException if {@code params} is {@code null}
307
*/
308
@Override
309
protected void engineInit(int opmode, Key key,
310
AlgorithmParameterSpec params, SecureRandom random)
311
throws InvalidKeyException, InvalidAlgorithmParameterException {
312
313
// If AlgorithmParameterSpec is null, then treat this like an init
314
// of the form (int, Key, SecureRandom)
315
if (params == null) {
316
engineInit(opmode, key, random);
317
return;
318
}
319
320
// We will ignore the secure random implementation and use the nonce
321
// from the AlgorithmParameterSpec instead.
322
byte[] newNonce = null;
323
switch (mode) {
324
case MODE_NONE:
325
if (!(params instanceof ChaCha20ParameterSpec)) {
326
throw new InvalidAlgorithmParameterException(
327
"ChaCha20 algorithm requires ChaCha20ParameterSpec");
328
}
329
ChaCha20ParameterSpec chaParams = (ChaCha20ParameterSpec)params;
330
newNonce = chaParams.getNonce();
331
counter = ((long)chaParams.getCounter()) & 0x00000000FFFFFFFFL;
332
break;
333
case MODE_AEAD:
334
if (!(params instanceof IvParameterSpec)) {
335
throw new InvalidAlgorithmParameterException(
336
"ChaCha20-Poly1305 requires IvParameterSpec");
337
}
338
IvParameterSpec ivParams = (IvParameterSpec)params;
339
newNonce = ivParams.getIV();
340
if (newNonce.length != 12) {
341
throw new InvalidAlgorithmParameterException(
342
"ChaCha20-Poly1305 nonce must be 12 bytes in length");
343
}
344
break;
345
default:
346
// Should never happen
347
throw new RuntimeException("ChaCha20 in unsupported mode");
348
}
349
init(opmode, key, newNonce);
350
}
351
352
/**
353
* Initialize the engine using the {@code AlgorithmParameter} initialization
354
* format. This cipher does supports initialization with
355
* {@code AlgorithmParameter} objects for ChaCha20-Poly1305 but not for
356
* ChaCha20 as a simple stream cipher. In the latter case, it will throw
357
* an {@code InvalidAlgorithmParameterException} if the value is non-null.
358
* If a null value is supplied for the {@code params} field
359
* the cipher will be initialized with the counter value set to 1 and
360
* a random nonce. If {@code null} is used for the random object,
361
* then an internal secure random source will be used to create the
362
* nonce.
363
*
364
* @param opmode the type of operation to do. This value must be either
365
* {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
366
* @param key a 256-bit key suitable for ChaCha20
367
* @param params a {@code null} value if the algorithm is ChaCha20, or
368
* the appropriate {@code AlgorithmParameters} object containing the
369
* nonce information if the algorithm is ChaCha20-Poly1305.
370
* @param random a {@code SecureRandom} implementation, may be {@code null}.
371
*
372
* @throws UnsupportedOperationException if the mode of operation
373
* is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
374
* (currently unsupported).
375
* @throws InvalidKeyException if the key is of the wrong type or is
376
* not 256-bits in length. This will also be thrown if the opmode
377
* parameter is not {@code Cipher.ENCRYPT_MODE} or
378
* {@code Cipher.DECRYPT_MODE} (excepting the UOE case above).
379
* @throws InvalidAlgorithmParameterException if {@code params} is
380
* non-null and the algorithm is ChaCha20. This exception will be
381
* also thrown if the algorithm is ChaCha20-Poly1305 and an incorrect
382
* {@code AlgorithmParameters} object is supplied.
383
*/
384
@Override
385
protected void engineInit(int opmode, Key key,
386
AlgorithmParameters params, SecureRandom random)
387
throws InvalidKeyException, InvalidAlgorithmParameterException {
388
389
// If AlgorithmParameters is null, then treat this like an init
390
// of the form (int, Key, SecureRandom)
391
if (params == null) {
392
engineInit(opmode, key, random);
393
return;
394
}
395
396
byte[] newNonce = null;
397
switch (mode) {
398
case MODE_NONE:
399
throw new InvalidAlgorithmParameterException(
400
"AlgorithmParameters not supported");
401
case MODE_AEAD:
402
String paramAlg = params.getAlgorithm();
403
if (!paramAlg.equalsIgnoreCase("ChaCha20-Poly1305")) {
404
throw new InvalidAlgorithmParameterException(
405
"Invalid parameter type: " + paramAlg);
406
}
407
try {
408
DerValue dv = new DerValue(params.getEncoded());
409
newNonce = dv.getOctetString();
410
if (newNonce.length != 12) {
411
throw new InvalidAlgorithmParameterException(
412
"ChaCha20-Poly1305 nonce must be " +
413
"12 bytes in length");
414
}
415
} catch (IOException ioe) {
416
throw new InvalidAlgorithmParameterException(ioe);
417
}
418
break;
419
default:
420
throw new RuntimeException("Invalid mode: " + mode);
421
}
422
423
// If after all the above processing we still don't have a nonce value
424
// then supply a random one provided a random source has been given.
425
if (newNonce == null) {
426
newNonce = createRandomNonce(random);
427
}
428
429
// Continue with initialization
430
init(opmode, key, newNonce);
431
}
432
433
/**
434
* Update additional authenticated data (AAD).
435
*
436
* @param src the byte array containing the authentication data.
437
* @param offset the starting offset in the buffer to update.
438
* @param len the amount of authentication data to update.
439
*
440
* @throws IllegalStateException if the cipher has not been initialized,
441
* {@code engineUpdate} has been called, or the cipher is running
442
* in a non-AEAD mode of operation. It will also throw this
443
* exception if the submitted AAD would overflow a 64-bit length
444
* counter.
445
*/
446
@Override
447
protected void engineUpdateAAD(byte[] src, int offset, int len) {
448
if (!initialized) {
449
// We know that the cipher has not been initialized if the key
450
// is still null.
451
throw new IllegalStateException(
452
"Attempted to update AAD on uninitialized Cipher");
453
} else if (aadDone) {
454
// No AAD updates allowed after the PT/CT update method is called
455
throw new IllegalStateException("Attempted to update AAD on " +
456
"Cipher after plaintext/ciphertext update");
457
} else if (mode != MODE_AEAD) {
458
throw new IllegalStateException(
459
"Cipher is running in non-AEAD mode");
460
} else {
461
try {
462
aadLen = Math.addExact(aadLen, len);
463
authUpdate(src, offset, len);
464
} catch (ArithmeticException ae) {
465
throw new IllegalStateException("AAD overflow", ae);
466
}
467
}
468
}
469
470
/**
471
* Update additional authenticated data (AAD).
472
*
473
* @param src the ByteBuffer containing the authentication data.
474
*
475
* @throws IllegalStateException if the cipher has not been initialized,
476
* {@code engineUpdate} has been called, or the cipher is running
477
* in a non-AEAD mode of operation. It will also throw this
478
* exception if the submitted AAD would overflow a 64-bit length
479
* counter.
480
*/
481
@Override
482
protected void engineUpdateAAD(ByteBuffer src) {
483
if (!initialized) {
484
// We know that the cipher has not been initialized if the key
485
// is still null.
486
throw new IllegalStateException(
487
"Attempted to update AAD on uninitialized Cipher");
488
} else if (aadDone) {
489
// No AAD updates allowed after the PT/CT update method is called
490
throw new IllegalStateException("Attempted to update AAD on " +
491
"Cipher after plaintext/ciphertext update");
492
} else if (mode != MODE_AEAD) {
493
throw new IllegalStateException(
494
"Cipher is running in non-AEAD mode");
495
} else {
496
try {
497
aadLen = Math.addExact(aadLen, (src.limit() - src.position()));
498
authenticator.engineUpdate(src);
499
} catch (ArithmeticException ae) {
500
throw new IllegalStateException("AAD overflow", ae);
501
}
502
}
503
}
504
505
/**
506
* Create a random 12-byte nonce.
507
*
508
* @param random a {@code SecureRandom} object. If {@code null} is
509
* provided a new {@code SecureRandom} object will be instantiated.
510
*
511
* @return a 12-byte array containing the random nonce.
512
*/
513
private static byte[] createRandomNonce(SecureRandom random) {
514
byte[] newNonce = new byte[12];
515
SecureRandom rand = (random != null) ? random : new SecureRandom();
516
rand.nextBytes(newNonce);
517
return newNonce;
518
}
519
520
/**
521
* Perform additional initialization actions based on the key and operation
522
* type.
523
*
524
* @param opmode the type of operation to do. This value must be either
525
* {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}
526
* @param key a 256-bit key suitable for ChaCha20
527
* @param newNonce the new nonce value for this initialization.
528
*
529
* @throws UnsupportedOperationException if the {@code opmode} parameter
530
* is {@code Cipher.WRAP_MODE} or {@code Cipher.UNWRAP_MODE}
531
* (currently unsupported).
532
* @throws InvalidKeyException if the {@code opmode} parameter is not
533
* {@code Cipher.ENCRYPT_MODE} or {@code Cipher.DECRYPT_MODE}, or
534
* if the key format is not {@code RAW}.
535
*/
536
private void init(int opmode, Key key, byte[] newNonce)
537
throws InvalidKeyException {
538
// Cipher.init() already checks opmode to be:
539
// ENCRYPT_MODE/DECRYPT_MODE/WRAP_MODE/UNWRAP_MODE
540
if ((opmode == Cipher.WRAP_MODE) || (opmode == Cipher.UNWRAP_MODE)) {
541
throw new UnsupportedOperationException(
542
"WRAP_MODE and UNWRAP_MODE are not currently supported");
543
}
544
545
// Make sure that the provided key and nonce are unique before
546
// assigning them to the object.
547
byte[] newKeyBytes = getEncodedKey(key);
548
checkKeyAndNonce(newKeyBytes, newNonce);
549
if (this.keyBytes != null) {
550
Arrays.fill(this.keyBytes, (byte)0);
551
}
552
this.keyBytes = newKeyBytes;
553
nonce = newNonce;
554
555
// Now that we have the key and nonce, we can build the initial state
556
setInitialState();
557
558
if (mode == MODE_NONE) {
559
engine = new EngineStreamOnly();
560
} else if (mode == MODE_AEAD) {
561
if (opmode == Cipher.ENCRYPT_MODE) {
562
engine = new EngineAEADEnc();
563
} else if (opmode == Cipher.DECRYPT_MODE) {
564
engine = new EngineAEADDec();
565
} else {
566
throw new InvalidKeyException("Not encrypt or decrypt mode");
567
}
568
}
569
570
// We can also get one block's worth of keystream created
571
finalCounterValue = counter + MAX_UINT32;
572
generateKeystream();
573
direction = opmode;
574
aadDone = false;
575
this.keyStrOffset = 0;
576
initialized = true;
577
}
578
579
/**
580
* Check the key and nonce bytes to make sure that they do not repeat
581
* across reinitialization.
582
*
583
* @param newKeyBytes the byte encoding for the newly provided key
584
* @param newNonce the new nonce to be used with this initialization
585
*
586
* @throws InvalidKeyException if both the key and nonce match the
587
* previous initialization.
588
*
589
*/
590
private void checkKeyAndNonce(byte[] newKeyBytes, byte[] newNonce)
591
throws InvalidKeyException {
592
// A new initialization must have either a different key or nonce
593
// so the starting state for each block is not the same as the
594
// previous initialization.
595
if (MessageDigest.isEqual(newKeyBytes, keyBytes) &&
596
MessageDigest.isEqual(newNonce, nonce)) {
597
throw new InvalidKeyException(
598
"Matching key and nonce from previous initialization");
599
}
600
}
601
602
/**
603
* Return the encoded key as a byte array
604
*
605
* @param key the {@code Key} object used for this {@code Cipher}
606
*
607
* @return the key bytes
608
*
609
* @throws InvalidKeyException if the key is of the wrong type or length,
610
* or if the key encoding format is not {@code RAW}.
611
*/
612
private static byte[] getEncodedKey(Key key) throws InvalidKeyException {
613
if ("RAW".equals(key.getFormat()) == false) {
614
throw new InvalidKeyException("Key encoding format must be RAW");
615
}
616
byte[] encodedKey = key.getEncoded();
617
if (encodedKey == null || encodedKey.length != 32) {
618
if (encodedKey != null) {
619
Arrays.fill(encodedKey, (byte)0);
620
}
621
throw new InvalidKeyException("Key length must be 256 bits");
622
}
623
return encodedKey;
624
}
625
626
/**
627
* Update the currently running operation with additional data
628
*
629
* @param in the plaintext or ciphertext input bytes (depending on the
630
* operation type).
631
* @param inOfs the offset into the input array
632
* @param inLen the length of the data to use for the update operation.
633
*
634
* @return the resulting plaintext or ciphertext bytes (depending on
635
* the operation type)
636
*/
637
@Override
638
protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
639
byte[] out = new byte[engine.getOutputSize(inLen, false)];
640
try {
641
engine.doUpdate(in, inOfs, inLen, out, 0);
642
} catch (ShortBufferException | KeyException exc) {
643
throw new RuntimeException(exc);
644
}
645
646
return out;
647
}
648
649
/**
650
* Update the currently running operation with additional data
651
*
652
* @param in the plaintext or ciphertext input bytes (depending on the
653
* operation type).
654
* @param inOfs the offset into the input array
655
* @param inLen the length of the data to use for the update operation.
656
* @param out the byte array that will hold the resulting data. The array
657
* must be large enough to hold the resulting data.
658
* @param outOfs the offset for the {@code out} buffer to begin writing
659
* the resulting data.
660
*
661
* @return the length in bytes of the data written into the {@code out}
662
* buffer.
663
*
664
* @throws ShortBufferException if the buffer {@code out} does not have
665
* enough space to hold the resulting data.
666
*/
667
@Override
668
protected int engineUpdate(byte[] in, int inOfs, int inLen,
669
byte[] out, int outOfs) throws ShortBufferException {
670
int bytesUpdated = 0;
671
try {
672
bytesUpdated = engine.doUpdate(in, inOfs, inLen, out, outOfs);
673
} catch (KeyException ke) {
674
throw new RuntimeException(ke);
675
}
676
return bytesUpdated;
677
}
678
679
/**
680
* Complete the currently running operation using any final
681
* data provided by the caller.
682
*
683
* @param in the plaintext or ciphertext input bytes (depending on the
684
* operation type).
685
* @param inOfs the offset into the input array
686
* @param inLen the length of the data to use for the update operation.
687
*
688
* @return the resulting plaintext or ciphertext bytes (depending on
689
* the operation type)
690
*
691
* @throws AEADBadTagException if, during decryption, the provided tag
692
* does not match the calculated tag.
693
*/
694
@Override
695
protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
696
throws AEADBadTagException {
697
byte[] output = new byte[engine.getOutputSize(inLen, true)];
698
try {
699
engine.doFinal(in, inOfs, inLen, output, 0);
700
} catch (ShortBufferException | KeyException exc) {
701
throw new RuntimeException(exc);
702
} finally {
703
// Regardless of what happens, the cipher cannot be used for
704
// further processing until it has been freshly initialized.
705
initialized = false;
706
}
707
return output;
708
}
709
710
/**
711
* Complete the currently running operation using any final
712
* data provided by the caller.
713
*
714
* @param in the plaintext or ciphertext input bytes (depending on the
715
* operation type).
716
* @param inOfs the offset into the input array
717
* @param inLen the length of the data to use for the update operation.
718
* @param out the byte array that will hold the resulting data. The array
719
* must be large enough to hold the resulting data.
720
* @param outOfs the offset for the {@code out} buffer to begin writing
721
* the resulting data.
722
*
723
* @return the length in bytes of the data written into the {@code out}
724
* buffer.
725
*
726
* @throws ShortBufferException if the buffer {@code out} does not have
727
* enough space to hold the resulting data.
728
* @throws AEADBadTagException if, during decryption, the provided tag
729
* does not match the calculated tag.
730
*/
731
@Override
732
protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
733
int outOfs) throws ShortBufferException, AEADBadTagException {
734
735
int bytesUpdated = 0;
736
try {
737
bytesUpdated = engine.doFinal(in, inOfs, inLen, out, outOfs);
738
} catch (KeyException ke) {
739
throw new RuntimeException(ke);
740
} finally {
741
// Regardless of what happens, the cipher cannot be used for
742
// further processing until it has been freshly initialized.
743
initialized = false;
744
}
745
return bytesUpdated;
746
}
747
748
/**
749
* Wrap a {@code Key} using this Cipher's current encryption parameters.
750
*
751
* @param key the key to wrap. The data that will be encrypted will
752
* be the provided {@code Key} in its encoded form.
753
*
754
* @return a byte array consisting of the wrapped key.
755
*
756
* @throws UnsupportedOperationException this will (currently) always
757
* be thrown, as this method is not currently supported.
758
*/
759
@Override
760
protected byte[] engineWrap(Key key) throws IllegalBlockSizeException,
761
InvalidKeyException {
762
throw new UnsupportedOperationException(
763
"Wrap operations are not supported");
764
}
765
766
/**
767
* Unwrap a {@code Key} using this Cipher's current encryption parameters.
768
*
769
* @param wrappedKey the key to unwrap.
770
* @param algorithm the algorithm associated with the wrapped key
771
* @param type the type of the wrapped key. This is one of
772
* {@code SECRET_KEY}, {@code PRIVATE_KEY}, or {@code PUBLIC_KEY}.
773
*
774
* @return the unwrapped key as a {@code Key} object.
775
*
776
* @throws UnsupportedOperationException this will (currently) always
777
* be thrown, as this method is not currently supported.
778
*/
779
@Override
780
protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
781
int type) throws InvalidKeyException, NoSuchAlgorithmException {
782
throw new UnsupportedOperationException(
783
"Unwrap operations are not supported");
784
}
785
786
/**
787
* Get the length of a provided key in bits.
788
*
789
* @param key the key to be evaluated
790
*
791
* @return the length of the key in bits
792
*
793
* @throws InvalidKeyException if the key is invalid or does not
794
* have an encoded form.
795
*/
796
@Override
797
protected int engineGetKeySize(Key key) throws InvalidKeyException {
798
byte[] encodedKey = getEncodedKey(key);
799
Arrays.fill(encodedKey, (byte)0);
800
return encodedKey.length << 3;
801
}
802
803
/**
804
* Set the initial state. This will populate the state array and put the
805
* key and nonce into their proper locations. The counter field is not
806
* set here.
807
*
808
* @throws IllegalArgumentException if the key or nonce are not in
809
* their proper lengths (32 bytes for the key, 12 bytes for the
810
* nonce).
811
* @throws InvalidKeyException if the key does not support an encoded form.
812
*/
813
private void setInitialState() throws InvalidKeyException {
814
// Apply constants to first 4 words
815
startState[0] = STATE_CONST_0;
816
startState[1] = STATE_CONST_1;
817
startState[2] = STATE_CONST_2;
818
startState[3] = STATE_CONST_3;
819
820
// Apply the key bytes as 8 32-bit little endian ints (4 through 11)
821
for (int i = 0; i < 32; i += 4) {
822
startState[(i / 4) + 4] = (keyBytes[i] & 0x000000FF) |
823
((keyBytes[i + 1] << 8) & 0x0000FF00) |
824
((keyBytes[i + 2] << 16) & 0x00FF0000) |
825
((keyBytes[i + 3] << 24) & 0xFF000000);
826
}
827
828
startState[12] = 0;
829
830
// The final integers for the state are from the nonce
831
// interpreted as 3 little endian integers
832
for (int i = 0; i < 12; i += 4) {
833
startState[(i / 4) + 13] = (nonce[i] & 0x000000FF) |
834
((nonce[i + 1] << 8) & 0x0000FF00) |
835
((nonce[i + 2] << 16) & 0x00FF0000) |
836
((nonce[i + 3] << 24) & 0xFF000000);
837
}
838
}
839
840
/**
841
* Using the current state and counter create the next set of keystream
842
* bytes. This method will generate the next 512 bits of keystream and
843
* return it in the {@code keyStream} parameter. Following the
844
* block function the counter will be incremented.
845
*/
846
private void generateKeystream() {
847
chaCha20Block(startState, counter, keyStream);
848
counter++;
849
}
850
851
/**
852
* Perform a full 20-round ChaCha20 transform on the initial state.
853
*
854
* @param initState the starting state, not including the counter
855
* value.
856
* @param counter the counter value to apply
857
* @param result the array that will hold the result of the ChaCha20
858
* block function.
859
*
860
* @note it is the caller's responsibility to ensure that the workState
861
* is sized the same as the initState, no checking is performed internally.
862
*/
863
private static void chaCha20Block(int[] initState, long counter,
864
byte[] result) {
865
// Create an initial state and clone a working copy
866
int ws00 = STATE_CONST_0;
867
int ws01 = STATE_CONST_1;
868
int ws02 = STATE_CONST_2;
869
int ws03 = STATE_CONST_3;
870
int ws04 = initState[4];
871
int ws05 = initState[5];
872
int ws06 = initState[6];
873
int ws07 = initState[7];
874
int ws08 = initState[8];
875
int ws09 = initState[9];
876
int ws10 = initState[10];
877
int ws11 = initState[11];
878
int ws12 = (int)counter;
879
int ws13 = initState[13];
880
int ws14 = initState[14];
881
int ws15 = initState[15];
882
883
// Peform 10 iterations of the 8 quarter round set
884
for (int round = 0; round < 10; round++) {
885
ws00 += ws04;
886
ws12 = Integer.rotateLeft(ws12 ^ ws00, 16);
887
888
ws08 += ws12;
889
ws04 = Integer.rotateLeft(ws04 ^ ws08, 12);
890
891
ws00 += ws04;
892
ws12 = Integer.rotateLeft(ws12 ^ ws00, 8);
893
894
ws08 += ws12;
895
ws04 = Integer.rotateLeft(ws04 ^ ws08, 7);
896
897
ws01 += ws05;
898
ws13 = Integer.rotateLeft(ws13 ^ ws01, 16);
899
900
ws09 += ws13;
901
ws05 = Integer.rotateLeft(ws05 ^ ws09, 12);
902
903
ws01 += ws05;
904
ws13 = Integer.rotateLeft(ws13 ^ ws01, 8);
905
906
ws09 += ws13;
907
ws05 = Integer.rotateLeft(ws05 ^ ws09, 7);
908
909
ws02 += ws06;
910
ws14 = Integer.rotateLeft(ws14 ^ ws02, 16);
911
912
ws10 += ws14;
913
ws06 = Integer.rotateLeft(ws06 ^ ws10, 12);
914
915
ws02 += ws06;
916
ws14 = Integer.rotateLeft(ws14 ^ ws02, 8);
917
918
ws10 += ws14;
919
ws06 = Integer.rotateLeft(ws06 ^ ws10, 7);
920
921
ws03 += ws07;
922
ws15 = Integer.rotateLeft(ws15 ^ ws03, 16);
923
924
ws11 += ws15;
925
ws07 = Integer.rotateLeft(ws07 ^ ws11, 12);
926
927
ws03 += ws07;
928
ws15 = Integer.rotateLeft(ws15 ^ ws03, 8);
929
930
ws11 += ws15;
931
ws07 = Integer.rotateLeft(ws07 ^ ws11, 7);
932
933
ws00 += ws05;
934
ws15 = Integer.rotateLeft(ws15 ^ ws00, 16);
935
936
ws10 += ws15;
937
ws05 = Integer.rotateLeft(ws05 ^ ws10, 12);
938
939
ws00 += ws05;
940
ws15 = Integer.rotateLeft(ws15 ^ ws00, 8);
941
942
ws10 += ws15;
943
ws05 = Integer.rotateLeft(ws05 ^ ws10, 7);
944
945
ws01 += ws06;
946
ws12 = Integer.rotateLeft(ws12 ^ ws01, 16);
947
948
ws11 += ws12;
949
ws06 = Integer.rotateLeft(ws06 ^ ws11, 12);
950
951
ws01 += ws06;
952
ws12 = Integer.rotateLeft(ws12 ^ ws01, 8);
953
954
ws11 += ws12;
955
ws06 = Integer.rotateLeft(ws06 ^ ws11, 7);
956
957
ws02 += ws07;
958
ws13 = Integer.rotateLeft(ws13 ^ ws02, 16);
959
960
ws08 += ws13;
961
ws07 = Integer.rotateLeft(ws07 ^ ws08, 12);
962
963
ws02 += ws07;
964
ws13 = Integer.rotateLeft(ws13 ^ ws02, 8);
965
966
ws08 += ws13;
967
ws07 = Integer.rotateLeft(ws07 ^ ws08, 7);
968
969
ws03 += ws04;
970
ws14 = Integer.rotateLeft(ws14 ^ ws03, 16);
971
972
ws09 += ws14;
973
ws04 = Integer.rotateLeft(ws04 ^ ws09, 12);
974
975
ws03 += ws04;
976
ws14 = Integer.rotateLeft(ws14 ^ ws03, 8);
977
978
ws09 += ws14;
979
ws04 = Integer.rotateLeft(ws04 ^ ws09, 7);
980
}
981
982
// Add the end working state back into the original state
983
asIntLittleEndian.set(result, 0, ws00 + STATE_CONST_0);
984
asIntLittleEndian.set(result, 4, ws01 + STATE_CONST_1);
985
asIntLittleEndian.set(result, 8, ws02 + STATE_CONST_2);
986
asIntLittleEndian.set(result, 12, ws03 + STATE_CONST_3);
987
asIntLittleEndian.set(result, 16, ws04 + initState[4]);
988
asIntLittleEndian.set(result, 20, ws05 + initState[5]);
989
asIntLittleEndian.set(result, 24, ws06 + initState[6]);
990
asIntLittleEndian.set(result, 28, ws07 + initState[7]);
991
asIntLittleEndian.set(result, 32, ws08 + initState[8]);
992
asIntLittleEndian.set(result, 36, ws09 + initState[9]);
993
asIntLittleEndian.set(result, 40, ws10 + initState[10]);
994
asIntLittleEndian.set(result, 44, ws11 + initState[11]);
995
// Add the counter back into workState[12]
996
asIntLittleEndian.set(result, 48, ws12 + (int)counter);
997
asIntLittleEndian.set(result, 52, ws13 + initState[13]);
998
asIntLittleEndian.set(result, 56, ws14 + initState[14]);
999
asIntLittleEndian.set(result, 60, ws15 + initState[15]);
1000
}
1001
1002
/**
1003
* Perform the ChaCha20 transform.
1004
*
1005
* @param in the array of bytes for the input
1006
* @param inOff the offset into the input array to start the transform
1007
* @param inLen the length of the data to perform the transform on.
1008
* @param out the output array. It must be large enough to hold the
1009
* resulting data
1010
* @param outOff the offset into the output array to place the resulting
1011
* data.
1012
*/
1013
private void chaCha20Transform(byte[] in, int inOff, int inLen,
1014
byte[] out, int outOff) throws KeyException {
1015
int remainingData = inLen;
1016
1017
while (remainingData > 0) {
1018
int ksRemain = keyStream.length - keyStrOffset;
1019
if (ksRemain <= 0) {
1020
if (counter <= finalCounterValue) {
1021
generateKeystream();
1022
keyStrOffset = 0;
1023
ksRemain = keyStream.length;
1024
} else {
1025
throw new KeyException("Counter exhausted. " +
1026
"Reinitialize with new key and/or nonce");
1027
}
1028
}
1029
1030
// XOR each byte in the keystream against the input
1031
int xformLen = Math.min(remainingData, ksRemain);
1032
xor(keyStream, keyStrOffset, in, inOff, out, outOff, xformLen);
1033
outOff += xformLen;
1034
inOff += xformLen;
1035
keyStrOffset += xformLen;
1036
remainingData -= xformLen;
1037
}
1038
}
1039
1040
private static void xor(byte[] in1, int off1, byte[] in2, int off2,
1041
byte[] out, int outOff, int len) {
1042
while (len >= 8) {
1043
long v1 = (long) asLongView.get(in1, off1);
1044
long v2 = (long) asLongView.get(in2, off2);
1045
asLongView.set(out, outOff, v1 ^ v2);
1046
off1 += 8;
1047
off2 += 8;
1048
outOff += 8;
1049
len -= 8;
1050
}
1051
while (len > 0) {
1052
out[outOff] = (byte) (in1[off1] ^ in2[off2]);
1053
off1++;
1054
off2++;
1055
outOff++;
1056
len--;
1057
}
1058
}
1059
1060
/**
1061
* Perform initialization steps for the authenticator
1062
*
1063
* @throws InvalidKeyException if the key is unusable for some reason
1064
* (invalid length, etc.)
1065
*/
1066
private void initAuthenticator() throws InvalidKeyException {
1067
authenticator = new Poly1305();
1068
1069
// Derive the Poly1305 key from the starting state
1070
byte[] serializedKey = new byte[KEYSTREAM_SIZE];
1071
chaCha20Block(startState, 0, serializedKey);
1072
1073
authenticator.engineInit(new SecretKeySpec(serializedKey, 0, 32,
1074
authAlgName), null);
1075
aadLen = 0;
1076
dataLen = 0;
1077
}
1078
1079
/**
1080
* Update the authenticator state with data. This routine can be used
1081
* to add data to the authenticator, whether AAD or application data.
1082
*
1083
* @param data the data to stir into the authenticator.
1084
* @param offset the offset into the data.
1085
* @param length the length of data to add to the authenticator.
1086
*
1087
* @return the number of bytes processed by this method.
1088
*/
1089
private int authUpdate(byte[] data, int offset, int length) {
1090
Objects.checkFromIndexSize(offset, length, data.length);
1091
authenticator.engineUpdate(data, offset, length);
1092
return length;
1093
}
1094
1095
/**
1096
* Finalize the data and return the tag.
1097
*
1098
* @param data an array containing any remaining data to process.
1099
* @param dataOff the offset into the data.
1100
* @param length the length of the data to process.
1101
* @param out the array to write the resulting tag into
1102
* @param outOff the offset to begin writing the data.
1103
*
1104
* @throws ShortBufferException if there is insufficient room to
1105
* write the tag.
1106
*/
1107
private void authFinalizeData(byte[] data, int dataOff, int length,
1108
byte[] out, int outOff) throws ShortBufferException {
1109
// Update with the final chunk of ciphertext, then pad to a
1110
// multiple of 16.
1111
if (data != null) {
1112
dataLen += authUpdate(data, dataOff, length);
1113
}
1114
authPad16(dataLen);
1115
1116
// Also write the AAD and ciphertext data lengths as little-endian
1117
// 64-bit values.
1118
authWriteLengths(aadLen, dataLen, lenBuf);
1119
authenticator.engineUpdate(lenBuf, 0, lenBuf.length);
1120
byte[] tag = authenticator.engineDoFinal();
1121
Objects.checkFromIndexSize(outOff, tag.length, out.length);
1122
System.arraycopy(tag, 0, out, outOff, tag.length);
1123
aadLen = 0;
1124
dataLen = 0;
1125
}
1126
1127
/**
1128
* Based on a given length of data, make the authenticator process
1129
* zero bytes that will pad the length out to a multiple of 16.
1130
*
1131
* @param dataLen the starting length to be padded.
1132
*/
1133
private void authPad16(long dataLen) {
1134
// Pad out the AAD or data to a multiple of 16 bytes
1135
authenticator.engineUpdate(padBuf, 0,
1136
(TAG_LENGTH - ((int)dataLen & 15)) & 15);
1137
}
1138
1139
/**
1140
* Write the two 64-bit little-endian length fields into an array
1141
* for processing by the poly1305 authenticator.
1142
*
1143
* @param aLen the length of the AAD.
1144
* @param dLen the length of the application data.
1145
* @param buf the buffer to write the two lengths into.
1146
*
1147
* @note it is the caller's responsibility to provide an array large
1148
* enough to hold the two longs.
1149
*/
1150
private void authWriteLengths(long aLen, long dLen, byte[] buf) {
1151
asLongLittleEndian.set(buf, 0, aLen);
1152
asLongLittleEndian.set(buf, Long.BYTES, dLen);
1153
}
1154
1155
/**
1156
* Interface for the underlying processing engines for ChaCha20
1157
*/
1158
interface ChaChaEngine {
1159
/**
1160
* Size an output buffer based on the input and where applicable
1161
* the current state of the engine in a multipart operation.
1162
*
1163
* @param inLength the input length.
1164
* @param isFinal true if this is invoked from a doFinal call.
1165
*
1166
* @return the recommended size for the output buffer.
1167
*/
1168
int getOutputSize(int inLength, boolean isFinal);
1169
1170
/**
1171
* Perform a multi-part update for ChaCha20.
1172
*
1173
* @param in the input data.
1174
* @param inOff the offset into the input.
1175
* @param inLen the length of the data to process.
1176
* @param out the output buffer.
1177
* @param outOff the offset at which to write the output data.
1178
*
1179
* @return the number of output bytes written.
1180
*
1181
* @throws ShortBufferException if the output buffer does not
1182
* provide enough space.
1183
* @throws KeyException if the counter value has been exhausted.
1184
*/
1185
int doUpdate(byte[] in, int inOff, int inLen, byte[] out, int outOff)
1186
throws ShortBufferException, KeyException;
1187
1188
/**
1189
* Finalize a multi-part or single-part ChaCha20 operation.
1190
*
1191
* @param in the input data.
1192
* @param inOff the offset into the input.
1193
* @param inLen the length of the data to process.
1194
* @param out the output buffer.
1195
* @param outOff the offset at which to write the output data.
1196
*
1197
* @return the number of output bytes written.
1198
*
1199
* @throws ShortBufferException if the output buffer does not
1200
* provide enough space.
1201
* @throws AEADBadTagException if in decryption mode the provided
1202
* tag and calculated tag do not match.
1203
* @throws KeyException if the counter value has been exhausted.
1204
*/
1205
int doFinal(byte[] in, int inOff, int inLen, byte[] out, int outOff)
1206
throws ShortBufferException, AEADBadTagException, KeyException;
1207
}
1208
1209
private final class EngineStreamOnly implements ChaChaEngine {
1210
1211
private EngineStreamOnly () { }
1212
1213
@Override
1214
public int getOutputSize(int inLength, boolean isFinal) {
1215
// The isFinal parameter is not relevant in this kind of engine
1216
return inLength;
1217
}
1218
1219
@Override
1220
public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
1221
int outOff) throws ShortBufferException, KeyException {
1222
if (initialized) {
1223
try {
1224
if (out != null) {
1225
Objects.checkFromIndexSize(outOff, inLen, out.length);
1226
} else {
1227
throw new ShortBufferException(
1228
"Output buffer too small");
1229
}
1230
} catch (IndexOutOfBoundsException iobe) {
1231
throw new ShortBufferException("Output buffer too small");
1232
}
1233
if (in != null) {
1234
Objects.checkFromIndexSize(inOff, inLen, in.length);
1235
chaCha20Transform(in, inOff, inLen, out, outOff);
1236
}
1237
return inLen;
1238
} else {
1239
throw new IllegalStateException(
1240
"Must use either a different key or iv.");
1241
}
1242
}
1243
1244
@Override
1245
public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
1246
int outOff) throws ShortBufferException, KeyException {
1247
return doUpdate(in, inOff, inLen, out, outOff);
1248
}
1249
}
1250
1251
private final class EngineAEADEnc implements ChaChaEngine {
1252
1253
@Override
1254
public int getOutputSize(int inLength, boolean isFinal) {
1255
return (isFinal ? Math.addExact(inLength, TAG_LENGTH) : inLength);
1256
}
1257
1258
private EngineAEADEnc() throws InvalidKeyException {
1259
initAuthenticator();
1260
counter = 1;
1261
}
1262
1263
@Override
1264
public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
1265
int outOff) throws ShortBufferException, KeyException {
1266
if (initialized) {
1267
// If this is the first update since AAD updates, signal that
1268
// we're done processing AAD info and pad the AAD to a multiple
1269
// of 16 bytes.
1270
if (!aadDone) {
1271
authPad16(aadLen);
1272
aadDone = true;
1273
}
1274
try {
1275
if (out != null) {
1276
Objects.checkFromIndexSize(outOff, inLen, out.length);
1277
} else {
1278
throw new ShortBufferException(
1279
"Output buffer too small");
1280
}
1281
} catch (IndexOutOfBoundsException iobe) {
1282
throw new ShortBufferException("Output buffer too small");
1283
}
1284
if (in != null) {
1285
Objects.checkFromIndexSize(inOff, inLen, in.length);
1286
chaCha20Transform(in, inOff, inLen, out, outOff);
1287
dataLen += authUpdate(out, outOff, inLen);
1288
}
1289
1290
return inLen;
1291
} else {
1292
throw new IllegalStateException(
1293
"Must use either a different key or iv.");
1294
}
1295
}
1296
1297
@Override
1298
public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
1299
int outOff) throws ShortBufferException, KeyException {
1300
// Make sure we have enough room for the remaining data (if any)
1301
// and the tag.
1302
if ((inLen + TAG_LENGTH) > (out.length - outOff)) {
1303
throw new ShortBufferException("Output buffer too small");
1304
}
1305
1306
doUpdate(in, inOff, inLen, out, outOff);
1307
authFinalizeData(null, 0, 0, out, outOff + inLen);
1308
aadDone = false;
1309
return inLen + TAG_LENGTH;
1310
}
1311
}
1312
1313
private final class EngineAEADDec implements ChaChaEngine {
1314
1315
private final ByteArrayOutputStream cipherBuf;
1316
private final byte[] tag;
1317
1318
@Override
1319
public int getOutputSize(int inLen, boolean isFinal) {
1320
// If we are performing a decrypt-update we should always return
1321
// zero length since we cannot return any data until the tag has
1322
// been consumed and verified. CipherSpi.engineGetOutputSize will
1323
// always set isFinal to true to get the required output buffer
1324
// size.
1325
return (isFinal ?
1326
Integer.max(Math.addExact((inLen - TAG_LENGTH),
1327
cipherBuf.size()), 0) : 0);
1328
}
1329
1330
private EngineAEADDec() throws InvalidKeyException {
1331
initAuthenticator();
1332
counter = 1;
1333
cipherBuf = new ByteArrayOutputStream(CIPHERBUF_BASE);
1334
tag = new byte[TAG_LENGTH];
1335
}
1336
1337
@Override
1338
public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
1339
int outOff) {
1340
if (initialized) {
1341
// If this is the first update since AAD updates, signal that
1342
// we're done processing AAD info and pad the AAD to a multiple
1343
// of 16 bytes.
1344
if (!aadDone) {
1345
authPad16(aadLen);
1346
aadDone = true;
1347
}
1348
1349
if (in != null) {
1350
Objects.checkFromIndexSize(inOff, inLen, in.length);
1351
cipherBuf.write(in, inOff, inLen);
1352
}
1353
} else {
1354
throw new IllegalStateException(
1355
"Must use either a different key or iv.");
1356
}
1357
1358
return 0;
1359
}
1360
1361
@Override
1362
public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
1363
int outOff) throws ShortBufferException, AEADBadTagException,
1364
KeyException {
1365
1366
byte[] ctPlusTag;
1367
int ctPlusTagLen;
1368
if (cipherBuf.size() == 0 && inOff == 0) {
1369
// No previous data has been seen before doFinal, so we do
1370
// not need to hold any ciphertext in a buffer. We can
1371
// process it directly from the "in" parameter.
1372
doUpdate(null, inOff, inLen, out, outOff);
1373
ctPlusTag = in;
1374
ctPlusTagLen = inLen;
1375
} else {
1376
doUpdate(in, inOff, inLen, out, outOff);
1377
ctPlusTag = cipherBuf.toByteArray();
1378
ctPlusTagLen = ctPlusTag.length;
1379
}
1380
cipherBuf.reset();
1381
1382
// There must at least be a tag length's worth of ciphertext
1383
// data in the buffered input.
1384
if (ctPlusTagLen < TAG_LENGTH) {
1385
throw new AEADBadTagException("Input too short - need tag");
1386
}
1387
int ctLen = ctPlusTagLen - TAG_LENGTH;
1388
1389
// Make sure we will have enough room for the output buffer
1390
try {
1391
Objects.checkFromIndexSize(outOff, ctLen, out.length);
1392
} catch (IndexOutOfBoundsException ioobe) {
1393
throw new ShortBufferException("Output buffer too small");
1394
}
1395
1396
// Calculate and compare the tag. Only do the decryption
1397
// if and only if the tag matches.
1398
authFinalizeData(ctPlusTag, 0, ctLen, tag, 0);
1399
long tagCompare = ((long)asLongView.get(ctPlusTag, ctLen) ^
1400
(long)asLongView.get(tag, 0)) |
1401
((long)asLongView.get(ctPlusTag, ctLen + Long.BYTES) ^
1402
(long)asLongView.get(tag, Long.BYTES));
1403
if (tagCompare != 0) {
1404
throw new AEADBadTagException("Tag mismatch");
1405
}
1406
chaCha20Transform(ctPlusTag, 0, ctLen, out, outOff);
1407
aadDone = false;
1408
1409
return ctLen;
1410
}
1411
}
1412
1413
public static final class ChaCha20Only extends ChaCha20Cipher {
1414
public ChaCha20Only() {
1415
mode = MODE_NONE;
1416
}
1417
}
1418
1419
public static final class ChaCha20Poly1305 extends ChaCha20Cipher {
1420
public ChaCha20Poly1305() {
1421
mode = MODE_AEAD;
1422
authAlgName = "Poly1305";
1423
}
1424
}
1425
}
1426
1427