1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.crypto.cipher;
20
21 import org.apache.shiro.crypto.CryptoException;
22 import org.apache.shiro.lang.util.ByteSource;
23 import org.apache.shiro.lang.util.StringUtils;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import javax.crypto.CipherInputStream;
28 import javax.crypto.spec.IvParameterSpec;
29 import javax.crypto.spec.SecretKeySpec;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.security.Key;
34 import java.security.SecureRandom;
35 import java.security.spec.AlgorithmParameterSpec;
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 @SuppressWarnings("checkstyle:MethodCount")
71 public abstract class JcaCipherService implements CipherService {
72
73
74
75
76 private static final Logger LOGGER = LoggerFactory.getLogger(JcaCipherService.class);
77
78
79
80
81 private static final int DEFAULT_KEY_SIZE = 128;
82
83
84
85
86 private static final int DEFAULT_STREAMING_BUFFER_SIZE = 512;
87
88 private static final int BITS_PER_BYTE = 8;
89
90
91
92
93 private static final String RANDOM_NUM_GENERATOR_ALGORITHM_NAME = "SHA1PRNG";
94
95
96
97
98 private String algorithmName;
99
100
101
102
103 private int keySize;
104
105
106
107
108 private int streamingBufferSize;
109
110 private boolean generateInitializationVectors;
111 private int initializationVectorSize;
112
113
114 private SecureRandom secureRandom;
115
116
117
118
119
120
121
122
123
124
125
126
127 protected JcaCipherService(String algorithmName) {
128 if (!StringUtils.hasText(algorithmName)) {
129 throw new IllegalArgumentException("algorithmName argument cannot be null or empty.");
130 }
131 this.algorithmName = algorithmName;
132 this.keySize = DEFAULT_KEY_SIZE;
133
134 this.initializationVectorSize = DEFAULT_KEY_SIZE;
135 this.streamingBufferSize = DEFAULT_STREAMING_BUFFER_SIZE;
136 this.generateInitializationVectors = true;
137 }
138
139
140
141
142
143
144
145 public String getAlgorithmName() {
146 return algorithmName;
147 }
148
149
150
151
152
153
154 public int getKeySize() {
155 return keySize;
156 }
157
158
159
160
161
162
163 public void setKeySize(int keySize) {
164 this.keySize = keySize;
165 }
166
167 public boolean isGenerateInitializationVectors() {
168 return generateInitializationVectors;
169 }
170
171 public void setGenerateInitializationVectors(boolean generateInitializationVectors) {
172 this.generateInitializationVectors = generateInitializationVectors;
173 }
174
175
176
177
178
179
180 public int getInitializationVectorSize() {
181 return initializationVectorSize;
182 }
183
184
185
186
187
188
189
190
191
192 public void setInitializationVectorSize(int initializationVectorSize) throws IllegalArgumentException {
193 if (initializationVectorSize % BITS_PER_BYTE != 0) {
194 String msg = "Initialization vector sizes are specified in bits, but must be a multiple of 8 so they "
195 + "can be easily represented as a byte array.";
196 throw new IllegalArgumentException(msg);
197 }
198 this.initializationVectorSize = initializationVectorSize;
199 }
200
201 protected boolean isGenerateInitializationVectors(boolean streaming) {
202 return isGenerateInitializationVectors();
203 }
204
205
206
207
208
209
210
211
212
213
214
215 public int getStreamingBufferSize() {
216 return streamingBufferSize;
217 }
218
219
220
221
222
223
224
225
226
227
228
229 public void setStreamingBufferSize(int streamingBufferSize) {
230 this.streamingBufferSize = streamingBufferSize;
231 }
232
233
234
235
236
237
238
239
240 public SecureRandom getSecureRandom() {
241 return secureRandom;
242 }
243
244
245
246
247
248
249
250
251 public void setSecureRandom(SecureRandom secureRandom) {
252 this.secureRandom = secureRandom;
253 }
254
255 protected static SecureRandom getDefaultSecureRandom() {
256 try {
257 return java.security.SecureRandom.getInstance(RANDOM_NUM_GENERATOR_ALGORITHM_NAME);
258 } catch (java.security.NoSuchAlgorithmException e) {
259 LOGGER.debug("The SecureRandom SHA1PRNG algorithm is not available on the current platform. Using the "
260 + "platform's default SecureRandom algorithm.", e);
261 return new java.security.SecureRandom();
262 }
263 }
264
265 protected SecureRandom ensureSecureRandom() {
266 SecureRandom random = getSecureRandom();
267 if (random == null) {
268 random = getDefaultSecureRandom();
269 }
270 return random;
271 }
272
273
274
275
276
277
278
279
280
281
282
283 protected String getTransformationString(boolean streaming) {
284 return getAlgorithmName();
285 }
286
287 protected byte[] generateInitializationVector(boolean streaming) {
288 int size = getInitializationVectorSize();
289 if (size <= 0) {
290 String msg = "initializationVectorSize property must be greater than zero. This number is "
291 + "typically set in the " + CipherService.class.getSimpleName() + " subclass constructor. "
292 + "Also check your configuration to ensure that if you are setting a value, it is positive.";
293 throw new IllegalStateException(msg);
294 }
295 if (size % BITS_PER_BYTE != 0) {
296 String msg = "initializationVectorSize property must be a multiple of 8 to represent as a byte array.";
297 throw new IllegalStateException(msg);
298 }
299 int sizeInBytes = size / BITS_PER_BYTE;
300 byte[] ivBytes = new byte[sizeInBytes];
301 SecureRandom random = ensureSecureRandom();
302 random.nextBytes(ivBytes);
303 return ivBytes;
304 }
305
306 public ByteSource encrypt(byte[] plaintext, byte[] key) {
307 byte[] ivBytes = null;
308 boolean generate = isGenerateInitializationVectors(false);
309 if (generate) {
310 ivBytes = generateInitializationVector(false);
311 if (ivBytes == null || ivBytes.length == 0) {
312 throw new IllegalStateException("Initialization vector generation is enabled - generated vector "
313 + "cannot be null or empty.");
314 }
315 }
316 return encrypt(plaintext, key, ivBytes, generate);
317 }
318
319 private ByteSource encrypt(byte[] plaintext, byte[] key, byte[] iv, boolean prependIv) throws CryptoException {
320
321 final int mode = javax.crypto.Cipher.ENCRYPT_MODE;
322
323 byte[] output;
324
325 if (prependIv && iv != null && iv.length > 0) {
326
327 byte[] encrypted = crypt(plaintext, key, iv, mode);
328
329 output = new byte[iv.length + encrypted.length];
330
331
332
333
334 System.arraycopy(iv, 0, output, 0, iv.length);
335
336
337 System.arraycopy(encrypted, 0, output, iv.length, encrypted.length);
338 } else {
339 output = crypt(plaintext, key, iv, mode);
340 }
341
342 if (LOGGER.isTraceEnabled()) {
343 LOGGER.trace("Incoming plaintext of size " + (plaintext != null ? plaintext.length : 0) + ". Ciphertext "
344 + "byte array is size " + (output != null ? output.length : 0));
345 }
346
347 return ByteSource.Util.bytes(output);
348 }
349
350 public ByteSourceBroker decrypt(byte[] ciphertext, byte[] key) throws CryptoException {
351 return new SimpleByteSourceBroker(this, ciphertext, key);
352 }
353
354 ByteSource decryptInternal(byte[] ciphertext, byte[] key) throws CryptoException {
355
356 byte[] encrypted = ciphertext;
357
358
359 byte[] iv = null;
360
361 if (isGenerateInitializationVectors(false)) {
362 try {
363
364
365
366
367
368
369
370
371
372 int ivSize = getInitializationVectorSize();
373 int ivByteSize = ivSize / BITS_PER_BYTE;
374
375
376 iv = new byte[ivByteSize];
377 System.arraycopy(ciphertext, 0, iv, 0, ivByteSize);
378
379
380 int encryptedSize = ciphertext.length - ivByteSize;
381 encrypted = new byte[encryptedSize];
382 System.arraycopy(ciphertext, ivByteSize, encrypted, 0, encryptedSize);
383 } catch (Exception e) {
384 String msg = "Unable to correctly extract the Initialization Vector or ciphertext.";
385 throw new CryptoException(msg, e);
386 }
387 }
388
389 return decryptInternal(encrypted, key, iv);
390 }
391
392 private ByteSource decryptInternal(byte[] ciphertext, byte[] key, byte[] iv) throws CryptoException {
393 if (LOGGER.isTraceEnabled()) {
394 LOGGER.trace("Attempting to decrypt incoming byte array of length "
395 + (ciphertext != null ? ciphertext.length : 0));
396 }
397 byte[] decrypted = crypt(ciphertext, key, iv, javax.crypto.Cipher.DECRYPT_MODE);
398 return decrypted == null ? null : ByteSource.Util.bytes(decrypted);
399 }
400
401
402
403
404
405
406
407
408
409
410
411
412 private javax.crypto.Cipher newCipherInstance(boolean streaming) throws CryptoException {
413 String transformationString = getTransformationString(streaming);
414 try {
415 return javax.crypto.Cipher.getInstance(transformationString);
416 } catch (Exception e) {
417 String msg = "Unable to acquire a Java JCA Cipher instance using "
418 + javax.crypto.Cipher.class.getName() + ".getInstance( \"" + transformationString + "\" ). "
419 + getAlgorithmName() + " under this configuration is required for the "
420 + getClass().getName() + " instance to function.";
421 throw new CryptoException(msg, e);
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 private byte[] crypt(byte[] bytes, byte[] key, byte[] iv, int mode) throws IllegalArgumentException, CryptoException {
448 if (key == null || key.length == 0) {
449 throw new IllegalArgumentException("key argument cannot be null or empty.");
450 }
451 javax.crypto.Cipher cipher = initNewCipher(mode, key, iv, false);
452 return crypt(cipher, bytes);
453 }
454
455
456
457
458
459
460
461
462
463
464 private byte[] crypt(javax.crypto.Cipher cipher, byte[] bytes) throws CryptoException {
465 try {
466 return cipher.doFinal(bytes);
467 } catch (Exception e) {
468 String msg = "Unable to execute 'doFinal' with cipher instance [" + cipher + "].";
469 throw new CryptoException(msg, e);
470 }
471 }
472
473
474
475
476
477
478
479
480
481
482
483
484 private void init(javax.crypto.Cipher cipher, int mode, java.security.Key key,
485 AlgorithmParameterSpec spec, SecureRandom random) throws CryptoException {
486 try {
487 if (random != null) {
488 if (spec != null) {
489 cipher.init(mode, key, spec, random);
490 } else {
491 cipher.init(mode, key, random);
492 }
493 } else {
494 if (spec != null) {
495 cipher.init(mode, key, spec);
496 } else {
497 cipher.init(mode, key);
498 }
499 }
500 } catch (Exception e) {
501 String msg = "Unable to init cipher instance.";
502 throw new CryptoException(msg, e);
503 }
504 }
505
506
507 public void encrypt(InputStream in, OutputStream out, byte[] key) throws CryptoException {
508 byte[] iv = null;
509 boolean generate = isGenerateInitializationVectors(true);
510 if (generate) {
511 iv = generateInitializationVector(true);
512 if (iv == null || iv.length == 0) {
513 throw new IllegalStateException("Initialization vector generation is enabled - generated vector "
514 + "cannot be null or empty.");
515 }
516 }
517 encrypt(in, out, key, iv, generate);
518 }
519
520 private void encrypt(InputStream in, OutputStream out, byte[] key, byte[] iv, boolean prependIv) throws CryptoException {
521 if (prependIv && iv != null && iv.length > 0) {
522 try {
523
524 out.write(iv);
525 } catch (IOException e) {
526 throw new CryptoException(e);
527 }
528 }
529
530 crypt(in, out, key, iv, javax.crypto.Cipher.ENCRYPT_MODE);
531 }
532
533 public void decrypt(InputStream in, OutputStream out, byte[] key) throws CryptoException {
534 decrypt(in, out, key, isGenerateInitializationVectors(true));
535 }
536
537 private void decrypt(InputStream in, OutputStream out, byte[] key, boolean ivPrepended) throws CryptoException {
538
539 byte[] iv = null;
540
541 if (ivPrepended) {
542
543
544 int ivSize = getInitializationVectorSize();
545 int ivByteSize = ivSize / BITS_PER_BYTE;
546 iv = new byte[ivByteSize];
547 int read;
548
549 try {
550 read = in.read(iv);
551 } catch (IOException e) {
552 String msg = "Unable to correctly read the Initialization Vector from the input stream.";
553 throw new CryptoException(msg, e);
554 }
555
556 if (read != ivByteSize) {
557 throw new CryptoException("Unable to read initialization vector bytes from the InputStream. "
558 + "This is required when initialization vectors are autogenerated during an encryption operation.");
559 }
560 }
561
562 decrypt(in, out, key, iv);
563 }
564
565 private void decrypt(InputStream in, OutputStream out, byte[] decryptionKey, byte[] iv) throws CryptoException {
566 crypt(in, out, decryptionKey, iv, javax.crypto.Cipher.DECRYPT_MODE);
567 }
568
569 private void crypt(InputStream in, OutputStream out, byte[] keyBytes, byte[] iv, int cryptMode) throws CryptoException {
570 if (in == null) {
571 throw new NullPointerException("InputStream argument cannot be null.");
572 }
573 if (out == null) {
574 throw new NullPointerException("OutputStream argument cannot be null.");
575 }
576
577 javax.crypto.Cipher cipher = initNewCipher(cryptMode, keyBytes, iv, true);
578
579 CipherInputStream cis = new CipherInputStream(in, cipher);
580
581 int bufSize = getStreamingBufferSize();
582 byte[] buffer = new byte[bufSize];
583
584 int bytesRead;
585 try {
586 while ((bytesRead = cis.read(buffer)) != -1) {
587 out.write(buffer, 0, bytesRead);
588 }
589 } catch (IOException e) {
590 throw new CryptoException(e);
591 }
592 }
593
594 private javax.crypto.Cipher initNewCipher(int jcaCipherMode, byte[] key, byte[] iv, boolean streaming)
595 throws CryptoException {
596
597 javax.crypto.Cipher cipher = newCipherInstance(streaming);
598 java.security.Key jdkKey = new SecretKeySpec(key, getAlgorithmName());
599 AlgorithmParameterSpec ivSpec = null;
600
601 if (iv != null && iv.length > 0) {
602 ivSpec = createParameterSpec(iv, streaming);
603 }
604
605 init(cipher, jcaCipherMode, jdkKey, ivSpec, getSecureRandom());
606
607 return cipher;
608 }
609
610 protected AlgorithmParameterSpec createParameterSpec(byte[] iv, boolean streaming) {
611 return new IvParameterSpec(iv);
612 }
613 }