-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathDESedeCipher.java
More file actions
352 lines (301 loc) · 12.4 KB
/
DESedeCipher.java
File metadata and controls
352 lines (301 loc) · 12.4 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
/*
* Copyright IBM Corp. 2023, 2026
*
* This code is free software; you can redistribute it and/or modify it
* under the terms provided by IBM in the LICENSE file that accompanied
* this code, including the "Classpath" Exception described therein.
*/
package com.ibm.crypto.plus.provider;
import com.ibm.crypto.plus.provider.base.Padding;
import com.ibm.crypto.plus.provider.base.SymmetricCipher;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.ProviderException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
public final class DESedeCipher extends LegacyCipher implements DESConstants {
private OpenJCEPlusProvider provider = null;
private SymmetricCipher symmetricCipher = null;
private String mode = "ECB";
private Padding padding = Padding.PKCS5Padding;
private byte[] iv = null;
private boolean encrypting = true;
private boolean initialized = false;
private SecureRandom cryptoRandom = null;
private String configAlgName = "DESede";
public DESedeCipher(OpenJCEPlusProvider provider) {
this.provider = provider;
}
public DESedeCipher(OpenJCEPlusProvider provider, String algName) {
this.provider = provider;
this.configAlgName = algName;
}
@Override
protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
throws IllegalBlockSizeException, BadPaddingException {
checkCipherInitialized();
try {
byte[] output = new byte[engineGetOutputSize(inputLen)];
int outputLen = symmetricCipher.doFinal(input, inputOffset, inputLen, output, 0);
if (outputLen < output.length) {
byte[] out = Arrays.copyOfRange(output, 0, outputLen);
if (!encrypting) {
Arrays.fill(output, 0, outputLen, (byte) 0x00);
}
return out;
} else {
return output;
}
} catch (BadPaddingException | IllegalBlockSizeException exc) {
throw exc;
} catch (Exception e) {
throw provider.providerException("Failure in engineDoFinal", e);
}
}
@Override
protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
int outputOffset)
throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
checkCipherInitialized();
try {
return symmetricCipher.doFinal(input, inputOffset, inputLen, output, outputOffset);
} catch (BadPaddingException | IllegalBlockSizeException | ShortBufferException exc) {
throw exc;
} catch (Exception e) {
throw provider.providerException("Failure in engineDoFinal", e);
}
}
@Override
protected int engineGetBlockSize() {
return DES_BLOCK_SIZE;
}
@Override
protected int engineGetKeySize(Key key) throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("Key missing");
}
byte[] encoded = key.getEncoded();
if (encoded.length != 24) {
throw new InvalidKeyException("Invalid key length: " + encoded.length + " bytes");
}
return 168;
}
@Override
protected byte[] engineGetIV() {
return (this.iv == null) ? null : this.iv.clone();
}
@Override
protected int engineGetOutputSize(int inputLen) {
try {
return symmetricCipher.getOutputSize(inputLen);
} catch (Exception e) {
throw provider.providerException("Unable to get output size", e);
}
}
@Override
protected AlgorithmParameters engineGetParameters() {
AlgorithmParameters params = null;
if (this.iv != null) {
IvParameterSpec ivSpec = new IvParameterSpec(this.iv);
try {
params = AlgorithmParameters.getInstance("DESede", provider);
params.init(ivSpec);
} catch (NoSuchAlgorithmException nsae) {
throw new ProviderException(
"Cannot find DESede AlgorithmParameters implementation in "
+ provider.getName() + " provider");
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new ProviderException(ivSpec.getClass() + " not supported");
}
}
return params;
}
@Override
protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException {
if (mode.equals("ECB")) {
internalInit(opmode, key, null);
return;
}
if ((opmode == Cipher.DECRYPT_MODE) || (opmode == Cipher.UNWRAP_MODE)) {
throw new InvalidKeyException("Parameters missing");
}
if (cryptoRandom == null) {
cryptoRandom = provider.getSecureRandom(random);
}
byte[] generatedIv = new byte[DES_BLOCK_SIZE];
cryptoRandom.nextBytes(generatedIv);
internalInit(opmode, key, generatedIv);
}
@Override
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
if (params == null) {
engineInit(opmode, key, random);
} else {
if (params instanceof IvParameterSpec) {
byte[] iv = ((IvParameterSpec) params).getIV();
if (iv.length != DES_BLOCK_SIZE) {
throw new InvalidAlgorithmParameterException(
"IV must be " + DES_BLOCK_SIZE + " bytes");
}
internalInit(opmode, key, iv);
} else {
throw new InvalidAlgorithmParameterException("Wrong parameter type: IV expected");
}
}
}
@Override
protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
IvParameterSpec ivSpec = null;
if (params != null) {
try {
ivSpec = params.getParameterSpec(IvParameterSpec.class);
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException("Wrong parameter type: IV expected");
}
}
engineInit(opmode, key, ivSpec, random);
}
private void internalInit(int opmode, Key key, byte[] iv) throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("Key missing");
}
if (!(key.getAlgorithm().equalsIgnoreCase("DESede"))) {
throw new InvalidKeyException("Wrong algorithm: DESede required");
}
if (!(key.getFormat().equalsIgnoreCase("RAW"))) {
throw new InvalidKeyException("Wrong format: RAW bytes needed");
}
byte[] rawKey = key.getEncoded();
if (rawKey == null) {
throw new InvalidKeyException("RAW bytes missing");
}
if (!isKeySizeValid(rawKey.length)) {
throw new InvalidKeyException("Invalid DESede key length: " + rawKey.length + " bytes");
}
boolean isEncrypt = (opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE);
// if (isEncrypt && provider.isFIPS()) {
// throw new ProviderException("DESede encrypt is not supported in FIPS
// mode");
// }
try {
if (symmetricCipher == null) {
symmetricCipher = SymmetricCipher.getInstanceDESede(mode,
padding, provider, configAlgName);
}
if (isEncrypt) {
symmetricCipher.initCipherEncrypt(rawKey, iv);
} else {
symmetricCipher.initCipherDecrypt(rawKey, iv);
}
this.iv = iv;
this.encrypting = isEncrypt;
this.initialized = true;
} catch (Exception e) {
throw provider.providerException("Failed to init cipher", e);
}
}
@Override
protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
String modeUpperCase = mode.toUpperCase();
if (modeUpperCase.equals("ECB") || modeUpperCase.equals("CBC")/*
* || modeUpperCase.equals("OFB") ||
* modeUpperCase.equals("CFB")
*/) {
this.mode = modeUpperCase;
} else {
throw new NoSuchAlgorithmException("Cipher mode: " + mode + " not found");
}
}
@Override
protected void engineSetPadding(String padding) throws NoSuchPaddingException {
if (padding.equalsIgnoreCase("NoPadding")) {
this.padding = Padding.NoPadding;
} else if (padding.equalsIgnoreCase("PKCS5Padding")) {
this.padding = Padding.PKCS5Padding;
} else {
throw new NoSuchPaddingException("Padding: " + padding + " not implemented");
}
}
@Override
protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
checkCipherInitialized();
try {
byte[] output = new byte[engineGetOutputSize(inputLen)];
int outputLen = symmetricCipher.update(input, inputOffset, inputLen, output, 0);
if (outputLen < output.length) {
byte[] out = Arrays.copyOfRange(output, 0, outputLen);
if (!encrypting) {
Arrays.fill(output, 0, outputLen, (byte) 0x00);
}
return out;
} else {
return output;
}
} catch (Exception e) {
throw provider.providerException("Failure in engineUpdate", e);
}
}
@Override
protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output,
int outputOffset) throws ShortBufferException {
checkCipherInitialized();
try {
return symmetricCipher.update(input, inputOffset, inputLen, output, outputOffset);
} catch (ShortBufferException sbe) {
throw sbe;
} catch (Exception e) {
throw provider.providerException("Failure in engineDoFinal", e);
}
}
// see JCE spec
protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException {
checkCipherInitialized();
byte[] encoded = key.getEncoded();
if ((encoded == null) || (encoded.length == 0)) {
throw new InvalidKeyException("Could not obtain encoded key");
}
try {
return engineDoFinal(encoded, 0, encoded.length);
} catch (BadPaddingException e) {
// should not occur
throw new InvalidKeyException("Wrapping failed", e);
}
}
// see JCE spec
protected Key engineUnwrap(byte[] wrappedKey, String algorithm, int type)
throws InvalidKeyException, NoSuchAlgorithmException {
checkCipherInitialized();
try {
byte[] encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
return ConstructKeys.constructKey(provider, encoded, algorithm, type);
} catch (BadPaddingException e) {
// should not occur
throw new InvalidKeyException("Unwrapping failed", e);
} catch (IllegalBlockSizeException e) {
// should not occur, handled with length check above
throw new InvalidKeyException("Unwrapping failed", e);
}
}
private void checkCipherInitialized() throws IllegalStateException {
if (!this.initialized) {
throw new IllegalStateException("Cipher has not been initialized");
}
}
static final boolean isKeySizeValid(int len) {
return len == 24 ? true : false;
}
}