Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-aarch32-jdk8u
Path: blob/jdk8u272-b10-aarch32-20201026/jdk/src/share/classes/sun/security/rsa/RSAPadding.java
83409 views
1
/*
2
* Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.rsa;
27
28
import java.util.*;
29
30
import java.security.*;
31
import java.security.spec.*;
32
33
import javax.crypto.BadPaddingException;
34
import javax.crypto.spec.PSource;
35
import javax.crypto.spec.OAEPParameterSpec;
36
37
import sun.security.jca.JCAUtil;
38
39
/**
40
* RSA padding and unpadding.
41
*
42
* The various PKCS#1 versions can be found in the IETF RFCs
43
* tracking the corresponding PKCS#1 standards.
44
*
45
* RFC 2313: PKCS#1 v1.5
46
* RFC 2437: PKCS#1 v2.0
47
* RFC 3447: PKCS#1 v2.1
48
* RFC 8017: PKCS#1 v2.2
49
*
50
* The format of PKCS#1 v1.5 padding is:
51
*
52
* 0x00 | BT | PS...PS | 0x00 | data...data
53
*
54
* where BT is the blocktype (1 or 2). The length of the entire string
55
* must be the same as the size of the modulus (i.e. 128 byte for a 1024 bit
56
* key). Per spec, the padding string must be at least 8 bytes long. That
57
* leaves up to (length of key in bytes) - 11 bytes for the data.
58
*
59
* OAEP padding was introduced in PKCS#1 v2.0 and is a bit more complicated
60
* and has a number of options. We support:
61
*
62
* . arbitrary hash functions ('Hash' in the specification), MessageDigest
63
* implementation must be available
64
* . MGF1 as the mask generation function
65
* . the empty string as the default value for label L and whatever
66
* specified in javax.crypto.spec.OAEPParameterSpec
67
*
68
* The algorithms (representations) are forwards-compatible: that is,
69
* the algorithm described in previous releases are in later releases.
70
* However, additional comments/checks/clarifications were added to the
71
* later versions based on real-world experience (e.g. stricter v1.5
72
* format checking.)
73
*
74
* Note: RSA keys should be at least 512 bits long
75
*
76
* @since 1.5
77
* @author Andreas Sterbenz
78
*/
79
public final class RSAPadding {
80
81
// NOTE: the constants below are embedded in the JCE RSACipher class
82
// file. Do not change without coordinating the update
83
84
// PKCS#1 v1.5 padding, blocktype 1 (signing)
85
public final static int PAD_BLOCKTYPE_1 = 1;
86
// PKCS#1 v1.5 padding, blocktype 2 (encryption)
87
public final static int PAD_BLOCKTYPE_2 = 2;
88
// nopadding. Does not do anything, but allows simpler RSACipher code
89
public final static int PAD_NONE = 3;
90
// PKCS#1 v2.1 OAEP padding
91
public final static int PAD_OAEP_MGF1 = 4;
92
93
// type, one of PAD_*
94
private final int type;
95
96
// size of the padded block (i.e. size of the modulus)
97
private final int paddedSize;
98
99
// PRNG used to generate padding bytes (PAD_BLOCKTYPE_2, PAD_OAEP_MGF1)
100
private SecureRandom random;
101
102
// maximum size of the data
103
private final int maxDataSize;
104
105
// OAEP: main message digest
106
private MessageDigest md;
107
108
// OAEP: MGF1
109
private MGF1 mgf;
110
111
// OAEP: value of digest of data (user-supplied or zero-length) using md
112
private byte[] lHash;
113
114
/**
115
* Get a RSAPadding instance of the specified type.
116
* Keys used with this padding must be paddedSize bytes long.
117
*/
118
public static RSAPadding getInstance(int type, int paddedSize)
119
throws InvalidKeyException, InvalidAlgorithmParameterException {
120
return new RSAPadding(type, paddedSize, null, null);
121
}
122
123
/**
124
* Get a RSAPadding instance of the specified type.
125
* Keys used with this padding must be paddedSize bytes long.
126
*/
127
public static RSAPadding getInstance(int type, int paddedSize,
128
SecureRandom random) throws InvalidKeyException,
129
InvalidAlgorithmParameterException {
130
return new RSAPadding(type, paddedSize, random, null);
131
}
132
133
/**
134
* Get a RSAPadding instance of the specified type, which must be
135
* OAEP. Keys used with this padding must be paddedSize bytes long.
136
*/
137
public static RSAPadding getInstance(int type, int paddedSize,
138
SecureRandom random, OAEPParameterSpec spec)
139
throws InvalidKeyException, InvalidAlgorithmParameterException {
140
return new RSAPadding(type, paddedSize, random, spec);
141
}
142
143
// internal constructor
144
private RSAPadding(int type, int paddedSize, SecureRandom random,
145
OAEPParameterSpec spec) throws InvalidKeyException,
146
InvalidAlgorithmParameterException {
147
this.type = type;
148
this.paddedSize = paddedSize;
149
this.random = random;
150
if (paddedSize < 64) {
151
// sanity check, already verified in RSASignature/RSACipher
152
throw new InvalidKeyException("Padded size must be at least 64");
153
}
154
switch (type) {
155
case PAD_BLOCKTYPE_1:
156
case PAD_BLOCKTYPE_2:
157
maxDataSize = paddedSize - 11;
158
break;
159
case PAD_NONE:
160
maxDataSize = paddedSize;
161
break;
162
case PAD_OAEP_MGF1:
163
String mdName = "SHA-1";
164
String mgfMdName = mdName;
165
byte[] digestInput = null;
166
try {
167
if (spec != null) {
168
mdName = spec.getDigestAlgorithm();
169
String mgfName = spec.getMGFAlgorithm();
170
if (!mgfName.equalsIgnoreCase("MGF1")) {
171
throw new InvalidAlgorithmParameterException
172
("Unsupported MGF algo: " + mgfName);
173
}
174
mgfMdName = ((MGF1ParameterSpec)spec.getMGFParameters())
175
.getDigestAlgorithm();
176
PSource pSrc = spec.getPSource();
177
String pSrcAlgo = pSrc.getAlgorithm();
178
if (!pSrcAlgo.equalsIgnoreCase("PSpecified")) {
179
throw new InvalidAlgorithmParameterException
180
("Unsupported pSource algo: " + pSrcAlgo);
181
}
182
digestInput = ((PSource.PSpecified) pSrc).getValue();
183
}
184
md = MessageDigest.getInstance(mdName);
185
mgf = new MGF1(mgfMdName);
186
} catch (NoSuchAlgorithmException e) {
187
throw new InvalidKeyException("Digest not available", e);
188
}
189
lHash = getInitialHash(md, digestInput);
190
int digestLen = lHash.length;
191
maxDataSize = paddedSize - 2 - 2 * digestLen;
192
if (maxDataSize <= 0) {
193
throw new InvalidKeyException
194
("Key is too short for encryption using OAEPPadding" +
195
" with " + mdName + " and " + mgf.getName());
196
}
197
break;
198
default:
199
throw new InvalidKeyException("Invalid padding: " + type);
200
}
201
}
202
203
// cache of hashes of zero length data
204
private static final Map<String,byte[]> emptyHashes =
205
Collections.synchronizedMap(new HashMap<String,byte[]>());
206
207
/**
208
* Return the value of the digest using the specified message digest
209
* <code>md</code> and the digest input <code>digestInput</code>.
210
* if <code>digestInput</code> is null or 0-length, zero length
211
* is used to generate the initial digest.
212
* Note: the md object must be in reset state
213
*/
214
private static byte[] getInitialHash(MessageDigest md,
215
byte[] digestInput) {
216
byte[] result;
217
if ((digestInput == null) || (digestInput.length == 0)) {
218
String digestName = md.getAlgorithm();
219
result = emptyHashes.get(digestName);
220
if (result == null) {
221
result = md.digest();
222
emptyHashes.put(digestName, result);
223
}
224
} else {
225
result = md.digest(digestInput);
226
}
227
return result;
228
}
229
230
/**
231
* Return the maximum size of the plaintext data that can be processed
232
* using this object.
233
*/
234
public int getMaxDataSize() {
235
return maxDataSize;
236
}
237
238
/**
239
* Pad the data and return the padded block.
240
*/
241
public byte[] pad(byte[] data, int ofs, int len)
242
throws BadPaddingException {
243
return pad(RSACore.convert(data, ofs, len));
244
}
245
246
/**
247
* Pad the data and return the padded block.
248
*/
249
public byte[] pad(byte[] data) throws BadPaddingException {
250
if (data.length > maxDataSize) {
251
throw new BadPaddingException("Data must be shorter than "
252
+ (maxDataSize + 1) + " bytes but received "
253
+ data.length + " bytes.");
254
}
255
switch (type) {
256
case PAD_NONE:
257
return data;
258
case PAD_BLOCKTYPE_1:
259
case PAD_BLOCKTYPE_2:
260
return padV15(data);
261
case PAD_OAEP_MGF1:
262
return padOAEP(data);
263
default:
264
throw new AssertionError();
265
}
266
}
267
268
/**
269
* Unpad the padded block and return the data.
270
*/
271
public byte[] unpad(byte[] padded, int ofs, int len)
272
throws BadPaddingException {
273
return unpad(RSACore.convert(padded, ofs, len));
274
}
275
276
/**
277
* Unpad the padded block and return the data.
278
*/
279
public byte[] unpad(byte[] padded) throws BadPaddingException {
280
if (padded.length != paddedSize) {
281
throw new BadPaddingException("Decryption error." +
282
"The padded array length (" + padded.length +
283
") is not the specified padded size (" + paddedSize + ")");
284
}
285
switch (type) {
286
case PAD_NONE:
287
return padded;
288
case PAD_BLOCKTYPE_1:
289
case PAD_BLOCKTYPE_2:
290
return unpadV15(padded);
291
case PAD_OAEP_MGF1:
292
return unpadOAEP(padded);
293
default:
294
throw new AssertionError();
295
}
296
}
297
298
/**
299
* PKCS#1 v1.5 padding (blocktype 1 and 2).
300
*/
301
private byte[] padV15(byte[] data) throws BadPaddingException {
302
byte[] padded = new byte[paddedSize];
303
System.arraycopy(data, 0, padded, paddedSize - data.length,
304
data.length);
305
int psSize = paddedSize - 3 - data.length;
306
int k = 0;
307
padded[k++] = 0;
308
padded[k++] = (byte)type;
309
if (type == PAD_BLOCKTYPE_1) {
310
// blocktype 1: all padding bytes are 0xff
311
while (psSize-- > 0) {
312
padded[k++] = (byte)0xff;
313
}
314
} else {
315
// blocktype 2: padding bytes are random non-zero bytes
316
if (random == null) {
317
random = JCAUtil.getSecureRandom();
318
}
319
// generate non-zero padding bytes
320
// use a buffer to reduce calls to SecureRandom
321
byte[] r = new byte[64];
322
int i = -1;
323
while (psSize-- > 0) {
324
int b;
325
do {
326
if (i < 0) {
327
random.nextBytes(r);
328
i = r.length - 1;
329
}
330
b = r[i--] & 0xff;
331
} while (b == 0);
332
padded[k++] = (byte)b;
333
}
334
}
335
return padded;
336
}
337
338
/**
339
* PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)).
340
*
341
* Note that we want to make it a constant-time operation
342
*/
343
private byte[] unpadV15(byte[] padded) throws BadPaddingException {
344
int k = 0;
345
boolean bp = false;
346
347
if (padded[k++] != 0) {
348
bp = true;
349
}
350
if (padded[k++] != type) {
351
bp = true;
352
}
353
int p = 0;
354
while (k < padded.length) {
355
int b = padded[k++] & 0xff;
356
if ((b == 0) && (p == 0)) {
357
p = k;
358
}
359
if ((k == padded.length) && (p == 0)) {
360
bp = true;
361
}
362
if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) &&
363
(p == 0)) {
364
bp = true;
365
}
366
}
367
int n = padded.length - p;
368
if (n > maxDataSize) {
369
bp = true;
370
}
371
372
// copy useless padding array for a constant-time method
373
byte[] padding = new byte[p];
374
System.arraycopy(padded, 0, padding, 0, p);
375
376
byte[] data = new byte[n];
377
System.arraycopy(padded, p, data, 0, n);
378
379
BadPaddingException bpe = new BadPaddingException("Decryption error");
380
381
if (bp) {
382
throw bpe;
383
} else {
384
return data;
385
}
386
}
387
388
/**
389
* PKCS#1 v2.0 OAEP padding (MGF1).
390
* Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)
391
*/
392
private byte[] padOAEP(byte[] M) throws BadPaddingException {
393
if (random == null) {
394
random = JCAUtil.getSecureRandom();
395
}
396
int hLen = lHash.length;
397
398
// 2.d: generate a random octet string seed of length hLen
399
// if necessary
400
byte[] seed = new byte[hLen];
401
random.nextBytes(seed);
402
403
// buffer for encoded message EM
404
byte[] EM = new byte[paddedSize];
405
406
// start and length of seed (as index into EM)
407
int seedStart = 1;
408
int seedLen = hLen;
409
410
// copy seed into EM
411
System.arraycopy(seed, 0, EM, seedStart, seedLen);
412
413
// start and length of data block DB in EM
414
// we place it inside of EM to reduce copying
415
int dbStart = hLen + 1;
416
int dbLen = EM.length - dbStart;
417
418
// start of message M in EM
419
int mStart = paddedSize - M.length;
420
421
// build DB
422
// 2.b: Concatenate lHash, PS, a single octet with hexadecimal value
423
// 0x01, and the message M to form a data block DB of length
424
// k - hLen -1 octets as DB = lHash || PS || 0x01 || M
425
// (note that PS is all zeros)
426
System.arraycopy(lHash, 0, EM, dbStart, hLen);
427
EM[mStart - 1] = 1;
428
System.arraycopy(M, 0, EM, mStart, M.length);
429
430
// produce maskedDB
431
mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);
432
433
// produce maskSeed
434
mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);
435
436
return EM;
437
}
438
439
/**
440
* PKCS#1 v2.1 OAEP unpadding (MGF1).
441
*/
442
private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {
443
byte[] EM = padded;
444
boolean bp = false;
445
int hLen = lHash.length;
446
447
if (EM[0] != 0) {
448
bp = true;
449
}
450
451
int seedStart = 1;
452
int seedLen = hLen;
453
454
int dbStart = hLen + 1;
455
int dbLen = EM.length - dbStart;
456
457
mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);
458
mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);
459
460
// verify lHash == lHash'
461
for (int i = 0; i < hLen; i++) {
462
if (lHash[i] != EM[dbStart + i]) {
463
bp = true;
464
}
465
}
466
467
int padStart = dbStart + hLen;
468
int onePos = -1;
469
470
for (int i = padStart; i < EM.length; i++) {
471
int value = EM[i];
472
if (onePos == -1) {
473
if (value == 0x00) {
474
// continue;
475
} else if (value == 0x01) {
476
onePos = i;
477
} else { // Anything other than {0,1} is bad.
478
bp = true;
479
}
480
}
481
}
482
483
// We either ran off the rails or found something other than 0/1.
484
if (onePos == -1) {
485
bp = true;
486
onePos = EM.length - 1; // Don't inadvertently return any data.
487
}
488
489
int mStart = onePos + 1;
490
491
// copy useless padding array for a constant-time method
492
byte [] tmp = new byte[mStart - padStart];
493
System.arraycopy(EM, padStart, tmp, 0, tmp.length);
494
495
byte [] m = new byte[EM.length - mStart];
496
System.arraycopy(EM, mStart, m, 0, m.length);
497
498
BadPaddingException bpe = new BadPaddingException("Decryption error");
499
500
if (bp) {
501
throw bpe;
502
} else {
503
return m;
504
}
505
}
506
}
507
508