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
|
import java.io.*;
//import java.io.ByteArrayOutputStream;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Arrays;
public class HelloWorld
{
static String privateKey = "-----BEGIN PRIVATE KEY-----\n"
+ "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCucd9Bhz9lBGBU\n"
+ "Q2BPyufbSszdjfSxgPrB4/ua9tYkMhsM6NtWKVXhB8Mo9wEoTNNShAvcS/Xk/dxn\n"
+ "j+f3aMX1QHUys/Cf7AFfdz9B6LHRyaJrJEUiuZhpH3cohT/cZPWCfXMC8TkmM/WF\n"
+ "sJsUIg53J9j/KzamEYrREcZylxdh77Q6zpsloXmj0sVqvzy5L8HJYfttH/XNELzu\n"
+ "9ZEnBCi23Vo2Dt2Q6ZZO/MGJp1J2OAcaBBZ+B0i1E1c/MA2VNwuXx+v1Nc3SUyNy\n"
+ "bqM0zfNWoegTqssfAxOTsFclAiMIL96J9GJsqfl9IQzClgV7/anhwfTA3qEjpYLC\n"
+ "qxIyM0wVAgMBAAECggEACufBfjY3R1hjsUDZB4P2xKXDcuJJ9sLKak6XTxO5RWAA\n"
+ "gukXtSY2YS/8ClaOsvdCirkIiMgS4jLgkXTUmonpPjC+YuIO2+CEIXSx9qvWWfgR\n"
+ "+EK3M7mIhqHZ8CWMXXnOQ08WXou39+Rtp+LnfvW2E8rg7OrFqtIT7IgA8O7zHkMk\n"
+ "dBNUq5GO/nQ4GUmEbCb10Bs8Fb1Ibf4vUhAmgvpuS7oFfEcecoJmvU2x/UVTdWsL\n"
+ "1A+kzxvq0fShhmeMct1RJD1q33Ifv5C6Z3CgjHWJAjUaWR0+qTS61aS0u5Uh7FSl\n"
+ "zewiiDYueDhD6bQB22cCSzIi5yDDY9XtQl+bCncsjQKBgQDib39w0swSpNn6LzYz\n"
+ "Pm8LtTAo4ARFpHdZjR3+pOCtKHnBY89JHNxk1vTveY8lvMecqELSSLUhSYWgHVpw\n"
+ "3bWB1NXS7+ACIrSD0x93Qv9mJ9ZCUW8r4HcZ9Eo+z52Anoe6VOqg83uIgPGCLcvJ\n"
+ "nxXFOlwW1MGJUEHDnv5PsUHfJwKBgQDFOJvJmn1DgP1CHAEmnjhfKI/JnhS941Pi\n"
+ "terIHLq9t7vv6ASMin42bHGWxFfdEoLFWlssqr8xvPFpNiMqOA1A7pZs8kcJgLnu\n"
+ "Z7Il8M1Fx2BTk+UIQMWVX7Ftm3Jpdc4/qjNnmUEE7ITDIcKzXuHp48s2AmELSpc6\n"
+ "Zyq0ALYAYwKBgBOTlC8K6n3KJtZMcqEniq42cf12sKfcujzRyIAVfR87Wptvp6Io\n"
+ "jp1hQDfcCJY4pgFTQsOvaYmBM75OC12qrWCWKA5ekr1chsLG4/eJoU8RrqJ5K+Vd\n"
+ "OK7Twf+AL5vJGO7xHH/hzRJWI4sfrni1+knc681Fg539hFIHUvFM3+cNAoGAQmBY\n"
+ "BlUpfZOnKR3VwVKU9GnpYtkCcBpXfEDvwOPycbGp3gd/qHFgIx8CZ9SzIaN+Qb+0\n"
+ "WecprCrEMT3YPfhZdZYXKJmuEOOzMCrUSXKvE6ITqG1pMwrhtPFc/N/JdPcCMGkv\n"
+ "Hdn1iRu1Xxs4tTfk3twc45OPZ8Z1+WEJfUWT+7MCgYAYfHXHVF5U9XLsvCQz4z37\n"
+ "FkIVtrYjQ6D2329+YTO+axlfRB8v0EHsPIeMQcWFxIOybNWFu5kFJmWB8T1ycqk/\n"
+ "p9i04GoW44woZfzP8FWFw5B8wTXn9yqq3RVm2f5bsUGHv/32cPuGmi1aG2kNGJb0\n"
+ "LoLK4I5s6vHfBZ+wahqiTQ==\n"
+ "-----END PRIVATE KEY-----";
static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArnHfQYc/ZQRgVENgT8rn\n"
+ "20rM3Y30sYD6weP7mvbWJDIbDOjbVilV4QfDKPcBKEzTUoQL3Ev15P3cZ4/n92jF\n"
+ "9UB1MrPwn+wBX3c/Qeix0cmiayRFIrmYaR93KIU/3GT1gn1zAvE5JjP1hbCbFCIO\n"
+ "dyfY/ys2phGK0RHGcpcXYe+0Os6bJaF5o9LFar88uS/ByWH7bR/1zRC87vWRJwQo\n"
+ "tt1aNg7dkOmWTvzBiadSdjgHGgQWfgdItRNXPzANlTcLl8fr9TXN0lMjcm6jNM3z\n"
+ "VqHoE6rLHwMTk7BXJQIjCC/eifRibKn5fSEMwpYFe/2p4cH0wN6hI6WCwqsSMjNM\n"
+ "FQIDAQAB";
/**
* RSA加密解密测试示例
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
System.out.println("Hello World!");
// Read in the key into a String
StringBuilder pkcs8Lines = new StringBuilder();
BufferedReader rdr = new BufferedReader(new StringReader(privateKey));
String line;
while ((line = rdr.readLine()) != null) {
pkcs8Lines.append(line);
}
// Remove the "BEGIN" and "END" lines, as well as any whitespace
String pkcs8Pem = pkcs8Lines.toString();
pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
pkcs8Pem = pkcs8Pem.replaceAll("\\s+","");
System.out.println("pkcs8Pem:" + pkcs8Pem);
// Base64 decode the result
// byte[] pkcs8EncodedBytes = Base64.decode(pkcs8Pem, Base64.DEFAULT);
byte [] pkcs8EncodedBytes = decode(pkcs8Pem);
System.out.println("pkcs8EncodedBytes byte:" + Arrays.toString(pkcs8EncodedBytes));
System.out.println("pkcs8Pem byte:" + Arrays.toString(pkcs8Pem.getBytes()));
// extract the private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
System.out.println(privKey);
String param = "{\"name\":\"aa\"}";
String p1 = encode(param.getBytes());
System.out.println("p1:" + p1);
byte[] p2 = decode(p1);
System.out.println("p2:" + Arrays.toString(p2));
String encryptData = encryptForPrivateKey(param, pkcs8Pem);
System.out.println("加密后内容:" + encryptData);
String publicKey2 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv651nntK13ezxNPnQ5s7\n"
+ "8nwRK45rg28tvhMr9rt6HNrS1bhKEtysx+p4jKuA1BHBHWWSA5SlRlruS1zZIpgy\n"
+ "p5u8uqhAALp3yBa0Yw/XcyBe2zuY5mfCCL3ftKw3o9rzFsG6obnwLXnGQyKMPmxP\n"
+ "/pIeZHkIUMo/EjI5ExKG+dMQn1Fp6wo/+zbnZIk1ewQH4E0+iPyWa2nn2RBPFiYS\n"
+ "QPPvsypfkE46z0VG7eqAxqrUSzm26qhYgv+lqIn/Zqq/ZnTJO+2SDI8GsbEaqXiF\n"
+ "QRrWZrDcU92s76rwlIHUBlEqRKNXc+BcfWwEx4giEk87GPC9QHxjLgwzEeNXjih2\n"
+ "jwIDAQAB";
// String encryptData2 = "bl7TWxqWq17amPInw5gLEcNds5G3v2Gm8MNeRBniliTiPyUjMCZwbtiJK9/M423OOqYU3e+Kk3wROyk2K/5WSmgkfdaLWBgpRKWDO/x8H9Sg/5QsBnMCrosM/MFK9ayyJiuE5nM6PU3qCGZ+/v0nR0RagUo9Eqxx6g8ZQWMXBtCEd1yyGpnRzxmvbX77HYYs26gKKDduvbwhxjwEDBzByxZrhLQ03wBSJATRNevGEimlMK4ev+JVk0lqCz4Y0M28eskrvcT2246+OB4M/tElt4gGD/MTtFUAjJ/pKnyX/dRL/iIQzU6afxr3+QDBK7VHyNr3LrPJNXUeYNYwyJWrpw==";
String encryptData2 = "Wzfl/uB/7cXPkRjLJ/guruu9NytzdT+9dM3dsMAOYHLdBEcEPBsDkNICEmTlM7ubkGmNE6rxeZ/20SpaSWEY89zahoAb7GMu1ceGPbJZrb5F26BfMHsA+CK5Y6MLtbl/ssaq/r9U0xB/DJeDJrOUs8hO8YPgGxeOtzMuJhHT4BVh4Td1SBA9hSJOWkMZCkwGP6RaSl4eunggk1Kmuu5rxEOIv9B7TWCIRpuy2AwtLwRCIbZjIilVVFMTzpuUySKWlcl5qD/OdYKfidDtXvIam2J9JoH3TddUKSsbcPDsb0AC8BR8a9CRC72jGCvftxqUIwWMWTZgqViEWeEcSTK/gw==";
String decryptData = decryptForPublicKey(encryptData2, publicKey2);
System.out.println("解密后内容:" + decryptData);
String rSignData = "NZQrkpicy7wGx1fWu+8KhU5fWfI3oTAa6Deg0/GEDVcOwpwpoybLRdI4NCM7I8mLSNh/KI+d62gqcWnT399XQCGiesZlSR7ux7TM/aQe+RqLIvPNWcfcxyEGmDZxDgvnjTP5qzJYaQKC9DK4w2SelwDab7nhvV30uV24kQeBJGjGrsT2xZVPnWcsc8UaV+QUpajmV70QdYilDVn9RYht891Uwqm5twqcYej3ba9ZBE16cmaNGeveegXvwkGK6akmXR9covoLMqDUvq0HE1Mr2S43nMisF/vw2uQxgRq+Dr44OBbPMY9qICnd99B7csv498CfZLMRf/4+92TPUClnbw==";
// RSA验签
boolean result = doCheck(decryptData, rSignData, publicKey2, "UTF-8");
System.out.print("验签结果:" + result);
}
/**
* RSA验签名检查
* @param content 待签名数据
* @param sign 签名值
* @param publicKey 分配给开发商公钥
* @param encode 字符集编码
* @return 布尔值
*/
public static boolean doCheck(String content, String sign, String publicKey,String encode)
{
try
{
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
byte[] encodedKey = decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature
.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update( content.getBytes(encode) );
boolean bverify = signature.verify( decode(sign) );
System.out.print("验签结果-----:" + bverify);
return bverify;
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
/**
* 签名算法
*/
public static final String SIGN_ALGORITHMS = "SHA256WithRSA";
/**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 245;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 256;
/**
* 私钥加密
* @param privateKeyStr 私钥
* @param data 加密字符串
* @return String 密文数据
* @throws Exception
*/
public static String encryptForPrivateKey(String data, String privateKeyStr) throws Exception{
byte[] decryptedData = encryptByPrivateKey(data.getBytes(), privateKeyStr);
// return Base64.encode(decryptedData);
// return Base64.getEncoder().encodeToString(decryptedData);
return encode(decryptedData);
}
/**
* <p>
* 私钥加密
* </p>
*
* @param data
* 源数�?
* @param privateKey
* 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
System.out.println("privateKey:" + privateKey);
// byte[] keyBytes = Base64.decode(privateKey);
// byte[] keyBytes = Base64.getDecoder().decode(privateKey);
// byte[] keyBytes = privateKey.getBytes();
// System.out.println("privateKey byte:" + Arrays.toString(keyBytes));
byte [] pkcs8EncodedBytes = decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
// KeyFactory kf = KeyFactory.getInstance("RSA");
// PrivateKey privKey = kf.generatePrivate(keySpec);
// System.out.println(privKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
System.out.println("---" + privateK);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
System.out.println("en inputLen:" + inputLen + "---" + MAX_ENCRYPT_BLOCK);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
System.out.println("----:" + inputLen + "===" + offSet + " i " + i);
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* 公钥解密方法
* @param publicKey
* @param plainTextData 密文
* @return 明文
* @throws Exception
*/
public static String decryptForPublicKey(String plainTextData, String publicKey) throws Exception{
byte[] decryptedData = decryptByPublicKey(decode(plainTextData), publicKey);
return new String(decryptedData);
}
/**
* <p>
* 公钥解密
* </p>
*
* @param encryptedData
* 已加密数据
* @param publicKey
* 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
byte[] keyBytes = decode(publicKey);
System.out.println("kkk----:" + keyBytes.length);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
System.out.println("inputLen:" + inputLen);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
System.out.println("de ----:" + inputLen + "===" + offSet + " i " + i);
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
// 标准 base64
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static
{
for (int i = 0; i < BASELENGTH; ++i)
{
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--)
{
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--)
{
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--)
{
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++)
{
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++)
{
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++)
{
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect)
{
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect)
{
return (octect == PAD);
}
private static boolean isData(char octect)
{
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData)
{
if (binaryData == null)
{
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0)
{
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
: numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug)
{
System.out.println("number of triplets = " + numberTriplets);
}
for (int i = 0; i < numberTriplets; i++)
{
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug)
{
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
}
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
if (fDebug)
{
System.out.println("val2 = " + val2);
System.out.println("k4 = " + (k << 4));
System.out.println("vak = " + (val2 | (k << 4)));
}
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT)
{
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug)
{
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1 >> 2));
}
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT)
{
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded
* string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded)
{
if (encoded == null)
{
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0)
{
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0)
{
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++)
{
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++])))
{
return null;
}// if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++])))
{
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4)))
{// Check if they are PAD characters
if (isPad(d3) && isPad(d4))
{
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
}
else if (!isPad(d3) && isPad(d4))
{
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
}
else
{
return null;
}
}
else
{ // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data)
{
if (data == null)
{
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++)
{
if (!isWhiteSpace(data[i]))
{
data[newSize++] = data[i];
}
}
return newSize;
}
}
|