golang RSA 私钥加密公钥解密,及和 Java 实现互通。

在golang中使用RSA算法时,一般都是公钥加密,私钥解密,这是一个常见的场景。但是在实际使用中,

往往需要和其他项目进行交互,其他项目实现就不一定是按标准使用的,比如Java、PHP中就比较常见,

经常有项目用私钥加密,公钥解密,实现参考Java使用RSA加密解密及签名校验,甚至直接就拿来就用,

这个时候就需要了解在golang中如何实现公钥加密,私钥解密。

下面是golang的公钥加密,私钥解密示例,实现和java的互通。

RSA 加密与解密

RSA 加密算法是一种非对称加密算法,在许多项目中广泛使用,是当前数据安全加密中最常用的算法之一。在 Go 语言中,RSA 的加密、解密、签名与验签主要通过 crypto/x509crypto/rsa 两个包的方法来实现。

RSA 通过生成一对公钥和私钥来进行加密和解密,公钥与私钥是相互对应的。公钥可以用来加密数据,但不能用于解密;而私钥则可以解密由对应公钥加密的数据。公钥可以公开分发,而私钥需要妥善保管,只有拥有私钥的人才能解密通过公钥加密的信息。

正常使用时,一般使用公钥加密,私钥解密。但是某些场景下,需要使用私钥加密,公钥解密,比较常见的就是签名验证。

Java RSA 加密解密示例

参考Java使用RSA加密解密及签名校验

实现测试示例如下,RSA密钥生成都为2048位:

  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;
    }
}

运行查看结果

1
2
javac HelloWorld.java
java HelloWorld

golang 实现私钥加密、公钥解密

参考Golang RSA 如何私钥加密公钥解密

RSA密钥生成都为2048位。

公钥解密实现

对于 2048 位 (256 字节) 的 RSA 密钥,最大能加密的数据长度约为 245 字节 (因为 PKCS#1 v1.5 填充需要 11 字节)。

 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
// EncryptForPrivateKey 加密长消息,RSA最大加密明文大小256-11=245字节,这里对245字节进行分组加密
func EncryptForPrivateKey(data []byte, privKey []byte) (string, error) {
	block, _ := pem.Decode(privKey)
	if block == nil {
		return "", errors.New("private key error")
	}
	priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return "", err
	}

	rsaPrivateKey, ok := priv.(*rsa.PrivateKey)
	if !ok {
		return "", errors.New("key is not an RSA private key")
	}
	publicKey := &rsaPrivateKey.PublicKey

	// RSA encryption with PKCS1v15 padding
	// The chunk size must be smaller than the key size - 11 bytes (for padding)
	maxEncryptBlock := publicKey.Size() - 11

	dataLen := len(data)
	var encryptedBytes bytes.Buffer

	for i := 0; i < dataLen; i += maxEncryptBlock {
		end := min(i+maxEncryptBlock, dataLen)

		chunk := data[i:end]
		encryptedChunk, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, crypto.Hash(0), chunk[:])
		if err != nil {
			return "", fmt.Errorf("encrypt chunk error: %v", err)
		}

		encryptedBytes.Write(encryptedChunk)
	}

	return base64.StdEncoding.EncodeToString(encryptedBytes.Bytes()), nil
}

Go 的 签名是采用的 PKCS #1 v1.5 padding 方式。

私钥签名常见是用在签名验证中,在签名验证中,是不需要解出明文,只需要验证签名是否正确,所以是有传入hash参数的,

如果想解出明文,只需要在加密时不传入hash参数即可,传crypto.Hash(0)则表示不进行任务hash处理。

1
encryptedChunk, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, crypto.Hash(0), chunk[:])

RSA签名、验签实现

 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
// 签名算法,对应java RSA.sign SHA256WithRSA
func RsaSign(origData []byte, privKey []byte) (string, error) {
	block, _ := pem.Decode(privKey)
	if block == nil {
		return "", errors.New("private key error")
	}
	priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return "", err
	}

	hashed := sha256.Sum256(origData) // 使用SHA-256哈希数据
	signature, err := rsa.SignPKCS1v15(rand.Reader, priv.(*rsa.PrivateKey), crypto.SHA256, hashed[:])
	if err != nil {
		return "", err
	}

	return base64.StdEncoding.EncodeToString(signature), err
}

// RsaVerifySignature 验证签名
func RsaVerifySignature(origData []byte, signData string, pubKey []byte) error {
	signDataBytes, err := base64.StdEncoding.DecodeString(signData)
	if err != nil {
		return err
	}

	block, _ := pem.Decode(pubKey)
	if block == nil {
		return errors.New("private key error")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return fmt.Errorf("parse public key error: %v", err)
	}

	publicKey, ok := pub.(*rsa.PublicKey)
	if !ok {
		return errors.New("key is not an RSA private key")
	}

	hashed := sha256.Sum256(origData) // 使用SHA-256哈希数据
	err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed[:], signDataBytes[:])
	return err
}

公钥解密实现:

 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
// DecryptForPublicKey 解密分块加密的长消息
func DecryptForPublicKey(encryptedData string, pubKey []byte) ([]byte, error) {
	encryptedDataBytes, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return nil, fmt.Errorf("base64 decode error: %v", err)
	}

	block, _ := pem.Decode(pubKey)
	if block == nil {
		return nil, errors.New("private key error")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, fmt.Errorf("parse public key error: %v", err)
	}

	publicKey, ok := pub.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New("key is not an RSA private key")
	}

	maxDecryptBlock := publicKey.Size()

	dataLen := len(encryptedDataBytes)
	var decryptedBytes bytes.Buffer

	for i := 0; i < dataLen; i += maxDecryptBlock {
		end := min(i+maxDecryptBlock, dataLen)

		chunk := encryptedDataBytes[i:end]
		decryptedChunk, err := publicKeyDecrypt(chunk[:], publicKey)
		if err != nil {
			return nil, fmt.Errorf("decrypt chunk error: %v", err)
		}

		decryptedBytes.Write(decryptedChunk[:])
	}

	return decryptedBytes.Bytes(), nil
}

func publicKeyDecrypt(encryptedData []byte, pubKey *rsa.PublicKey) ([]byte, error) {
	c := new(big.Int).SetBytes(encryptedData)
	if c.Cmp(pubKey.N) > 0 {
		return nil, errors.New("加密数据太大")
	}

	m := new(big.Int).Exp(c, big.NewInt(int64(pubKey.E)), pubKey.N)

	modulusSize := (pubKey.N.BitLen() + 7) / 8
	plaintext := make([]byte, modulusSize)
	mBytes := m.Bytes()
	copy(plaintext[modulusSize-len(mBytes):], mBytes)

	// 检查并移除PKCS#1 v1.5填充
	if len(plaintext) < 11 {
		return nil, errors.New("解密错误:数据太短")
	}

	fmt.Println("plaintext:", plaintext)
	// PKCS#1 v1.5填充格式: 0x00 0x02 [随机非零字节] 0x00 [原始数据]
	if plaintext[0] != 0x00 || plaintext[1] != 0x02 {
		return nil, errors.New("解密错误:无效的填充格式")
	}

	// 查找分隔符0x00
	separator := bytes.IndexByte(plaintext[2:], 0x00)
	if separator == -1 {
		return nil, errors.New("解密错误:找不到填充分隔符")
	}

	// 返回原始数据部分
	return plaintext[3+separator:], nil
}

这里在publicKeyDecrypt函数中,首先检查填充格式,然后查找填充的分隔符,并返回原始数据部分。

为什么要这样做吗?

在网上比较多的实现私钥加密、公钥解密都是这样:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// 真正的私钥加密(非标准)
func RealPrivateEncrypt(msg []byte, privKey *rsa.PrivateKey) ([]byte, error) {
    // 直接使用RSA核心运算
    c := new(big.Int).SetBytes(msg)
    if c.Cmp(privKey.N) > 0 {
        return nil, errors.New("消息太长")
    }
    m := new(big.Int).Exp(c, privKey.D, privKey.N)
    return m.Bytes(), nil
}

// 对应的公钥解密
func RealPublicDecrypt(ciphertext []byte, pubKey *rsa.PublicKey) ([]byte, error) {
    c := new(big.Int).SetBytes(ciphertext)
    m := new(big.Int).Exp(c, big.NewInt(int64(pubKey.E)), pubKey.N)
    return m.Bytes(), nil
}

但是这样使用原始RSA运算进行"公钥解密"时,直接使用 big.IntBytes() 方法会导致数据长度固定为密钥长度(256字节),

并且高位填充255(即0xFF),所以就需要像publicKeyDecrypt一样去掉高位填充,才能等到真实的明文内容。

还有个问题就是,这里为什么填充的是0x00 0x02?

1
2
3
4
5
	// PKCS#1 v1.5填充格式: 0x00 0x02 [随机非零字节] 0x00 [原始数据]
	if plaintext[0] != 0x00 || plaintext[1] != 0x02 {
		return nil, errors.New("解密错误:无效的填充格式")
	}

这其实是PKCS#1 填充类型的区别,要看是加密填充还是签名填充:

  • 加密填充 (RSAES-PKCS1-v1_5) 格式:0x00 0x02

  • 签名填充 (RSASSA-PKCS1-v1_5) 填充格式:0x00 0x01

而上面java代码中,使用的是加密填充,所以填充格式是0x00 0x01

1
2
3
// Java 代码使用的是加密填充
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);  // 这会使用 PKCS#1 加密填充

java中填充的格式是:

  • 如果使用 Cipher.ENCRYPT_MODE → 加密填充 (0x02)

  • 如果使用 Signature.getInstance("SHA256withRSA") → 签名填充 (0x01)

数据特征:

  • 加密填充:第二个字节是 0x02,后面是随机非零字节

  • 签名填充:第二个字节是 0x01,后面是连续的 0xFF

所以如果要和java互通,就要保持填充的格式一致,在项目中视具体情况修改填充格式。

参考