This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
CipherCore.java
1255 lines (1182 loc) · 48.1 KB
/
CipherCore.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.crypto.provider;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Locale;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.BadPaddingException;
/**
* This class represents the symmetric algorithms in its various modes
* (<code>ECB</code>, <code>CFB</code>, <code>OFB</code>, <code>CBC</code>,
* <code>PCBC</code>, <code>CTR</code>, and <code>CTS</code>) and
* padding schemes (<code>PKCS5Padding</code>, <code>NoPadding</code>,
* <code>ISO10126Padding</code>).
*
* @author Gigi Ankeny
* @author Jan Luehe
* @see ElectronicCodeBook
* @see CipherFeedback
* @see OutputFeedback
* @see CipherBlockChaining
* @see PCBC
* @see CounterMode
* @see CipherTextStealing
*/
final class CipherCore {
/*
* internal buffer
*/
private byte[] buffer = null;
/*
* block size of cipher in bytes
*/
private int blockSize = 0;
/*
* unit size (number of input bytes that can be processed at a time)
*/
private int unitBytes = 0;
/*
* index of the content size left in the buffer
*/
private int buffered = 0;
/*
* minimum number of bytes in the buffer required for
* FeedbackCipher.encryptFinal()/decryptFinal() call.
* update() must buffer this many bytes before starting
* to encrypt/decrypt data.
* currently, only the following cases have non-zero values:
* 1) CTS mode - due to its special handling on the last two blocks
* (the last one may be incomplete).
* 2) GCM mode + decryption - due to its trailing tag bytes
*/
private int minBytes = 0;
/*
* number of bytes needed to make the total input length a multiple
* of the blocksize (this is used in feedback mode, when the number of
* input bytes that are processed at a time is different from the block
* size)
*/
private int diffBlocksize = 0;
/*
* padding class
*/
private Padding padding = null;
/*
* internal cipher engine
*/
private FeedbackCipher cipher = null;
/*
* the cipher mode
*/
private int cipherMode = ECB_MODE;
/*
* are we encrypting or decrypting?
*/
private boolean decrypting = false;
/*
* Block Mode constants
*/
private static final int ECB_MODE = 0;
private static final int CBC_MODE = 1;
private static final int CFB_MODE = 2;
private static final int OFB_MODE = 3;
private static final int PCBC_MODE = 4;
private static final int CTR_MODE = 5;
private static final int CTS_MODE = 6;
static final int GCM_MODE = 7;
/*
* variables used for performing the GCM (key+iv) uniqueness check.
* To use GCM mode safely, the cipher object must be re-initialized
* with a different combination of key + iv values for each
* encryption operation. However, checking all past key + iv values
* isn't feasible. Thus, we only do a per-instance check of the
* key + iv values used in previous encryption.
* For decryption operations, no checking is necessary.
* NOTE: this key+iv check have to be done inside CipherCore class
* since CipherCore class buffers potential tag bytes in GCM mode
* and may not call GaloisCounterMode when there isn't sufficient
* input to process.
*/
private boolean requireReinit = false;
private byte[] lastEncKey = null;
private byte[] lastEncIv = null;
/**
* Creates an instance of CipherCore with default ECB mode and
* PKCS5Padding.
*/
CipherCore(SymmetricCipher impl, int blkSize) {
blockSize = blkSize;
unitBytes = blkSize;
diffBlocksize = blkSize;
/*
* The buffer should be usable for all cipher mode and padding
* schemes. Thus, it has to be at least (blockSize+1) for CTS.
* In decryption mode, it also hold the possible padding block.
*/
buffer = new byte[blockSize*2];
// set mode and padding
cipher = new ElectronicCodeBook(impl);
padding = new PKCS5Padding(blockSize);
}
/**
* Sets the mode of this cipher.
*
* @param mode the cipher mode
*
* @exception NoSuchAlgorithmException if the requested cipher mode does
* not exist for this cipher
*/
void setMode(String mode) throws NoSuchAlgorithmException {
if (mode == null)
throw new NoSuchAlgorithmException("null mode");
String modeUpperCase = mode.toUpperCase(Locale.ENGLISH);
if (modeUpperCase.equals("ECB")) {
return;
}
SymmetricCipher rawImpl = cipher.getEmbeddedCipher();
if (modeUpperCase.equals("CBC")) {
cipherMode = CBC_MODE;
cipher = new CipherBlockChaining(rawImpl);
} else if (modeUpperCase.equals("CTS")) {
cipherMode = CTS_MODE;
cipher = new CipherTextStealing(rawImpl);
minBytes = blockSize+1;
padding = null;
} else if (modeUpperCase.equals("CTR")) {
cipherMode = CTR_MODE;
cipher = new CounterMode(rawImpl);
unitBytes = 1;
padding = null;
} else if (modeUpperCase.equals("GCM")) {
// can only be used for block ciphers w/ 128-bit block size
if (blockSize != 16) {
throw new NoSuchAlgorithmException
("GCM mode can only be used for AES cipher");
}
cipherMode = GCM_MODE;
cipher = new GaloisCounterMode(rawImpl);
padding = null;
} else if (modeUpperCase.startsWith("CFB")) {
cipherMode = CFB_MODE;
unitBytes = getNumOfUnit(mode, "CFB".length(), blockSize);
cipher = new CipherFeedback(rawImpl, unitBytes);
} else if (modeUpperCase.startsWith("OFB")) {
cipherMode = OFB_MODE;
unitBytes = getNumOfUnit(mode, "OFB".length(), blockSize);
cipher = new OutputFeedback(rawImpl, unitBytes);
} else if (modeUpperCase.equals("PCBC")) {
cipherMode = PCBC_MODE;
cipher = new PCBC(rawImpl);
}
else {
throw new NoSuchAlgorithmException("Cipher mode: " + mode
+ " not found");
}
}
/**
* Returns the mode of this cipher.
*
* @return the parsed cipher mode
*/
int getMode() {
return cipherMode;
}
private static int getNumOfUnit(String mode, int offset, int blockSize)
throws NoSuchAlgorithmException {
int result = blockSize; // use blockSize as default value
if (mode.length() > offset) {
int numInt;
try {
Integer num = Integer.valueOf(mode.substring(offset));
numInt = num.intValue();
result = numInt >> 3;
} catch (NumberFormatException e) {
throw new NoSuchAlgorithmException
("Algorithm mode: " + mode + " not implemented");
}
if ((numInt % 8 != 0) || (result > blockSize)) {
throw new NoSuchAlgorithmException
("Invalid algorithm mode: " + mode);
}
}
return result;
}
/**
* Sets the padding mechanism of this cipher.
*
* @param paddingScheme the padding mechanism
*
* @exception NoSuchPaddingException if the requested padding mechanism
* does not exist
*/
void setPadding(String paddingScheme)
throws NoSuchPaddingException
{
if (paddingScheme == null) {
throw new NoSuchPaddingException("null padding");
}
if (paddingScheme.equalsIgnoreCase("NoPadding")) {
padding = null;
} else if (paddingScheme.equalsIgnoreCase("ISO10126Padding")) {
padding = new ISO10126Padding(blockSize);
} else if (paddingScheme.equalsIgnoreCase("PKCS5Padding")) {
padding = new PKCS5Padding(blockSize);
} else {
throw new NoSuchPaddingException("Padding: " + paddingScheme
+ " not implemented");
}
if ((padding != null) &&
((cipherMode == CTR_MODE) || (cipherMode == CTS_MODE)
|| (cipherMode == GCM_MODE))) {
padding = null;
String modeStr = null;
switch (cipherMode) {
case CTR_MODE:
modeStr = "CTR";
break;
case GCM_MODE:
modeStr = "GCM";
break;
case CTS_MODE:
modeStr = "CTS";
break;
default:
// should never happen
}
if (modeStr != null) {
throw new NoSuchPaddingException
(modeStr + " mode must be used with NoPadding");
}
}
}
/**
* Returns the length in bytes that an output buffer would need to be in
* order to hold the result of the next <code>update</code> or
* <code>doFinal</code> operation, given the input length
* <code>inputLen</code> (in bytes).
*
* <p>This call takes into account any unprocessed (buffered) data from a
* previous <code>update</code> call, padding, and AEAD tagging.
*
* <p>The actual output length of the next <code>update</code> or
* <code>doFinal</code> call may be smaller than the length returned by
* this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*/
int getOutputSize(int inputLen) {
// estimate based on the maximum
return getOutputSizeByOperation(inputLen, true);
}
private int getOutputSizeByOperation(int inputLen, boolean isDoFinal) {
int totalLen = Math.addExact(buffered, cipher.getBufferedLength());
totalLen = Math.addExact(totalLen, inputLen);
switch (cipherMode) {
case GCM_MODE:
if (isDoFinal) {
int tagLen = ((GaloisCounterMode) cipher).getTagLen();
if (!decrypting) {
totalLen = Math.addExact(totalLen, tagLen);
} else {
totalLen -= tagLen;
}
}
if (totalLen < 0) {
totalLen = 0;
}
break;
default:
if (padding != null && !decrypting) {
if (unitBytes != blockSize) {
if (totalLen < diffBlocksize) {
totalLen = diffBlocksize;
} else {
int residue = (totalLen - diffBlocksize) % blockSize;
totalLen = Math.addExact(totalLen, (blockSize - residue));
}
} else {
totalLen = Math.addExact(totalLen, padding.padLength(totalLen));
}
}
break;
}
return totalLen;
}
/**
* Returns the initialization vector (IV) in a new buffer.
*
* <p>This is useful in the case where a random IV has been created
* (see <a href = "#init">init</a>),
* or in the context of password-based encryption or
* decryption, where the IV is derived from a user-provided password.
*
* @return the initialization vector in a new buffer, or null if the
* underlying algorithm does not use an IV, or if the IV has not yet
* been set.
*/
byte[] getIV() {
byte[] iv = cipher.getIV();
return (iv == null) ? null : iv.clone();
}
/**
* Returns the parameters used with this cipher.
*
* <p>The returned parameters may be the same that were used to initialize
* this cipher, or may contain the default set of parameters or a set of
* randomly generated parameters used by the underlying cipher
* implementation (provided that the underlying cipher implementation
* uses a default set of parameters or creates new parameters if it needs
* parameters but was not initialized with any).
*
* @return the parameters used with this cipher, or null if this cipher
* does not use any parameters.
*/
AlgorithmParameters getParameters(String algName) {
if (cipherMode == ECB_MODE) {
return null;
}
AlgorithmParameters params = null;
AlgorithmParameterSpec spec;
byte[] iv = getIV();
if (iv == null) {
// generate spec using default value
if (cipherMode == GCM_MODE) {
iv = new byte[GaloisCounterMode.DEFAULT_IV_LEN];
} else {
iv = new byte[blockSize];
}
SunJCE.getRandom().nextBytes(iv);
}
if (cipherMode == GCM_MODE) {
algName = "GCM";
spec = new GCMParameterSpec
(((GaloisCounterMode) cipher).getTagLen()*8, iv);
} else {
if (algName.equals("RC2")) {
RC2Crypt rawImpl = (RC2Crypt) cipher.getEmbeddedCipher();
spec = new RC2ParameterSpec
(rawImpl.getEffectiveKeyBits(), iv);
} else {
spec = new IvParameterSpec(iv);
}
}
try {
params = AlgorithmParameters.getInstance(algName,
SunJCE.getInstance());
params.init(spec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("Cannot find " + algName +
" AlgorithmParameters implementation in SunJCE provider");
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException(spec.getClass() + " not supported");
}
return params;
}
/**
* Initializes this cipher with a key and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher requires an initialization vector (IV), it will get
* it from <code>random</code>.
* This behaviour should only be used in encryption or key wrapping
* mode, however.
* When initializing a cipher that requires an IV for decryption or
* key unwrapping, the IV
* (same IV that was used for encryption or key wrapping) must be provided
* explicitly as a
* parameter, in order to get the correct result.
*
* <p>This method also cleans existing buffer and other related state
* information.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the secret key
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
*/
void init(int opmode, Key key, SecureRandom random)
throws InvalidKeyException {
try {
init(opmode, key, (AlgorithmParameterSpec)null, random);
} catch (InvalidAlgorithmParameterException e) {
throw new InvalidKeyException(e.getMessage());
}
}
/**
* Initializes this cipher with a key, a set of
* algorithm parameters, and a source of randomness.
*
* <p>The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes, it will get them from <code>random</code>.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>,
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher
*/
void init(int opmode, Key key, AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
decrypting = (opmode == Cipher.DECRYPT_MODE)
|| (opmode == Cipher.UNWRAP_MODE);
byte[] keyBytes = getKeyBytes(key);
int tagLen = -1;
byte[] ivBytes = null;
if (params != null) {
if (cipherMode == GCM_MODE) {
if (params instanceof GCMParameterSpec) {
tagLen = ((GCMParameterSpec)params).getTLen();
if (tagLen < 96 || tagLen > 128 || ((tagLen & 0x07) != 0)) {
throw new InvalidAlgorithmParameterException
("Unsupported TLen value; must be one of " +
"{128, 120, 112, 104, 96}");
}
tagLen = tagLen >> 3;
ivBytes = ((GCMParameterSpec)params).getIV();
} else {
throw new InvalidAlgorithmParameterException
("Unsupported parameter: " + params);
}
} else {
if (params instanceof IvParameterSpec) {
ivBytes = ((IvParameterSpec)params).getIV();
if ((ivBytes == null) || (ivBytes.length != blockSize)) {
throw new InvalidAlgorithmParameterException
("Wrong IV length: must be " + blockSize +
" bytes long");
}
} else if (params instanceof RC2ParameterSpec) {
ivBytes = ((RC2ParameterSpec)params).getIV();
if ((ivBytes != null) && (ivBytes.length != blockSize)) {
throw new InvalidAlgorithmParameterException
("Wrong IV length: must be " + blockSize +
" bytes long");
}
} else {
throw new InvalidAlgorithmParameterException
("Unsupported parameter: " + params);
}
}
}
if (cipherMode == ECB_MODE) {
if (ivBytes != null) {
throw new InvalidAlgorithmParameterException
("ECB mode cannot use IV");
}
} else if (ivBytes == null) {
if (decrypting) {
throw new InvalidAlgorithmParameterException("Parameters "
+ "missing");
}
if (random == null) {
random = SunJCE.getRandom();
}
if (cipherMode == GCM_MODE) {
ivBytes = new byte[GaloisCounterMode.DEFAULT_IV_LEN];
} else {
ivBytes = new byte[blockSize];
}
random.nextBytes(ivBytes);
}
buffered = 0;
diffBlocksize = blockSize;
String algorithm = key.getAlgorithm();
// GCM mode needs additional handling
if (cipherMode == GCM_MODE) {
if(tagLen == -1) {
tagLen = GaloisCounterMode.DEFAULT_TAG_LEN;
}
if (decrypting) {
minBytes = tagLen;
} else {
// check key+iv for encryption in GCM mode
requireReinit =
Arrays.equals(ivBytes, lastEncIv) &&
MessageDigest.isEqual(keyBytes, lastEncKey);
if (requireReinit) {
throw new InvalidAlgorithmParameterException
("Cannot reuse iv for GCM encryption");
}
lastEncIv = ivBytes;
lastEncKey = keyBytes;
}
((GaloisCounterMode) cipher).init
(decrypting, algorithm, keyBytes, ivBytes, tagLen);
} else {
cipher.init(decrypting, algorithm, keyBytes, ivBytes);
}
// skip checking key+iv from now on until after doFinal()
requireReinit = false;
}
void init(int opmode, Key key, AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
AlgorithmParameterSpec spec = null;
String paramType = null;
if (params != null) {
try {
if (cipherMode == GCM_MODE) {
paramType = "GCM";
spec = params.getParameterSpec(GCMParameterSpec.class);
} else {
// NOTE: RC2 parameters are always handled through
// init(..., AlgorithmParameterSpec,...) method, so
// we can assume IvParameterSpec type here.
paramType = "IV";
spec = params.getParameterSpec(IvParameterSpec.class);
}
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException
("Wrong parameter type: " + paramType + " expected");
}
}
init(opmode, key, spec, random);
}
/**
* Return the key bytes of the specified key. Throw an InvalidKeyException
* if the key is not usable.
*/
static byte[] getKeyBytes(Key key) throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("No key given");
}
// note: key.getFormat() may return null
if (!"RAW".equalsIgnoreCase(key.getFormat())) {
throw new InvalidKeyException("Wrong format: RAW bytes needed");
}
byte[] keyBytes = key.getEncoded();
if (keyBytes == null) {
throw new InvalidKeyException("RAW key bytes missing");
}
return keyBytes;
}
/**
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, are processed, and the
* result is stored in a new buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
*/
byte[] update(byte[] input, int inputOffset, int inputLen) {
checkReinit();
byte[] output = null;
try {
output = new byte[getOutputSizeByOperation(inputLen, false)];
int len = update(input, inputOffset, inputLen, output,
0);
if (len == output.length) {
return output;
} else {
byte[] copy = Arrays.copyOf(output, len);
if (decrypting) {
// Zero out internal buffer which is no longer required
Arrays.fill(output, (byte) 0x00);
}
return copy;
}
} catch (ShortBufferException e) {
// should never happen
throw new ProviderException("Unexpected exception", e);
}
}
/**
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, are processed, and the
* result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code>.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
*/
int update(byte[] input, int inputOffset, int inputLen, byte[] output,
int outputOffset) throws ShortBufferException {
checkReinit();
// figure out how much can be sent to crypto function
int len = Math.addExact(buffered, inputLen);
len -= minBytes;
if (padding != null && decrypting) {
// do not include the padding bytes when decrypting
len -= blockSize;
}
// do not count the trailing bytes which do not make up a unit
len = (len > 0 ? (len - (len % unitBytes)) : 0);
// check output buffer capacity
if (output == null || (output.length - outputOffset) < len) {
throw new ShortBufferException("Output buffer must be "
+ "(at least) " + len
+ " bytes long");
}
int outLen = 0;
if (len != 0) { // there is some work to do
if ((input == output)
&& (outputOffset - inputOffset < inputLen)
&& (inputOffset - outputOffset < buffer.length)) {
// copy 'input' out to avoid its content being
// overwritten prematurely.
input = Arrays.copyOfRange(input, inputOffset,
Math.addExact(inputOffset, inputLen));
inputOffset = 0;
}
if (len <= buffered) {
// all to-be-processed data are from 'buffer'
if (decrypting) {
outLen = cipher.decrypt(buffer, 0, len, output, outputOffset);
} else {
outLen = cipher.encrypt(buffer, 0, len, output, outputOffset);
}
buffered -= len;
if (buffered != 0) {
System.arraycopy(buffer, len, buffer, 0, buffered);
}
} else { // len > buffered
int inputConsumed = len - buffered;
int temp;
if (buffered > 0) {
int bufferCapacity = buffer.length - buffered;
if (bufferCapacity != 0) {
temp = Math.min(bufferCapacity, inputConsumed);
if (unitBytes != blockSize) {
temp -= (Math.addExact(buffered, temp) % unitBytes);
}
System.arraycopy(input, inputOffset, buffer, buffered, temp);
inputOffset = Math.addExact(inputOffset, temp);
inputConsumed -= temp;
inputLen -= temp;
buffered = Math.addExact(buffered, temp);
}
// process 'buffer'. When finished we can null out 'buffer'
// Only necessary to null out if buffer holds data for encryption
if (decrypting) {
outLen = cipher.decrypt(buffer, 0, buffered, output, outputOffset);
} else {
outLen = cipher.encrypt(buffer, 0, buffered, output, outputOffset);
//encrypt mode. Zero out internal (input) buffer
Arrays.fill(buffer, (byte) 0x00);
}
outputOffset = Math.addExact(outputOffset, outLen);
buffered = 0;
}
if (inputConsumed > 0) { // still has input to process
if (decrypting) {
outLen += cipher.decrypt(input, inputOffset, inputConsumed,
output, outputOffset);
} else {
outLen += cipher.encrypt(input, inputOffset, inputConsumed,
output, outputOffset);
}
inputOffset += inputConsumed;
inputLen -= inputConsumed;
}
}
// Let's keep track of how many bytes are needed to make
// the total input length a multiple of blocksize when
// padding is applied
if (unitBytes != blockSize) {
if (len < diffBlocksize) {
diffBlocksize -= len;
} else {
diffBlocksize = blockSize -
((len - diffBlocksize) % blockSize);
}
}
}
// Store remaining input into 'buffer' again
if (inputLen > 0) {
System.arraycopy(input, inputOffset, buffer, buffered,
inputLen);
buffered = Math.addExact(buffered, inputLen);
}
return outLen;
}
/**
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in a new buffer.
*
* <p>The cipher is reset to its initial state (uninitialized) after this
* call.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
byte[] doFinal(byte[] input, int inputOffset, int inputLen)
throws IllegalBlockSizeException, BadPaddingException {
try {
checkReinit();
byte[] output = new byte[getOutputSizeByOperation(inputLen, true)];
byte[] finalBuf = prepareInputBuffer(input, inputOffset,
inputLen, output, 0);
int finalOffset = (finalBuf == input) ? inputOffset : 0;
int finalBufLen = (finalBuf == input) ? inputLen : finalBuf.length;
int outLen = fillOutputBuffer(finalBuf, finalOffset, output, 0,
finalBufLen, input);
endDoFinal();
if (outLen < output.length) {
byte[] copy = Arrays.copyOf(output, outLen);
if (decrypting) {
// Zero out internal (ouput) array
Arrays.fill(output, (byte) 0x00);
}
return copy;
} else {
return output;
}
} catch (ShortBufferException e) {
// never thrown
throw new ProviderException("Unexpected exception", e);
}
}
/**
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code>.
*
* <p>The cipher is reset to its initial state (uninitialized) after this
* call.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
int doFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
int outputOffset)
throws IllegalBlockSizeException, ShortBufferException,
BadPaddingException {
checkReinit();
int estOutSize = getOutputSizeByOperation(inputLen, true);
int outputCapacity = checkOutputCapacity(output, outputOffset,
estOutSize);
int offset = outputOffset;
byte[] finalBuf = prepareInputBuffer(input, inputOffset,
inputLen, output, outputOffset);
byte[] internalOutput = null; // for decrypting only
int finalOffset = (finalBuf == input) ? inputOffset : 0;
int finalBufLen = (finalBuf == input) ? inputLen : finalBuf.length;
if (decrypting) {
// if the size of specified output buffer is less than
// the length of the cipher text, then the current
// content of cipher has to be preserved in order for
// users to retry the call with a larger buffer in the
// case of ShortBufferException.
if (outputCapacity < estOutSize) {
cipher.save();
}
if (getMode() != GCM_MODE || outputCapacity < estOutSize) {
// create temporary output buffer if the estimated size is larger
// than the user-provided buffer.
internalOutput = new byte[estOutSize];
offset = 0;
}
}
byte[] outBuffer = (internalOutput != null) ? internalOutput : output;
int outLen = fillOutputBuffer(finalBuf, finalOffset, outBuffer,
offset, finalBufLen, input);
if (decrypting) {
if (outputCapacity < outLen) {
// restore so users can retry with a larger buffer
cipher.restore();
throw new ShortBufferException("Output buffer too short: "
+ (outputCapacity)
+ " bytes given, " + outLen
+ " bytes needed");
}
// copy the result into user-supplied output buffer
if (internalOutput != null) {
System.arraycopy(internalOutput, 0, output, outputOffset, outLen);
// decrypt mode. Zero out output data that's not required
Arrays.fill(internalOutput, (byte) 0x00);
}
}
endDoFinal();
return outLen;
}
private void endDoFinal() {
buffered = 0;
diffBlocksize = blockSize;
if (cipherMode != ECB_MODE) {
cipher.reset();
}
}
private int unpad(int outLen, int off, byte[] outWithPadding)
throws BadPaddingException {
int padStart = padding.unpad(outWithPadding, off, outLen);
if (padStart < 0) {
throw new BadPaddingException("Given final block not " +
"properly padded. Such issues can arise if a bad key " +
"is used during decryption.");
}
return padStart - off;
}
private byte[] prepareInputBuffer(byte[] input, int inputOffset,
int inputLen, byte[] output, int outputOffset)
throws IllegalBlockSizeException, ShortBufferException {
// calculate total input length
int len = Math.addExact(buffered, inputLen);
// calculate padding length
int totalLen = Math.addExact(len, cipher.getBufferedLength());
int paddingLen = 0;
// will the total input length be a multiple of blockSize?
if (unitBytes != blockSize) {
if (totalLen < diffBlocksize) {
paddingLen = diffBlocksize - totalLen;