-
Notifications
You must be signed in to change notification settings - Fork 94
/
OpenSslJnaCipher.java
379 lines (350 loc) · 17.1 KB
/
OpenSslJnaCipher.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.crypto.jna;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Objects;
import java.util.Properties;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.crypto.cipher.CryptoCipher;
import org.apache.commons.crypto.cipher.CryptoCipherFactory;
import org.apache.commons.crypto.utils.Transformation;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.PointerByReference;
/**
* Implements the CryptoCipher using JNA into OpenSSL.
*/
final class OpenSslJnaCipher implements CryptoCipher {
private static final int AES_128_ENCODED_KEYLEN = 16;
private static final int AES_192_ENCODED_KEYLEN = 24;
private static final int AES_256_ENCODED_KEYLEN = 32;
private static final int IV_LENGTH = 16;
/**
* AlgorithmMode of JNA. Currently only support AES/CTR/NoPadding.
*/
private enum AlgorithmMode {
AES_CTR, AES_CBC;
/**
* Gets the AlgorithmMode instance.
*
* @param algorithm the algorithm name
* @param mode the mode name
* @return the AlgorithmMode instance
* @throws NoSuchAlgorithmException if the algorithm is not support
*/
static AlgorithmMode get(final String algorithm, final String mode) throws NoSuchAlgorithmException {
try {
return AlgorithmMode.valueOf(algorithm + "_" + mode);
} catch (final Exception e) {
throw new NoSuchAlgorithmException("Algorithm not supported: " + algorithm + " and mode: " + mode);
}
}
}
private PointerByReference algo;
private final PointerByReference context;
private final AlgorithmMode algorithmMode;
private final int padding;
private final String transformation;
/**
* Constructs a {@link CryptoCipher} using JNA into OpenSSL
*
* @param props properties for OpenSSL cipher
* @param transformation transformation for OpenSSL cipher
* @throws GeneralSecurityException if OpenSSL cipher initialize failed
*/
public OpenSslJnaCipher(final Properties props, final String transformation) // NOPMD
throws GeneralSecurityException {
if (!OpenSslJna.isEnabled()) {
throw new GeneralSecurityException("Could not enable JNA access", OpenSslJna.initialisationError());
}
this.transformation = transformation;
final Transformation transform = Transformation.parse(transformation);
algorithmMode = AlgorithmMode.get(transform.getAlgorithm(), transform.getMode());
if (algorithmMode != AlgorithmMode.AES_CBC && algorithmMode != AlgorithmMode.AES_CTR) {
throw new GeneralSecurityException("Unknown algorithm " + transform.getAlgorithm() + "_" + transform.getMode());
}
padding = transform.getPadding().ordinal();
context = OpenSslNativeJna.EVP_CIPHER_CTX_new();
}
/**
* Closes the OpenSSL cipher. Clean the OpenSsl native context.
*/
@Override
public void close() {
if (context != null) {
OpenSslNativeJna.EVP_CIPHER_CTX_cleanup(context);
// Freeing the context multiple times causes a JVM crash
// A work-round is to only free it at finalize time
// TODO is that sufficient?
// OpenSslNativeJna.EVP_CIPHER_CTX_free(context);
}
}
/**
* Encrypts or decrypts data in a single-part operation, or finishes a
* multiple-part operation.
*
* @param input the input byte array
* @param inputOffset the offset in input where the input starts
* @param inputLen the input length
* @param output the byte array for the result
* @param outputOffset the offset in output where the result is stored
* @return the number of bytes stored in output
* @throws ShortBufferException if the given output byte array is too small
* to hold the result
* @throws 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
* @throws 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; or if this
* encryption algorithm is unable to process
* the input data provided.
*/
@Override
public int doFinal(final byte[] input, final int inputOffset, final int inputLen, final byte[] output,
final int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
final ByteBuffer outputBuf = ByteBuffer.wrap(output, outputOffset, output.length - outputOffset);
final ByteBuffer inputBuf = ByteBuffer.wrap(input, inputOffset, inputLen);
return doFinal(inputBuf, outputBuf);
}
/**
* 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.
*
* @param inBuffer the input ByteBuffer
* @param outBuffer the output ByteBuffer
* @return int number of bytes stored in {@code output}
* @throws 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
* @throws 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; or if this
* encryption algorithm is unable to process
* the input data provided.
* @throws ShortBufferException if the given output buffer is too small to
* hold the result
*/
@Override
public int doFinal(final ByteBuffer inBuffer, final ByteBuffer outBuffer)
throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
final int uptLen = update(inBuffer, outBuffer);
final int[] outlen = new int[1];
throwOnError(OpenSslNativeJna.EVP_CipherFinal_ex(context, outBuffer, outlen));
final int len = uptLen + outlen[0];
outBuffer.position(outBuffer.position() + outlen[0]);
return len;
}
@Override
protected void finalize() throws Throwable {
OpenSslNativeJna.EVP_CIPHER_CTX_free(context);
super.finalize();
}
@Override
public String getAlgorithm() {
return transformation;
}
@Override
public int getBlockSize() {
return CryptoCipherFactory.AES_BLOCK_SIZE;
}
/**
* Initializes the cipher with mode, key and iv.
*
* @param mode {@link Cipher#ENCRYPT_MODE} or {@link Cipher#DECRYPT_MODE}
* @param key crypto key for the cipher
* @param params the algorithm parameters
* @throws InvalidKeyException If key length is invalid
* @throws InvalidAlgorithmParameterException if IV length is wrong
*/
@Override
public void init(final int mode, final Key key, final AlgorithmParameterSpec params)
throws InvalidKeyException, InvalidAlgorithmParameterException {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(params, "params");
final int cipherMode = mode == Cipher.ENCRYPT_MODE ? OpenSslNativeJna.OOSL_JNA_ENCRYPT_MODE : OpenSslNativeJna.OOSL_JNA_DECRYPT_MODE;
if (!(params instanceof IvParameterSpec)) {
// other AlgorithmParameterSpec such as GCMParameterSpec is not
// supported now.
throw new InvalidAlgorithmParameterException("Illegal parameters");
}
final byte[] iv = ((IvParameterSpec) params).getIV();
if ((algorithmMode == AlgorithmMode.AES_CBC || algorithmMode == AlgorithmMode.AES_CTR) && iv.length != IV_LENGTH) {
throw new InvalidAlgorithmParameterException("Wrong IV length: must be 16 bytes long");
}
final int keyEncodedLength = key.getEncoded().length;
if (algorithmMode == AlgorithmMode.AES_CBC) {
switch (keyEncodedLength) {
case AES_128_ENCODED_KEYLEN:
algo = OpenSslNativeJna.EVP_aes_128_cbc();
break;
case AES_192_ENCODED_KEYLEN:
algo = OpenSslNativeJna.EVP_aes_192_cbc();
break;
case AES_256_ENCODED_KEYLEN:
algo = OpenSslNativeJna.EVP_aes_256_cbc();
break;
default:
throw new InvalidKeyException("keysize unsupported (" + keyEncodedLength + ")");
}
} else {
switch (keyEncodedLength) {
case AES_128_ENCODED_KEYLEN:
algo = OpenSslNativeJna.EVP_aes_128_ctr();
break;
case AES_192_ENCODED_KEYLEN:
algo = OpenSslNativeJna.EVP_aes_192_ctr();
break;
case AES_256_ENCODED_KEYLEN:
algo = OpenSslNativeJna.EVP_aes_256_ctr();
break;
default:
throw new InvalidKeyException("keysize unsupported (" + keyEncodedLength + ")");
}
}
throwOnError(OpenSslNativeJna.EVP_CipherInit_ex(context, algo, null, key.getEncoded(), iv, cipherMode));
throwOnError(OpenSslNativeJna.EVP_CIPHER_CTX_set_padding(context, padding));
}
/**
* @param retVal the result value of error.
*/
private void throwOnError(final int retVal) {
if (retVal != 1) {
final NativeLong err = OpenSslNativeJna.ERR_peek_error();
final String errdesc = OpenSslNativeJna.ERR_error_string(err, null);
if (context != null) {
OpenSslNativeJna.EVP_CIPHER_CTX_cleanup(context);
}
throw new IllegalStateException(
"return code " + retVal + " from OpenSSL. Err code is " + err + ": " + errdesc);
}
}
/**
* Continues a multiple-part encryption/decryption operation. The data is
* encrypted or decrypted, depending on how this cipher was initialized.
*
* @param input the input byte array
* @param inputOffset the offset in input where the input starts
* @param inputLen the input length
* @param output the byte array for the result
* @param outputOffset the offset in output where the result is stored
* @return the number of bytes stored in output
* @throws ShortBufferException if there is insufficient space in the output
* byte array
*/
@Override
public int update(final byte[] input, final int inputOffset, final int inputLen, final byte[] output,
final int outputOffset) throws ShortBufferException {
final ByteBuffer outputBuf = ByteBuffer.wrap(output, outputOffset, output.length - outputOffset);
final ByteBuffer inputBuf = ByteBuffer.wrap(input, inputOffset, inputLen);
return update(inputBuf, outputBuf);
}
/**
* Continues a multiple-part encryption/decryption operation. The data is
* encrypted or decrypted, depending on how this cipher was initialized.
*
* @param inBuffer the input ByteBuffer
* @param outBuffer the output ByteBuffer
* @return int number of bytes stored in {@code output}
* @throws ShortBufferException if there is insufficient space in the output
* buffer
*/
@Override
public int update(final ByteBuffer inBuffer, final ByteBuffer outBuffer) throws ShortBufferException {
final int[] outlen = new int[1];
throwOnError(OpenSslNativeJna.EVP_CipherUpdate(context, outBuffer, outlen, inBuffer, inBuffer.remaining()));
final int len = outlen[0];
inBuffer.position(inBuffer.limit());
outBuffer.position(outBuffer.position() + len);
return len;
}
/**
* Continues a multi-part update of the Additional Authentication Data (AAD).
* <p>
* Calls to this method provide AAD to the opensslEngine when operating in modes
* such as AEAD (GCM). If this opensslEngine is operating in either GCM mode,
* all AAD must be supplied before beginning operations on the ciphertext (via
* the {@code update} and {@code doFinal} methods).
* </p>
*
* @param aad the buffer containing the Additional Authentication Data
*
* @throws IllegalArgumentException if the {@code aad} byte array is {@code null}
* @throws IllegalStateException if this opensslEngine is in a wrong
* state (e.g., has not been initialized),
* does not accept AAD, or if operating in
* either GCM mode and one of the
* {@code update} methods has already been
* called for the active
* encryption/decryption operation
* @throws UnsupportedOperationException if the implementation
* {@code opensslEngine} doesn't support
* this operation.
*/
@Override
public void updateAAD(final byte[] aad)
throws IllegalArgumentException, IllegalStateException, UnsupportedOperationException {
// TODO: implement GCM mode using Jna
throw new UnsupportedOperationException("This is unsupported in Jna Cipher");
}
/**
* Continues a multi-part update of the Additional Authentication Data (AAD).
* <p>
* Calls to this method provide AAD to the opensslEngine when operating in modes
* such as AEAD (GCM). If this opensslEngine is operating in either GCM mode,
* all AAD must be supplied before beginning operations on the ciphertext (via
* the {@code update} and {@code doFinal} methods).
* </p>
*
* @param aad the buffer containing the Additional Authentication Data
*
* @throws IllegalArgumentException if the {@code aad} byte array is {@code null}
* @throws IllegalStateException if this opensslEngine is in a wrong
* state (e.g., has not been initialized),
* does not accept AAD, or if operating in
* either GCM mode and one of the
* {@code update} methods has already been
* called for the active
* encryption/decryption operation
* @throws UnsupportedOperationException if the implementation
* {@code opensslEngine} doesn't support
* this operation.
*/
@Override
public void updateAAD(final ByteBuffer aad)
throws IllegalArgumentException, IllegalStateException, UnsupportedOperationException {
// TODO: implement GCM mode using Jna
throw new UnsupportedOperationException("This is unsupported in Jna Cipher");
}
}