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