forked from wolfSSL/wolfcrypt-jni
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWolfCryptCipher.java
More file actions
2197 lines (1834 loc) · 74.5 KB
/
WolfCryptCipher.java
File metadata and controls
2197 lines (1834 loc) · 74.5 KB
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
/* WolfCryptCipher.java
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
package com.wolfssl.provider.jce;
import java.util.Arrays;
import java.nio.ByteBuffer;
import javax.crypto.Cipher;
import javax.crypto.CipherSpi;
import javax.crypto.SecretKey;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.AEADBadTagException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.security.KeyFactory;
import java.security.spec.MGF1ParameterSpec;
import java.security.AlgorithmParameters;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidParameterException;
import java.security.InvalidKeyException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPublicKey;
import com.wolfssl.wolfcrypt.Aes;
import com.wolfssl.wolfcrypt.AesEcb;
import com.wolfssl.wolfcrypt.AesCtr;
import com.wolfssl.wolfcrypt.AesOfb;
import com.wolfssl.wolfcrypt.AesGcm;
import com.wolfssl.wolfcrypt.AesCcm;
import com.wolfssl.wolfcrypt.AesCts;
import com.wolfssl.wolfcrypt.Des3;
import com.wolfssl.wolfcrypt.Rsa;
import com.wolfssl.wolfcrypt.Rng;
import com.wolfssl.wolfcrypt.WolfCrypt;
import com.wolfssl.wolfcrypt.WolfCryptError;
import com.wolfssl.wolfcrypt.WolfCryptException;
/**
* wolfCrypt JCE Cipher (AES, 3DES) wrapper
*/
public class WolfCryptCipher extends CipherSpi {
enum CipherType {
WC_AES,
WC_DES3,
WC_RSA
}
enum CipherMode {
WC_ECB,
WC_CBC,
WC_CTR,
WC_OFB,
WC_GCM,
WC_CCM,
WC_CTS
}
enum PaddingType {
WC_NONE,
WC_PKCS1,
WC_PKCS5,
WC_OAEP_SHA1,
WC_OAEP_SHA256
}
enum OpMode {
WC_ENCRYPT,
WC_DECRYPT
}
enum RsaKeyType {
WC_RSA_PRIVATE,
WC_RSA_PUBLIC
}
private CipherType cipherType = null;
private CipherMode cipherMode = null;
private PaddingType paddingType = null;
private OpMode direction = null;
private RsaKeyType rsaKeyType = null;
/* Store original opmode (ENCRYPT, DECRYPT, WRAP, UNWRAP), used by
* post-doFinal reset to restore correct mode */
private int storedOpMode = 0;
private int blockSize = 0;
private Aes aes = null;
private AesEcb aesEcb = null;
private AesCtr aesCtr = null;
private AesOfb aesOfb = null;
private AesGcm aesGcm = null;
private AesCcm aesCcm = null;
private AesCts aesCts = null;
private Des3 des3 = null;
private Rsa rsa = null;
private Rng rng = null;
/* RSA-OAEP parameters */
private int oaepHashType = 0;
private int oaepMgf = 0;
/* for debug logging */
private String algString;
private String algMode;
/* stash key and IV here for easy lookup */
private Key storedKey = null;
private AlgorithmParameterSpec storedSpec = null;
private byte[] iv = null;
/* AES-GCM/CCM tag length (bytes), default to 128 bits */
private int gcmTagLen = 16;
/* AAD data for AES-GCM, populated via engineUpdateAAD() */
private byte[] aadData = null;
/* Has update/final been called yet, gates setting of AAD for GCM */
private boolean operationStarted = false;
/* Has this Cipher been inintialized? */
private boolean cipherInitialized = false;
/* buffered data from update calls */
private byte[] buffered = new byte[0];
private WolfCryptCipher(CipherType type, CipherMode mode,
PaddingType pad) {
this.cipherType = type;
this.cipherMode = mode;
this.paddingType = pad;
/* Initialize OAEP parameters if using OAEP padding */
if (pad == PaddingType.WC_OAEP_SHA256) {
initOaepParams();
} else if (pad == PaddingType.WC_OAEP_SHA1) {
initOaepParamsSha1();
}
switch (cipherType) {
case WC_AES:
blockSize = Aes.BLOCK_SIZE;
break;
case WC_DES3:
blockSize = Des3.BLOCK_SIZE;
break;
case WC_RSA:
break;
}
if (WolfCryptDebug.DEBUG) {
algString = typeToString(cipherType);
algMode = modeToString(cipherMode);
}
}
/**
* Initialize OAEP parameters for RSA-OAEP padding.
* Uses SHA-256 for OAEP hash and SHA-1 for MGF1 hash to match
* JCE default behavior for OAEPWithSHA-256AndMGF1Padding.
*/
private void initOaepParams() {
this.oaepHashType = WolfCrypt.WC_HASH_TYPE_SHA256;
this.oaepMgf = Rsa.WC_MGF1SHA1;
}
/**
* Initialize OAEP parameters for RSA-OAEP padding with SHA-1.
* Uses SHA-1 for OAEP hash and SHA-1 for MGF1 hash to match
* JCE default behavior for OAEPWithSHA-1AndMGF1Padding.
*/
private void initOaepParamsSha1() {
this.oaepHashType = WolfCrypt.WC_HASH_TYPE_SHA;
this.oaepMgf = Rsa.WC_MGF1SHA1;
}
/**
* Convert JCE hash algorithm name to wolfCrypt hash type constant.
*
* @param hashAlgo JCE hash algorithm name (e.g., "SHA-256", "SHA-1")
* @return wolfCrypt hash type constant
* @throws InvalidAlgorithmParameterException if hash algorithm is not
* supported
*/
private int hashNameToWolfCryptType(String hashAlgo)
throws InvalidAlgorithmParameterException {
if (hashAlgo == null) {
throw new InvalidAlgorithmParameterException(
"Hash algorithm name cannot be null");
}
switch (hashAlgo.toUpperCase()) {
case "SHA-1":
case "SHA1":
return WolfCrypt.WC_HASH_TYPE_SHA;
case "SHA-224":
case "SHA224":
return WolfCrypt.WC_HASH_TYPE_SHA224;
case "SHA-256":
case "SHA256":
return WolfCrypt.WC_HASH_TYPE_SHA256;
case "SHA-384":
case "SHA384":
return WolfCrypt.WC_HASH_TYPE_SHA384;
case "SHA-512":
case "SHA512":
return WolfCrypt.WC_HASH_TYPE_SHA512;
default:
throw new InvalidAlgorithmParameterException(
"Unsupported OAEP hash algorithm: " + hashAlgo);
}
}
/**
* Convert MGF1ParameterSpec to wolfCrypt MGF type constant.
*
* @param mgfSpec MGF1ParameterSpec containing the hash algorithm
* @return wolfCrypt MGF type constant
* @throws InvalidAlgorithmParameterException if MGF hash algorithm is not
* supported
*/
private int mgf1SpecToWolfCryptMgf(MGF1ParameterSpec mgfSpec)
throws InvalidAlgorithmParameterException {
if (mgfSpec == null) {
throw new InvalidAlgorithmParameterException(
"MGF1ParameterSpec cannot be null");
}
String hashAlgo = mgfSpec.getDigestAlgorithm();
switch (hashAlgo.toUpperCase()) {
case "SHA-1":
case "SHA1":
return Rsa.WC_MGF1SHA1;
case "SHA-224":
case "SHA224":
return Rsa.WC_MGF1SHA224;
case "SHA-256":
case "SHA256":
return Rsa.WC_MGF1SHA256;
case "SHA-384":
case "SHA384":
return Rsa.WC_MGF1SHA384;
case "SHA-512":
case "SHA512":
return Rsa.WC_MGF1SHA512;
default:
throw new InvalidAlgorithmParameterException(
"Unsupported MGF1 hash algorithm: " + hashAlgo);
}
}
/**
* Set OAEP parameters from OAEPParameterSpec.
*
* @param spec OAEPParameterSpec containing OAEP parameters
* @throws InvalidAlgorithmParameterException if parameters are invalid
*/
private void setOaepParams(OAEPParameterSpec spec)
throws InvalidAlgorithmParameterException {
AlgorithmParameterSpec mgfParams = null;
PSource pSource = null;
if (spec == null) {
throw new InvalidAlgorithmParameterException(
"OAEPParameterSpec cannot be null");
}
/* Validate MGF algorithm is MGF1 */
if (!spec.getMGFAlgorithm().equals("MGF1") &&
!spec.getMGFAlgorithm().equals(OAEPParameterSpec.DEFAULT.
getMGFAlgorithm())) {
throw new InvalidAlgorithmParameterException(
"Only MGF1 is supported for OAEP, got: " +
spec.getMGFAlgorithm());
}
/* Get MGF parameters */
mgfParams = spec.getMGFParameters();
if (!(mgfParams instanceof MGF1ParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"MGF parameters must be MGF1ParameterSpec");
}
/* Validate PSource is PSpecified with empty label (default) */
pSource = spec.getPSource();
if (pSource != null && pSource instanceof PSource.PSpecified) {
byte[] label = ((PSource.PSpecified) pSource).getValue();
if (label != null && label.length > 0) {
throw new InvalidAlgorithmParameterException(
"OAEP label (PSource) must be empty, custom labels " +
"are not supported");
}
}
/* Set OAEP hash type */
this.oaepHashType = hashNameToWolfCryptType(spec.getDigestAlgorithm());
/* Set MGF type */
this.oaepMgf = mgf1SpecToWolfCryptMgf((MGF1ParameterSpec) mgfParams);
log("set OAEP params: hash=" + spec.getDigestAlgorithm() +
", mgf1Hash=" + ((MGF1ParameterSpec) mgfParams).
getDigestAlgorithm());
}
/**
* Reset / re-create internal native struct for algorithm.
* Should be called during wolfCryptInit() and wolfCryptFinal()
*/
private void InitializeNativeStructs() {
switch (this.cipherType) {
case WC_AES:
if (cipherMode == CipherMode.WC_CBC) {
if (aes != null) {
aes.releaseNativeStruct();
aes = null;
}
aes = new Aes();
}
else if (cipherMode == CipherMode.WC_ECB) {
if (aesEcb != null) {
aesEcb.releaseNativeStruct();
aesEcb = null;
}
aesEcb = new AesEcb();
}
else if (cipherMode == CipherMode.WC_CTR) {
if (aesCtr != null) {
aesCtr.releaseNativeStruct();
aesCtr = null;
}
aesCtr = new AesCtr();
}
else if (cipherMode == CipherMode.WC_OFB) {
if (aesOfb != null) {
aesOfb.releaseNativeStruct();
aesOfb = null;
}
aesOfb = new AesOfb();
}
else if (cipherMode == CipherMode.WC_GCM) {
if (aesGcm != null) {
aesGcm.releaseNativeStruct();
aesGcm = null;
}
aesGcm = new AesGcm();
}
else if (cipherMode == CipherMode.WC_CCM) {
if (aesCcm != null) {
aesCcm.releaseNativeStruct();
aesCcm = null;
}
aesCcm = new AesCcm();
}
else if (cipherMode == CipherMode.WC_CTS) {
if (aesCts != null) {
aesCts.releaseNativeStruct();
aesCts = null;
}
aesCts = new AesCts();
}
break;
case WC_DES3:
if (des3 != null) {
des3.releaseNativeStruct();
des3 = null;
}
des3 = new Des3();
break;
case WC_RSA:
/* RSA struct creation handled in wolfCryptSetKey() */
break;
}
}
@Override
protected void engineSetMode(String mode)
throws NoSuchAlgorithmException {
int supported = 0;
if (mode.equals("ECB")) {
/* RSA and AES support ECB mode */
if (cipherType == CipherType.WC_RSA ||
cipherType == CipherType.WC_AES) {
cipherMode = CipherMode.WC_ECB;
supported = 1;
log("set mode to ECB");
}
} else if (mode.equals("CBC")) {
/* AES and 3DES support CBC */
if (cipherType == CipherType.WC_AES ||
cipherType == CipherType.WC_DES3 ) {
cipherMode = CipherMode.WC_CBC;
supported = 1;
log("set mode to CBC");
}
} else if (mode.equals("CTR")) {
/* AES supports CTR */
if (cipherType == CipherType.WC_AES) {
cipherMode = CipherMode.WC_CTR;
supported = 1;
log("set mode to CTR");
}
} else if (mode.equals("OFB")) {
/* AES supports OFB */
if (cipherType == CipherType.WC_AES) {
cipherMode = CipherMode.WC_OFB;
supported = 1;
log("set mode to OFB");
}
} else if (mode.equals("GCM")) {
/* AES supports GCM */
if (cipherType == CipherType.WC_AES) {
cipherMode = CipherMode.WC_GCM;
supported = 1;
log("set mode to GCM");
}
} else if (mode.equals("CCM")) {
/* AES supports CCM */
if (cipherType == CipherType.WC_AES) {
cipherMode = CipherMode.WC_CCM;
supported = 1;
log("set mode to CCM");
}
} else if (mode.equals("CTS")) {
/* AES supports CTS */
if (cipherType == CipherType.WC_AES) {
cipherMode = CipherMode.WC_CTS;
supported = 1;
log("set mode to CTS");
}
}
if (supported == 0) {
throw new NoSuchAlgorithmException(
"Unsupported cipher mode for active algorithm choice: " +
mode);
}
}
@Override
protected void engineSetPadding(String padding)
throws NoSuchPaddingException {
int supported = 0;
if (padding.equals("NoPadding")) {
if (cipherType == CipherType.WC_AES ||
cipherType == CipherType.WC_DES3) {
paddingType = PaddingType.WC_NONE;
supported = 1;
log("set padding to NoPadding");
}
} else if (padding.equals("PKCS1Padding")) {
if (cipherType == CipherType.WC_RSA) {
paddingType = PaddingType.WC_PKCS1;
supported = 1;
log("set padding to PKCS1Padding");
}
} else if (padding.equals("PKCS5Padding")) {
if ((cipherType == CipherType.WC_AES) &&
(cipherMode == CipherMode.WC_CBC ||
cipherMode == CipherMode.WC_ECB)) {
paddingType = PaddingType.WC_PKCS5;
supported = 1;
log("set padding to PKCS5Padding");
}
} else if (padding.equals("OAEPWithSHA-256AndMGF1Padding") ||
padding.equals("OAEPWithSHA256AndMGF1Padding")) {
if (cipherType == CipherType.WC_RSA) {
paddingType = PaddingType.WC_OAEP_SHA256;
initOaepParams();
supported = 1;
log("set padding to OAEPWithSHA-256AndMGF1Padding");
}
} else if (padding.equals("OAEPWithSHA-1AndMGF1Padding") ||
padding.equals("OAEPWithSHA1AndMGF1Padding")) {
if (cipherType == CipherType.WC_RSA) {
paddingType = PaddingType.WC_OAEP_SHA1;
initOaepParamsSha1();
supported = 1;
log("set padding to OAEPWithSHA-1AndMGF1Padding");
}
}
if (supported == 0) {
throw new NoSuchPaddingException(
"Unsupported padding type for active algorithm choice: " +
padding);
}
}
@Override
protected int engineGetBlockSize() {
return this.blockSize;
}
@Override
protected int engineGetOutputSize(int inputLen)
throws IllegalStateException {
int outSize = 0;
int totalSz = inputLen;
int totalBlocks = 0;
if (!this.cipherInitialized) {
throw new IllegalStateException(
"Cipher has not been initialized yet");
}
/* Add buffered data size to input length, calculate total blocks */
if (isBlockCipher()) {
if (buffered != null && buffered.length > 0) {
totalSz = inputLen + buffered.length;
} else {
totalSz = inputLen;
}
/* For block ciphers that require block boundaries, round
* to next block size. GCM, CCM, CTR, CTS, and OFB do not require
* block boundaries. */
if (cipherMode != CipherMode.WC_GCM &&
cipherMode != CipherMode.WC_CCM &&
cipherMode != CipherMode.WC_CTR &&
cipherMode != CipherMode.WC_CTS &&
cipherMode != CipherMode.WC_OFB) {
totalBlocks = totalSz / blockSize;
totalSz = totalBlocks * blockSize;
}
}
switch (this.cipherType) {
case WC_AES:
if (paddingType == PaddingType.WC_NONE) {
if (cipherMode == CipherMode.WC_GCM) {
/* In AES-GCM mode we append the authentication tag
* to the end of ciphertext, When decrypting, output
* size will have it taken off. */
if (this.direction == OpMode.WC_ENCRYPT) {
outSize = totalSz + this.gcmTagLen;
}
else {
outSize = totalSz - this.gcmTagLen;
}
outSize = Math.max(outSize, 0);
}
else {
/* wolfCrypt expects input to be padded by application
* to block size, thus output is same size as input.
* If we have buffered data, and that plus inputLen
* makes another block, we will have one more block of
* data. */
outSize = totalSz;
}
}
else if (paddingType == PaddingType.WC_PKCS5) {
outSize = inputLen;
if (buffered != null && buffered.length > 0) {
outSize += buffered.length;
}
/* Only add padding size when encrypting. When decrypting,
* the output size should not include padding bytes since
* they will be stripped off during decryption. */
if (this.direction == OpMode.WC_ENCRYPT) {
outSize += Aes.getPKCS7PadSize(outSize, Aes.BLOCK_SIZE);
}
}
else {
throw new IllegalStateException(
"Unsupported padding mode for Cipher Aes");
}
break;
case WC_DES3:
if (paddingType == PaddingType.WC_NONE) {
/* wolfCrypt expects input to be padded by application to
* block size, thus output is same size as input */
outSize = totalSz;
}
else if (paddingType == PaddingType.WC_PKCS5) {
outSize = inputLen;
if (buffered != null && buffered.length > 0) {
outSize += buffered.length;
}
/* Only add padding size when encrypting. When decrypting,
* the output size should not include padding bytes since
* they will be stripped off during decryption. */
if (this.direction == OpMode.WC_ENCRYPT) {
outSize += Des3.getPKCS7PadSize(outSize,
Des3.BLOCK_SIZE);
}
}
else {
throw new IllegalStateException(
"Unsupported padding mode for Cipher Des3");
}
break;
case WC_RSA:
outSize = this.rsa.getEncryptSize();
break;
}
return outSize;
}
@Override
protected byte[] engineGetIV() {
if (this.iv != null) {
return this.iv.clone();
}
return null;
}
@Override
protected AlgorithmParameters engineGetParameters() {
AlgorithmParameters params = null;
try {
switch (this.cipherMode) {
case WC_GCM:
case WC_CCM:
/* Return parameters only if initialized */
if (this.iv != null && this.gcmTagLen > 0) {
params = AlgorithmParameters.getInstance("GCM");
GCMParameterSpec gcmSpec = new GCMParameterSpec(
this.gcmTagLen * 8, this.iv);
params.init(gcmSpec);
}
break;
case WC_CBC:
case WC_CTR:
case WC_OFB:
if (this.iv != null) {
if (this.cipherType == CipherType.WC_AES) {
params = AlgorithmParameters.getInstance("AES");
}
else if (this.cipherType == CipherType.WC_DES3) {
params = AlgorithmParameters.getInstance("DESede");
}
if (params != null) {
IvParameterSpec ivSpec =
new IvParameterSpec(this.iv);
params.init(ivSpec);
}
}
break;
/* ECB mode doesn't have parameters to return */
case WC_ECB:
break;
}
} catch (NoSuchAlgorithmException |
InvalidParameterSpecException e) {
/* Return null if parameter creation fails */
params = null;
}
return params;
}
private void wolfCryptSetDirection(int opmode)
throws InvalidKeyException {
this.storedOpMode = opmode;
switch (opmode) {
case Cipher.ENCRYPT_MODE:
this.direction = OpMode.WC_ENCRYPT;
break;
case Cipher.DECRYPT_MODE:
this.direction = OpMode.WC_DECRYPT;
break;
case Cipher.WRAP_MODE:
this.direction = OpMode.WC_ENCRYPT;
break;
case Cipher.UNWRAP_MODE:
this.direction = OpMode.WC_DECRYPT;
break;
default:
throw new InvalidParameterException(
"Cipher opmode must be ENCRYPT_MODE, " +
"DECRYPT_MODE, WRAP_MODE, or UNWRAP_MODE");
}
}
private void wolfCryptSetIV(AlgorithmParameterSpec spec,
SecureRandom random) throws InvalidAlgorithmParameterException {
/* store AlgorithmParameterSpec for class reset */
this.storedSpec = spec;
/* Handle RSA OAEP parameters if provided */
if (this.cipherType == CipherType.WC_RSA) {
if (spec != null) {
if (spec instanceof OAEPParameterSpec) {
if (this.paddingType != PaddingType.WC_OAEP_SHA256 &&
this.paddingType != PaddingType.WC_OAEP_SHA1) {
throw new InvalidAlgorithmParameterException(
"OAEPParameterSpec can only be used with " +
"OAEP padding modes");
}
setOaepParams((OAEPParameterSpec) spec);
} else {
throw new InvalidAlgorithmParameterException(
"AlgorithmParameterSpec for RSA OAEP must be of " +
"type OAEPParameterSpec");
}
}
return;
}
/* AES-ECB doesn't need an IV */
if (this.cipherType == CipherType.WC_AES &&
this.cipherMode == CipherMode.WC_ECB)
return;
/* store IV, or generate random IV if not available */
if (spec == null) {
this.iv = new byte[this.blockSize];
if (random != null) {
random.nextBytes(this.iv);
} else {
SecureRandom rand = new SecureRandom();
rand.nextBytes(this.iv);
}
} else {
if (cipherMode == CipherMode.WC_GCM) {
if (!(spec instanceof GCMParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"AlgorithmParameterSpec must be of type " +
"GCMParameterSpec");
}
GCMParameterSpec gcmSpec = (GCMParameterSpec)spec;
if (gcmSpec.getIV() == null ||
gcmSpec.getIV().length == 0) {
throw new InvalidAlgorithmParameterException(
"AES-GCM IV is null or 0 length");
}
this.iv = gcmSpec.getIV().clone();
/* store tag length as bytes */
if (gcmSpec.getTLen() == 0) {
throw new InvalidAlgorithmParameterException(
"Tag length cannot be zero");
}
this.gcmTagLen = (gcmSpec.getTLen() / 8);
}
else if (cipherMode == CipherMode.WC_CCM) {
/*
* CCM Parameter Handling:
* We use GCMParameterSpec for CCM mode to maintain
* compatibility with:
* 1. Java 8+ (CCMParameterSpec only available in Java 11+)
* 2. BouncyCastle provider (uses GCMParameterSpec for CCM)
* 3. Existing developer expectations and code patterns
*/
if (!(spec instanceof GCMParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"AlgorithmParameterSpec must be of type " +
"GCMParameterSpec for AES-CCM");
}
GCMParameterSpec ccmSpec = (GCMParameterSpec)spec;
if (ccmSpec.getIV() == null || ccmSpec.getIV().length == 0) {
throw new InvalidAlgorithmParameterException(
"AES-CCM nonce is null or 0 length");
}
/* CCM nonce length validation (7-15 bytes typical) */
if (ccmSpec.getIV().length < 7 || ccmSpec.getIV().length > 15) {
throw new InvalidAlgorithmParameterException(
"CCM nonce length must be 7-15 bytes, got: " +
ccmSpec.getIV().length);
}
this.iv = ccmSpec.getIV().clone();
/* store tag length as bytes */
if (ccmSpec.getTLen() == 0) {
throw new InvalidAlgorithmParameterException(
"Tag length cannot be zero");
}
this.gcmTagLen = (ccmSpec.getTLen() / 8);
}
else {
if (!(spec instanceof IvParameterSpec)) {
throw new InvalidAlgorithmParameterException(
"AlgorithmParameterSpec must be of type " +
"IvParameterSpec");
}
IvParameterSpec ivSpec = (IvParameterSpec)spec;
/* IV should be of block size length */
if (ivSpec.getIV().length != this.blockSize) {
throw new InvalidAlgorithmParameterException(
"Bad IV length (" + ivSpec.getIV().length +
"), must be " + blockSize + " bytes long");
}
this.iv = ivSpec.getIV().clone();
}
}
}
private void wolfCryptSetKey(Key key)
throws InvalidKeyException {
byte[] encodedKey;
/* validate key class type */
if (this.cipherType == CipherType.WC_RSA) {
if (key instanceof RSAPrivateKey) {
this.rsaKeyType = RsaKeyType.WC_RSA_PRIVATE;
/* wolfSSL requires CRT parameters for RSA private key
* operations. Non-CRT keys (created with only modulus and
* private exponent) will fail with "mp_exptmod error state"
* or similar in the native layer. */
if (!(key instanceof RSAPrivateCrtKey)) {
throw new InvalidKeyException(
"wolfSSL requires RSA private keys to include CRT " +
"parameters (p, q, dP, dQ, qInv). Keys created from " +
"only modulus and exponent are not supported.");
}
} else if (key instanceof RSAPublicKey) {
this.rsaKeyType = RsaKeyType.WC_RSA_PUBLIC;
} else {
throw new InvalidKeyException(
"Cipher key must be of type RSAPrivateKey or " +
"RSAPublicKey when used for RSA encrypt or decrypt");
}
} else if (!(key instanceof SecretKey)) {
throw new InvalidKeyException(
"Cipher key must be of type SecretKey");
}
/* save key for class state resets */
this.storedKey = key;
/* import key */
encodedKey = key.getEncoded();
if (encodedKey == null) {
throw new InvalidKeyException("Key does not support encoding");
}
switch (cipherType) {
case WC_AES:
if (this.direction == OpMode.WC_ENCRYPT) {
if (cipherMode == CipherMode.WC_GCM) {
this.aesGcm.setKey(encodedKey);
}
else if (cipherMode == CipherMode.WC_CCM) {
this.aesCcm.setKey(encodedKey);
}
else if (cipherMode == CipherMode.WC_CTS) {
this.aesCts.setKey(encodedKey, iv, AesCts.ENCRYPT_MODE);
}
else if (cipherMode == CipherMode.WC_ECB) {
this.aesEcb.setKey(
encodedKey, null, AesEcb.ENCRYPT_MODE);
}
else if (cipherMode == CipherMode.WC_CTR) {
this.aesCtr.setKey(encodedKey, iv);
}
else if (cipherMode == CipherMode.WC_OFB) {
this.aesOfb.setKey(encodedKey, iv, AesOfb.ENCRYPT_MODE);
}
else {
this.aes.setKey(encodedKey, iv, Aes.ENCRYPT_MODE);
}
} else {
if (cipherMode == CipherMode.WC_GCM) {
this.aesGcm.setKey(encodedKey);
}
else if (cipherMode == CipherMode.WC_CCM) {
this.aesCcm.setKey(encodedKey);
}
else if (cipherMode == CipherMode.WC_CTS) {
this.aesCts.setKey(encodedKey, iv, AesCts.DECRYPT_MODE);
}
else if (cipherMode == CipherMode.WC_ECB) {
this.aesEcb.setKey(
encodedKey, null, AesEcb.DECRYPT_MODE);
}
else if (cipherMode == CipherMode.WC_CTR) {
this.aesCtr.setKey(encodedKey, iv);
}
else if (cipherMode == CipherMode.WC_OFB) {
this.aesOfb.setKey(encodedKey, iv, AesOfb.ENCRYPT_MODE);
}
else {
this.aes.setKey(encodedKey, iv, Aes.DECRYPT_MODE);
}
}
break;