Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/com/sun/crypto/provider/ChaCha20Cipher.java
41161 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
if ((opmode == Cipher.WRAP_MODE) || (opmode == Cipher.UNWRAP_MODE)) {
539
throw new UnsupportedOperationException(
540
"WRAP_MODE and UNWRAP_MODE are not currently supported");
541
} else if ((opmode != Cipher.ENCRYPT_MODE) &&
542
(opmode != Cipher.DECRYPT_MODE)) {
543
throw new InvalidKeyException("Unknown opmode: " + opmode);
544
}
545
546
// Make sure that the provided key and nonce are unique before
547
// assigning them to the object.
548
byte[] newKeyBytes = getEncodedKey(key);
549
checkKeyAndNonce(newKeyBytes, newNonce);
550
if (this.keyBytes != null) {
551
Arrays.fill(this.keyBytes, (byte)0);
552
}
553
this.keyBytes = newKeyBytes;
554
nonce = newNonce;
555
556
// Now that we have the key and nonce, we can build the initial state
557
setInitialState();
558
559
if (mode == MODE_NONE) {
560
engine = new EngineStreamOnly();
561
} else if (mode == MODE_AEAD) {
562
if (opmode == Cipher.ENCRYPT_MODE) {
563
engine = new EngineAEADEnc();
564
} else if (opmode == Cipher.DECRYPT_MODE) {
565
engine = new EngineAEADDec();
566
} else {
567
throw new InvalidKeyException("Not encrypt or decrypt mode");
568
}
569
}
570
571
// We can also get one block's worth of keystream created
572
finalCounterValue = counter + MAX_UINT32;
573
generateKeystream();
574
direction = opmode;
575
aadDone = false;
576
this.keyStrOffset = 0;
577
initialized = true;
578
}
579
580
/**
581
* Check the key and nonce bytes to make sure that they do not repeat
582
* across reinitialization.
583
*
584
* @param newKeyBytes the byte encoding for the newly provided key
585
* @param newNonce the new nonce to be used with this initialization
586
*
587
* @throws InvalidKeyException if both the key and nonce match the
588
* previous initialization.
589
*
590
*/
591
private void checkKeyAndNonce(byte[] newKeyBytes, byte[] newNonce)
592
throws InvalidKeyException {
593
// A new initialization must have either a different key or nonce
594
// so the starting state for each block is not the same as the
595
// previous initialization.
596
if (MessageDigest.isEqual(newKeyBytes, keyBytes) &&
597
MessageDigest.isEqual(newNonce, nonce)) {
598
throw new InvalidKeyException(
599
"Matching key and nonce from previous initialization");
600
}
601
}
602
603
/**
604
* Return the encoded key as a byte array
605
*
606
* @param key the {@code Key} object used for this {@code Cipher}
607
*
608
* @return the key bytes
609
*
610
* @throws InvalidKeyException if the key is of the wrong type or length,
611
* or if the key encoding format is not {@code RAW}.
612
*/
613
private static byte[] getEncodedKey(Key key) throws InvalidKeyException {
614
if ("RAW".equals(key.getFormat()) == false) {
615
throw new InvalidKeyException("Key encoding format must be RAW");
616
}
617
byte[] encodedKey = key.getEncoded();
618
if (encodedKey == null || encodedKey.length != 32) {
619
if (encodedKey != null) {
620
Arrays.fill(encodedKey, (byte)0);
621
}
622
throw new InvalidKeyException("Key length must be 256 bits");
623
}
624
return encodedKey;
625
}
626
627
/**
628
* Update the currently running operation with additional data
629
*
630
* @param in the plaintext or ciphertext input bytes (depending on the
631
* operation type).
632
* @param inOfs the offset into the input array
633
* @param inLen the length of the data to use for the update operation.
634
*
635
* @return the resulting plaintext or ciphertext bytes (depending on
636
* the operation type)
637
*/
638
@Override
639
protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
640
byte[] out = new byte[engine.getOutputSize(inLen, false)];
641
try {
642
engine.doUpdate(in, inOfs, inLen, out, 0);
643
} catch (ShortBufferException | KeyException exc) {
644
throw new RuntimeException(exc);
645
}
646
647
return out;
648
}
649
650
/**
651
* Update the currently running operation with additional data
652
*
653
* @param in the plaintext or ciphertext input bytes (depending on the
654
* operation type).
655
* @param inOfs the offset into the input array
656
* @param inLen the length of the data to use for the update operation.
657
* @param out the byte array that will hold the resulting data. The array
658
* must be large enough to hold the resulting data.
659
* @param outOfs the offset for the {@code out} buffer to begin writing
660
* the resulting data.
661
*
662
* @return the length in bytes of the data written into the {@code out}
663
* buffer.
664
*
665
* @throws ShortBufferException if the buffer {@code out} does not have
666
* enough space to hold the resulting data.
667
*/
668
@Override
669
protected int engineUpdate(byte[] in, int inOfs, int inLen,
670
byte[] out, int outOfs) throws ShortBufferException {
671
int bytesUpdated = 0;
672
try {
673
bytesUpdated = engine.doUpdate(in, inOfs, inLen, out, outOfs);
674
} catch (KeyException ke) {
675
throw new RuntimeException(ke);
676
}
677
return bytesUpdated;
678
}
679
680
/**
681
* Complete the currently running operation using any final
682
* data provided by the caller.
683
*
684
* @param in the plaintext or ciphertext input bytes (depending on the
685
* operation type).
686
* @param inOfs the offset into the input array
687
* @param inLen the length of the data to use for the update operation.
688
*
689
* @return the resulting plaintext or ciphertext bytes (depending on
690
* the operation type)
691
*
692
* @throws AEADBadTagException if, during decryption, the provided tag
693
* does not match the calculated tag.
694
*/
695
@Override
696
protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
697
throws AEADBadTagException {
698
byte[] output = new byte[engine.getOutputSize(inLen, true)];
699
try {
700
engine.doFinal(in, inOfs, inLen, output, 0);
701
} catch (ShortBufferException | KeyException exc) {
702
throw new RuntimeException(exc);
703
} finally {
704
// Regardless of what happens, the cipher cannot be used for
705
// further processing until it has been freshly initialized.
706
initialized = false;
707
}
708
return output;
709
}
710
711
/**
712
* Complete the currently running operation using any final
713
* data provided by the caller.
714
*
715
* @param in the plaintext or ciphertext input bytes (depending on the
716
* operation type).
717
* @param inOfs the offset into the input array
718
* @param inLen the length of the data to use for the update operation.
719
* @param out the byte array that will hold the resulting data. The array
720
* must be large enough to hold the resulting data.
721
* @param outOfs the offset for the {@code out} buffer to begin writing
722
* the resulting data.
723
*
724
* @return the length in bytes of the data written into the {@code out}
725
* buffer.
726
*
727
* @throws ShortBufferException if the buffer {@code out} does not have
728
* enough space to hold the resulting data.
729
* @throws AEADBadTagException if, during decryption, the provided tag
730
* does not match the calculated tag.
731
*/
732
@Override
733
protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
734
int outOfs) throws ShortBufferException, AEADBadTagException {
735
736
int bytesUpdated = 0;
737
try {
738
bytesUpdated = engine.doFinal(in, inOfs, inLen, out, outOfs);
739
} catch (KeyException ke) {
740
throw new RuntimeException(ke);
741
} finally {
742
// Regardless of what happens, the cipher cannot be used for
743
// further processing until it has been freshly initialized.
744
initialized = false;
745
}
746
return bytesUpdated;
747
}
748
749
/**
750
* Wrap a {@code Key} using this Cipher's current encryption parameters.
751
*
752
* @param key the key to wrap. The data that will be encrypted will
753
* be the provided {@code Key} in its encoded form.
754
*
755
* @return a byte array consisting of the wrapped key.
756
*
757
* @throws UnsupportedOperationException this will (currently) always
758
* be thrown, as this method is not currently supported.
759
*/
760
@Override
761
protected byte[] engineWrap(Key key) throws IllegalBlockSizeException,
762
InvalidKeyException {
763
throw new UnsupportedOperationException(
764
"Wrap operations are not supported");
765
}
766
767
/**
768
* Unwrap a {@code Key} using this Cipher's current encryption parameters.
769
*
770
* @param wrappedKey the key to unwrap.
771
* @param algorithm the algorithm associated with the wrapped key
772
* @param type the type of the wrapped key. This is one of
773
* {@code SECRET_KEY}, {@code PRIVATE_KEY}, or {@code PUBLIC_KEY}.
774
*
775
* @return the unwrapped key as a {@code Key} object.
776
*
777
* @throws UnsupportedOperationException this will (currently) always
778
* be thrown, as this method is not currently supported.
779
*/
780
@Override
781
protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
782
int type) throws InvalidKeyException, NoSuchAlgorithmException {
783
throw new UnsupportedOperationException(
784
"Unwrap operations are not supported");
785
}
786
787
/**
788
* Get the length of a provided key in bits.
789
*
790
* @param key the key to be evaluated
791
*
792
* @return the length of the key in bits
793
*
794
* @throws InvalidKeyException if the key is invalid or does not
795
* have an encoded form.
796
*/
797
@Override
798
protected int engineGetKeySize(Key key) throws InvalidKeyException {
799
byte[] encodedKey = getEncodedKey(key);
800
Arrays.fill(encodedKey, (byte)0);
801
return encodedKey.length << 3;
802
}
803
804
/**
805
* Set the initial state. This will populate the state array and put the
806
* key and nonce into their proper locations. The counter field is not
807
* set here.
808
*
809
* @throws IllegalArgumentException if the key or nonce are not in
810
* their proper lengths (32 bytes for the key, 12 bytes for the
811
* nonce).
812
* @throws InvalidKeyException if the key does not support an encoded form.
813
*/
814
private void setInitialState() throws InvalidKeyException {
815
// Apply constants to first 4 words
816
startState[0] = STATE_CONST_0;
817
startState[1] = STATE_CONST_1;
818
startState[2] = STATE_CONST_2;
819
startState[3] = STATE_CONST_3;
820
821
// Apply the key bytes as 8 32-bit little endian ints (4 through 11)
822
for (int i = 0; i < 32; i += 4) {
823
startState[(i / 4) + 4] = (keyBytes[i] & 0x000000FF) |
824
((keyBytes[i + 1] << 8) & 0x0000FF00) |
825
((keyBytes[i + 2] << 16) & 0x00FF0000) |
826
((keyBytes[i + 3] << 24) & 0xFF000000);
827
}
828
829
startState[12] = 0;
830
831
// The final integers for the state are from the nonce
832
// interpreted as 3 little endian integers
833
for (int i = 0; i < 12; i += 4) {
834
startState[(i / 4) + 13] = (nonce[i] & 0x000000FF) |
835
((nonce[i + 1] << 8) & 0x0000FF00) |
836
((nonce[i + 2] << 16) & 0x00FF0000) |
837
((nonce[i + 3] << 24) & 0xFF000000);
838
}
839
}
840
841
/**
842
* Using the current state and counter create the next set of keystream
843
* bytes. This method will generate the next 512 bits of keystream and
844
* return it in the {@code keyStream} parameter. Following the
845
* block function the counter will be incremented.
846
*/
847
private void generateKeystream() {
848
chaCha20Block(startState, counter, keyStream);
849
counter++;
850
}
851
852
/**
853
* Perform a full 20-round ChaCha20 transform on the initial state.
854
*
855
* @param initState the starting state, not including the counter
856
* value.
857
* @param counter the counter value to apply
858
* @param result the array that will hold the result of the ChaCha20
859
* block function.
860
*
861
* @note it is the caller's responsibility to ensure that the workState
862
* is sized the same as the initState, no checking is performed internally.
863
*/
864
private static void chaCha20Block(int[] initState, long counter,
865
byte[] result) {
866
// Create an initial state and clone a working copy
867
int ws00 = STATE_CONST_0;
868
int ws01 = STATE_CONST_1;
869
int ws02 = STATE_CONST_2;
870
int ws03 = STATE_CONST_3;
871
int ws04 = initState[4];
872
int ws05 = initState[5];
873
int ws06 = initState[6];
874
int ws07 = initState[7];
875
int ws08 = initState[8];
876
int ws09 = initState[9];
877
int ws10 = initState[10];
878
int ws11 = initState[11];
879
int ws12 = (int)counter;
880
int ws13 = initState[13];
881
int ws14 = initState[14];
882
int ws15 = initState[15];
883
884
// Peform 10 iterations of the 8 quarter round set
885
for (int round = 0; round < 10; round++) {
886
ws00 += ws04;
887
ws12 = Integer.rotateLeft(ws12 ^ ws00, 16);
888
889
ws08 += ws12;
890
ws04 = Integer.rotateLeft(ws04 ^ ws08, 12);
891
892
ws00 += ws04;
893
ws12 = Integer.rotateLeft(ws12 ^ ws00, 8);
894
895
ws08 += ws12;
896
ws04 = Integer.rotateLeft(ws04 ^ ws08, 7);
897
898
ws01 += ws05;
899
ws13 = Integer.rotateLeft(ws13 ^ ws01, 16);
900
901
ws09 += ws13;
902
ws05 = Integer.rotateLeft(ws05 ^ ws09, 12);
903
904
ws01 += ws05;
905
ws13 = Integer.rotateLeft(ws13 ^ ws01, 8);
906
907
ws09 += ws13;
908
ws05 = Integer.rotateLeft(ws05 ^ ws09, 7);
909
910
ws02 += ws06;
911
ws14 = Integer.rotateLeft(ws14 ^ ws02, 16);
912
913
ws10 += ws14;
914
ws06 = Integer.rotateLeft(ws06 ^ ws10, 12);
915
916
ws02 += ws06;
917
ws14 = Integer.rotateLeft(ws14 ^ ws02, 8);
918
919
ws10 += ws14;
920
ws06 = Integer.rotateLeft(ws06 ^ ws10, 7);
921
922
ws03 += ws07;
923
ws15 = Integer.rotateLeft(ws15 ^ ws03, 16);
924
925
ws11 += ws15;
926
ws07 = Integer.rotateLeft(ws07 ^ ws11, 12);
927
928
ws03 += ws07;
929
ws15 = Integer.rotateLeft(ws15 ^ ws03, 8);
930
931
ws11 += ws15;
932
ws07 = Integer.rotateLeft(ws07 ^ ws11, 7);
933
934
ws00 += ws05;
935
ws15 = Integer.rotateLeft(ws15 ^ ws00, 16);
936
937
ws10 += ws15;
938
ws05 = Integer.rotateLeft(ws05 ^ ws10, 12);
939
940
ws00 += ws05;
941
ws15 = Integer.rotateLeft(ws15 ^ ws00, 8);
942
943
ws10 += ws15;
944
ws05 = Integer.rotateLeft(ws05 ^ ws10, 7);
945
946
ws01 += ws06;
947
ws12 = Integer.rotateLeft(ws12 ^ ws01, 16);
948
949
ws11 += ws12;
950
ws06 = Integer.rotateLeft(ws06 ^ ws11, 12);
951
952
ws01 += ws06;
953
ws12 = Integer.rotateLeft(ws12 ^ ws01, 8);
954
955
ws11 += ws12;
956
ws06 = Integer.rotateLeft(ws06 ^ ws11, 7);
957
958
ws02 += ws07;
959
ws13 = Integer.rotateLeft(ws13 ^ ws02, 16);
960
961
ws08 += ws13;
962
ws07 = Integer.rotateLeft(ws07 ^ ws08, 12);
963
964
ws02 += ws07;
965
ws13 = Integer.rotateLeft(ws13 ^ ws02, 8);
966
967
ws08 += ws13;
968
ws07 = Integer.rotateLeft(ws07 ^ ws08, 7);
969
970
ws03 += ws04;
971
ws14 = Integer.rotateLeft(ws14 ^ ws03, 16);
972
973
ws09 += ws14;
974
ws04 = Integer.rotateLeft(ws04 ^ ws09, 12);
975
976
ws03 += ws04;
977
ws14 = Integer.rotateLeft(ws14 ^ ws03, 8);
978
979
ws09 += ws14;
980
ws04 = Integer.rotateLeft(ws04 ^ ws09, 7);
981
}
982
983
// Add the end working state back into the original state
984
asIntLittleEndian.set(result, 0, ws00 + STATE_CONST_0);
985
asIntLittleEndian.set(result, 4, ws01 + STATE_CONST_1);
986
asIntLittleEndian.set(result, 8, ws02 + STATE_CONST_2);
987
asIntLittleEndian.set(result, 12, ws03 + STATE_CONST_3);
988
asIntLittleEndian.set(result, 16, ws04 + initState[4]);
989
asIntLittleEndian.set(result, 20, ws05 + initState[5]);
990
asIntLittleEndian.set(result, 24, ws06 + initState[6]);
991
asIntLittleEndian.set(result, 28, ws07 + initState[7]);
992
asIntLittleEndian.set(result, 32, ws08 + initState[8]);
993
asIntLittleEndian.set(result, 36, ws09 + initState[9]);
994
asIntLittleEndian.set(result, 40, ws10 + initState[10]);
995
asIntLittleEndian.set(result, 44, ws11 + initState[11]);
996
// Add the counter back into workState[12]
997
asIntLittleEndian.set(result, 48, ws12 + (int)counter);
998
asIntLittleEndian.set(result, 52, ws13 + initState[13]);
999
asIntLittleEndian.set(result, 56, ws14 + initState[14]);
1000
asIntLittleEndian.set(result, 60, ws15 + initState[15]);
1001
}
1002
1003
/**
1004
* Perform the ChaCha20 transform.
1005
*
1006
* @param in the array of bytes for the input
1007
* @param inOff the offset into the input array to start the transform
1008
* @param inLen the length of the data to perform the transform on.
1009
* @param out the output array. It must be large enough to hold the
1010
* resulting data
1011
* @param outOff the offset into the output array to place the resulting
1012
* data.
1013
*/
1014
private void chaCha20Transform(byte[] in, int inOff, int inLen,
1015
byte[] out, int outOff) throws KeyException {
1016
int remainingData = inLen;
1017
1018
while (remainingData > 0) {
1019
int ksRemain = keyStream.length - keyStrOffset;
1020
if (ksRemain <= 0) {
1021
if (counter <= finalCounterValue) {
1022
generateKeystream();
1023
keyStrOffset = 0;
1024
ksRemain = keyStream.length;
1025
} else {
1026
throw new KeyException("Counter exhausted. " +
1027
"Reinitialize with new key and/or nonce");
1028
}
1029
}
1030
1031
// XOR each byte in the keystream against the input
1032
int xformLen = Math.min(remainingData, ksRemain);
1033
xor(keyStream, keyStrOffset, in, inOff, out, outOff, xformLen);
1034
outOff += xformLen;
1035
inOff += xformLen;
1036
keyStrOffset += xformLen;
1037
remainingData -= xformLen;
1038
}
1039
}
1040
1041
private static void xor(byte[] in1, int off1, byte[] in2, int off2,
1042
byte[] out, int outOff, int len) {
1043
while (len >= 8) {
1044
long v1 = (long) asLongView.get(in1, off1);
1045
long v2 = (long) asLongView.get(in2, off2);
1046
asLongView.set(out, outOff, v1 ^ v2);
1047
off1 += 8;
1048
off2 += 8;
1049
outOff += 8;
1050
len -= 8;
1051
}
1052
while (len > 0) {
1053
out[outOff] = (byte) (in1[off1] ^ in2[off2]);
1054
off1++;
1055
off2++;
1056
outOff++;
1057
len--;
1058
}
1059
}
1060
1061
/**
1062
* Perform initialization steps for the authenticator
1063
*
1064
* @throws InvalidKeyException if the key is unusable for some reason
1065
* (invalid length, etc.)
1066
*/
1067
private void initAuthenticator() throws InvalidKeyException {
1068
authenticator = new Poly1305();
1069
1070
// Derive the Poly1305 key from the starting state
1071
byte[] serializedKey = new byte[KEYSTREAM_SIZE];
1072
chaCha20Block(startState, 0, serializedKey);
1073
1074
authenticator.engineInit(new SecretKeySpec(serializedKey, 0, 32,
1075
authAlgName), null);
1076
aadLen = 0;
1077
dataLen = 0;
1078
}
1079
1080
/**
1081
* Update the authenticator state with data. This routine can be used
1082
* to add data to the authenticator, whether AAD or application data.
1083
*
1084
* @param data the data to stir into the authenticator.
1085
* @param offset the offset into the data.
1086
* @param length the length of data to add to the authenticator.
1087
*
1088
* @return the number of bytes processed by this method.
1089
*/
1090
private int authUpdate(byte[] data, int offset, int length) {
1091
Objects.checkFromIndexSize(offset, length, data.length);
1092
authenticator.engineUpdate(data, offset, length);
1093
return length;
1094
}
1095
1096
/**
1097
* Finalize the data and return the tag.
1098
*
1099
* @param data an array containing any remaining data to process.
1100
* @param dataOff the offset into the data.
1101
* @param length the length of the data to process.
1102
* @param out the array to write the resulting tag into
1103
* @param outOff the offset to begin writing the data.
1104
*
1105
* @throws ShortBufferException if there is insufficient room to
1106
* write the tag.
1107
*/
1108
private void authFinalizeData(byte[] data, int dataOff, int length,
1109
byte[] out, int outOff) throws ShortBufferException {
1110
// Update with the final chunk of ciphertext, then pad to a
1111
// multiple of 16.
1112
if (data != null) {
1113
dataLen += authUpdate(data, dataOff, length);
1114
}
1115
authPad16(dataLen);
1116
1117
// Also write the AAD and ciphertext data lengths as little-endian
1118
// 64-bit values.
1119
authWriteLengths(aadLen, dataLen, lenBuf);
1120
authenticator.engineUpdate(lenBuf, 0, lenBuf.length);
1121
byte[] tag = authenticator.engineDoFinal();
1122
Objects.checkFromIndexSize(outOff, tag.length, out.length);
1123
System.arraycopy(tag, 0, out, outOff, tag.length);
1124
aadLen = 0;
1125
dataLen = 0;
1126
}
1127
1128
/**
1129
* Based on a given length of data, make the authenticator process
1130
* zero bytes that will pad the length out to a multiple of 16.
1131
*
1132
* @param dataLen the starting length to be padded.
1133
*/
1134
private void authPad16(long dataLen) {
1135
// Pad out the AAD or data to a multiple of 16 bytes
1136
authenticator.engineUpdate(padBuf, 0,
1137
(TAG_LENGTH - ((int)dataLen & 15)) & 15);
1138
}
1139
1140
/**
1141
* Write the two 64-bit little-endian length fields into an array
1142
* for processing by the poly1305 authenticator.
1143
*
1144
* @param aLen the length of the AAD.
1145
* @param dLen the length of the application data.
1146
* @param buf the buffer to write the two lengths into.
1147
*
1148
* @note it is the caller's responsibility to provide an array large
1149
* enough to hold the two longs.
1150
*/
1151
private void authWriteLengths(long aLen, long dLen, byte[] buf) {
1152
asLongLittleEndian.set(buf, 0, aLen);
1153
asLongLittleEndian.set(buf, Long.BYTES, dLen);
1154
}
1155
1156
/**
1157
* Interface for the underlying processing engines for ChaCha20
1158
*/
1159
interface ChaChaEngine {
1160
/**
1161
* Size an output buffer based on the input and where applicable
1162
* the current state of the engine in a multipart operation.
1163
*
1164
* @param inLength the input length.
1165
* @param isFinal true if this is invoked from a doFinal call.
1166
*
1167
* @return the recommended size for the output buffer.
1168
*/
1169
int getOutputSize(int inLength, boolean isFinal);
1170
1171
/**
1172
* Perform a multi-part update for ChaCha20.
1173
*
1174
* @param in the input data.
1175
* @param inOff the offset into the input.
1176
* @param inLen the length of the data to process.
1177
* @param out the output buffer.
1178
* @param outOff the offset at which to write the output data.
1179
*
1180
* @return the number of output bytes written.
1181
*
1182
* @throws ShortBufferException if the output buffer does not
1183
* provide enough space.
1184
* @throws KeyException if the counter value has been exhausted.
1185
*/
1186
int doUpdate(byte[] in, int inOff, int inLen, byte[] out, int outOff)
1187
throws ShortBufferException, KeyException;
1188
1189
/**
1190
* Finalize a multi-part or single-part ChaCha20 operation.
1191
*
1192
* @param in the input data.
1193
* @param inOff the offset into the input.
1194
* @param inLen the length of the data to process.
1195
* @param out the output buffer.
1196
* @param outOff the offset at which to write the output data.
1197
*
1198
* @return the number of output bytes written.
1199
*
1200
* @throws ShortBufferException if the output buffer does not
1201
* provide enough space.
1202
* @throws AEADBadTagException if in decryption mode the provided
1203
* tag and calculated tag do not match.
1204
* @throws KeyException if the counter value has been exhausted.
1205
*/
1206
int doFinal(byte[] in, int inOff, int inLen, byte[] out, int outOff)
1207
throws ShortBufferException, AEADBadTagException, KeyException;
1208
}
1209
1210
private final class EngineStreamOnly implements ChaChaEngine {
1211
1212
private EngineStreamOnly () { }
1213
1214
@Override
1215
public int getOutputSize(int inLength, boolean isFinal) {
1216
// The isFinal parameter is not relevant in this kind of engine
1217
return inLength;
1218
}
1219
1220
@Override
1221
public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
1222
int outOff) throws ShortBufferException, KeyException {
1223
if (initialized) {
1224
try {
1225
if (out != null) {
1226
Objects.checkFromIndexSize(outOff, inLen, out.length);
1227
} else {
1228
throw new ShortBufferException(
1229
"Output buffer too small");
1230
}
1231
} catch (IndexOutOfBoundsException iobe) {
1232
throw new ShortBufferException("Output buffer too small");
1233
}
1234
if (in != null) {
1235
Objects.checkFromIndexSize(inOff, inLen, in.length);
1236
chaCha20Transform(in, inOff, inLen, out, outOff);
1237
}
1238
return inLen;
1239
} else {
1240
throw new IllegalStateException(
1241
"Must use either a different key or iv.");
1242
}
1243
}
1244
1245
@Override
1246
public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
1247
int outOff) throws ShortBufferException, KeyException {
1248
return doUpdate(in, inOff, inLen, out, outOff);
1249
}
1250
}
1251
1252
private final class EngineAEADEnc implements ChaChaEngine {
1253
1254
@Override
1255
public int getOutputSize(int inLength, boolean isFinal) {
1256
return (isFinal ? Math.addExact(inLength, TAG_LENGTH) : inLength);
1257
}
1258
1259
private EngineAEADEnc() throws InvalidKeyException {
1260
initAuthenticator();
1261
counter = 1;
1262
}
1263
1264
@Override
1265
public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
1266
int outOff) throws ShortBufferException, KeyException {
1267
if (initialized) {
1268
// If this is the first update since AAD updates, signal that
1269
// we're done processing AAD info and pad the AAD to a multiple
1270
// of 16 bytes.
1271
if (!aadDone) {
1272
authPad16(aadLen);
1273
aadDone = true;
1274
}
1275
try {
1276
if (out != null) {
1277
Objects.checkFromIndexSize(outOff, inLen, out.length);
1278
} else {
1279
throw new ShortBufferException(
1280
"Output buffer too small");
1281
}
1282
} catch (IndexOutOfBoundsException iobe) {
1283
throw new ShortBufferException("Output buffer too small");
1284
}
1285
if (in != null) {
1286
Objects.checkFromIndexSize(inOff, inLen, in.length);
1287
chaCha20Transform(in, inOff, inLen, out, outOff);
1288
dataLen += authUpdate(out, outOff, inLen);
1289
}
1290
1291
return inLen;
1292
} else {
1293
throw new IllegalStateException(
1294
"Must use either a different key or iv.");
1295
}
1296
}
1297
1298
@Override
1299
public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
1300
int outOff) throws ShortBufferException, KeyException {
1301
// Make sure we have enough room for the remaining data (if any)
1302
// and the tag.
1303
if ((inLen + TAG_LENGTH) > (out.length - outOff)) {
1304
throw new ShortBufferException("Output buffer too small");
1305
}
1306
1307
doUpdate(in, inOff, inLen, out, outOff);
1308
authFinalizeData(null, 0, 0, out, outOff + inLen);
1309
aadDone = false;
1310
return inLen + TAG_LENGTH;
1311
}
1312
}
1313
1314
private final class EngineAEADDec implements ChaChaEngine {
1315
1316
private final ByteArrayOutputStream cipherBuf;
1317
private final byte[] tag;
1318
1319
@Override
1320
public int getOutputSize(int inLen, boolean isFinal) {
1321
// If we are performing a decrypt-update we should always return
1322
// zero length since we cannot return any data until the tag has
1323
// been consumed and verified. CipherSpi.engineGetOutputSize will
1324
// always set isFinal to true to get the required output buffer
1325
// size.
1326
return (isFinal ?
1327
Integer.max(Math.addExact((inLen - TAG_LENGTH),
1328
cipherBuf.size()), 0) : 0);
1329
}
1330
1331
private EngineAEADDec() throws InvalidKeyException {
1332
initAuthenticator();
1333
counter = 1;
1334
cipherBuf = new ByteArrayOutputStream(CIPHERBUF_BASE);
1335
tag = new byte[TAG_LENGTH];
1336
}
1337
1338
@Override
1339
public int doUpdate(byte[] in, int inOff, int inLen, byte[] out,
1340
int outOff) {
1341
if (initialized) {
1342
// If this is the first update since AAD updates, signal that
1343
// we're done processing AAD info and pad the AAD to a multiple
1344
// of 16 bytes.
1345
if (!aadDone) {
1346
authPad16(aadLen);
1347
aadDone = true;
1348
}
1349
1350
if (in != null) {
1351
Objects.checkFromIndexSize(inOff, inLen, in.length);
1352
cipherBuf.write(in, inOff, inLen);
1353
}
1354
} else {
1355
throw new IllegalStateException(
1356
"Must use either a different key or iv.");
1357
}
1358
1359
return 0;
1360
}
1361
1362
@Override
1363
public int doFinal(byte[] in, int inOff, int inLen, byte[] out,
1364
int outOff) throws ShortBufferException, AEADBadTagException,
1365
KeyException {
1366
1367
byte[] ctPlusTag;
1368
int ctPlusTagLen;
1369
if (cipherBuf.size() == 0 && inOff == 0) {
1370
// No previous data has been seen before doFinal, so we do
1371
// not need to hold any ciphertext in a buffer. We can
1372
// process it directly from the "in" parameter.
1373
doUpdate(null, inOff, inLen, out, outOff);
1374
ctPlusTag = in;
1375
ctPlusTagLen = inLen;
1376
} else {
1377
doUpdate(in, inOff, inLen, out, outOff);
1378
ctPlusTag = cipherBuf.toByteArray();
1379
ctPlusTagLen = ctPlusTag.length;
1380
}
1381
cipherBuf.reset();
1382
1383
// There must at least be a tag length's worth of ciphertext
1384
// data in the buffered input.
1385
if (ctPlusTagLen < TAG_LENGTH) {
1386
throw new AEADBadTagException("Input too short - need tag");
1387
}
1388
int ctLen = ctPlusTagLen - TAG_LENGTH;
1389
1390
// Make sure we will have enough room for the output buffer
1391
try {
1392
Objects.checkFromIndexSize(outOff, ctLen, out.length);
1393
} catch (IndexOutOfBoundsException ioobe) {
1394
throw new ShortBufferException("Output buffer too small");
1395
}
1396
1397
// Calculate and compare the tag. Only do the decryption
1398
// if and only if the tag matches.
1399
authFinalizeData(ctPlusTag, 0, ctLen, tag, 0);
1400
long tagCompare = ((long)asLongView.get(ctPlusTag, ctLen) ^
1401
(long)asLongView.get(tag, 0)) |
1402
((long)asLongView.get(ctPlusTag, ctLen + Long.BYTES) ^
1403
(long)asLongView.get(tag, Long.BYTES));
1404
if (tagCompare != 0) {
1405
throw new AEADBadTagException("Tag mismatch");
1406
}
1407
chaCha20Transform(ctPlusTag, 0, ctLen, out, outOff);
1408
aadDone = false;
1409
1410
return ctLen;
1411
}
1412
}
1413
1414
public static final class ChaCha20Only extends ChaCha20Cipher {
1415
public ChaCha20Only() {
1416
mode = MODE_NONE;
1417
}
1418
}
1419
1420
public static final class ChaCha20Poly1305 extends ChaCha20Cipher {
1421
public ChaCha20Poly1305() {
1422
mode = MODE_AEAD;
1423
authAlgName = "Poly1305";
1424
}
1425
}
1426
}
1427
1428