RSA 的加密 解密
RSA加密解密类:
1 package me.hao0.trace.order;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileReader;
6 import java.io.FileWriter;
7 import java.io.IOException;
8 import java.security.InvalidKeyException;
9 import java.security.KeyFactory;
10 import java.security.KeyPair;
11 import java.security.KeyPairGenerator;
12 import java.security.NoSuchAlgorithmException;
13 import java.security.SecureRandom;
14 import java.security.interfaces.RSAPrivateKey;
15 import java.security.interfaces.RSAPublicKey;
16 import java.security.spec.InvalidKeySpecException;
17 import java.security.spec.PKCS8EncodedKeySpec;
18 import java.security.spec.X509EncodedKeySpec;
19 import javax.crypto.BadPaddingException;
20 import javax.crypto.Cipher;
21 import javax.crypto.IllegalBlockSizeException;
22 import javax.crypto.NoSuchPaddingException;
23
24
25
26 public class RSAEncrypt {
27 /**
28 * 字节数据转字符串专用集合
29 */
30 private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
31 '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
32
33 /**
34 * 随机生成密钥对
35 */
36 public static void genKeyPair(String filePath) {
37 // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
38 KeyPairGenerator keyPairGen = null;
39 try {
40 keyPairGen = KeyPairGenerator.getInstance("RSA");
41 } catch (NoSuchAlgorithmException e) {
42 // TODO Auto-generated catch block
43 e.printStackTrace();
44 }
45 // 初始化密钥对生成器,密钥大小为96-1024位
46 keyPairGen.initialize(1024,new SecureRandom());
47 // 生成一个密钥对,保存在keyPair中
48 KeyPair keyPair = keyPairGen.generateKeyPair();
49 // 得到私钥
50 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
51 // 得到公钥
52 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
53 try {
54 // 得到公钥字符串
55 String publicKeyString = Base64.encode(publicKey.getEncoded());
56 // 得到私钥字符串
57 String privateKeyString = Base64.encode(privateKey.getEncoded());
58 // 将密钥对写入到文件
59 FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
60 FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
61 BufferedWriter pubbw = new BufferedWriter(pubfw);
62 BufferedWriter pribw = new BufferedWriter(prifw);
63 pubbw.write(publicKeyString);
64 pribw.write(privateKeyString);
65 pubbw.flush();
66 pubbw.close();
67 pubfw.close();
68 pribw.flush();
69 pribw.close();
70 prifw.close();
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74 }
75
76 /**
77 * 从文件中输入流中加载公钥
78 * @param path 公钥输入流
79 * @throws Exception 加载公钥时产生的异常
80 */
81 public static String loadPublicKeyByFile(String path) throws Exception {
82 try {
83 BufferedReader br = new BufferedReader(new FileReader(path+ "/publicKey.keystore"));
84 String readLine = null;
85 StringBuilder sb = new StringBuilder();
86 while ((readLine = br.readLine()) != null) {
87 sb.append(readLine);
88 System.out.println( "得到的公钥 = "+sb);
89 }
90 br.close();
91 return sb.toString();
92 } catch (IOException e) {
93 throw new Exception("公钥数据流读取错误");
94 } catch (NullPointerException e) {
95 throw new Exception("公钥输入流为空");
96 }
97 }
98
99 /**
100 * 从字符串中加载公钥
101 *
102 * @param publicKeyStr
103 * 公钥数据字符串
104 * @throws Exception
105 * 加载公钥时产生的异常
106 */
107 public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
108 throws Exception {
109 try {
110 byte[] buffer = Base64.decode(publicKeyStr);
111 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
112 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
113 return (RSAPublicKey) keyFactory.generatePublic(keySpec);
114 } catch (NoSuchAlgorithmException e) {
115 throw new Exception("无此算法");
116 } catch (InvalidKeySpecException e) {
117 throw new Exception("公钥非法");
118 } catch (NullPointerException e) {
119 throw new Exception("公钥数据为空");
120 }
121 }
122
123 /**
124 * 从文件中加载私钥
125 * @param path 私钥文件名
126 * @return 是否成功
127 * @throws Exception
128 */
129 public static String loadPrivateKeyByFile(String path) throws Exception {
130 try {
131 BufferedReader br = new BufferedReader(new FileReader(path + "/privateKey.keystore"));
132 String readLine = null;
133 StringBuilder sb = new StringBuilder();
134 while ((readLine = br.readLine()) != null) {
135 sb.append(readLine);
136 }
137 br.close();
138 return sb.toString();
139 } catch (IOException e) {
140 throw new Exception("私钥数据读取错误");
141 } catch (NullPointerException e) {
142 throw new Exception("私钥输入流为空");
143 }
144 }
145
146 public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
147 throws Exception {
148 try {
149 byte[] buffer = Base64.decode(privateKeyStr);
150 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
151 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
152 return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
153 } catch (NoSuchAlgorithmException e) {
154 throw new Exception("无此算法");
155 } catch (InvalidKeySpecException e) {
156 throw new Exception("私钥非法");
157 } catch (NullPointerException e) {
158 throw new Exception("私钥数据为空");
159 }
160 }
161
162 /**
163 * 公钥加密过程
164 * @param publicKey 公钥
165 * @param plainTextData 明文数据
166 * @return
167 * @throws Exception 加密过程中的异常信息
168 */
169 public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)throws Exception {
170 if (publicKey == null) {
171 throw new Exception("加密公钥为空, 请设置");
172 }
173 Cipher cipher = null;
174 try {
175 // 使用默认RSA
176 cipher = Cipher.getInstance("RSA");
177 // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
178 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
179 byte[] output = cipher.doFinal(plainTextData);
180 return output;
181 } catch (NoSuchAlgorithmException e) {
182 throw new Exception("无此加密算法");
183 } catch (NoSuchPaddingException e) {
184 e.printStackTrace();
185 return null;
186 } catch (InvalidKeyException e) {
187 throw new Exception("加密公钥非法,请检查");
188 } catch (IllegalBlockSizeException e) {
189 throw new Exception("明文长度非法");
190 } catch (BadPaddingException e) {
191 throw new Exception("明文数据已损坏");
192 }
193 }
194
195 /**
196 * 私钥加密过程 *
197 * @param privateKey 私钥
198 * @param plainTextData 明文数据
199 * @return
200 * @throws Exception 加密过程中的异常信息
201 */
202 public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)throws Exception {
203 if (privateKey == null) {
204 throw new Exception("加密私钥为空, 请设置");
205 }
206 Cipher cipher = null;
207 try {
208 // 使用默认RSA
209 cipher = Cipher.getInstance("RSA");
210 cipher.init(Cipher.ENCRYPT_MODE, privateKey);
211 byte[] output = cipher.doFinal(plainTextData);
212 return output;
213 } catch (NoSuchAlgorithmException e) {
214 throw new Exception("无此加密算法");
215 } catch (NoSuchPaddingException e) {
216 e.printStackTrace();
217 return null;
218 } catch (InvalidKeyException e) {
219 throw new Exception("加密私钥非法,请检查");
220 } catch (IllegalBlockSizeException e) {
221 throw new Exception("明文长度非法");
222 } catch (BadPaddingException e) {
223 throw new Exception("明文数据已损坏");
224 }
225 }
226
227 /**
228 * 私钥解密过程
229 *
230 * @param privateKey 私钥
231 * @param cipherData 密文数据(八进制)
232 * @return 明文
233 * @throws Exception 解密过程中的异常信息
234 */
235 public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
236 if (privateKey == null) {
237 throw new Exception("解密私钥为空, 请设置");
238 }
239 Cipher cipher = null;
240 try {
241 // 使用默认RSA
242 cipher = Cipher.getInstance("RSA");
243 // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
244 cipher.init(Cipher.DECRYPT_MODE, privateKey);
245 byte[] output = cipher.doFinal(cipherData);
246 return output;
247 } catch (NoSuchAlgorithmException e) {
248 throw new Exception("无此解密算法");
249 } catch (NoSuchPaddingException e) {
250 e.printStackTrace();
251 return null;
252 } catch (InvalidKeyException e) {
253 throw new Exception("解密私钥非法,请检查");
254 } catch (IllegalBlockSizeException e) {
255 throw new Exception("密文长度非法");
256 } catch (BadPaddingException e) {
257 throw new Exception("密文数据已损坏");
258 }
259 }
260
261 /**
262 * 公钥解密过程
263 * @param publicKey 公钥
264 * @param cipherData 密文数据
265 * @return 明文
266 * @throws Exception 解密过程中的异常信息
267 */
268 public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
269 throws Exception {
270 if (publicKey == null) {
271 throw new Exception("解密公钥为空, 请设置");
272 }
273 Cipher cipher = null;
274 try {
275 // 使用默认RSA
276 cipher = Cipher.getInstance("RSA");
277 // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
278 cipher.init(Cipher.DECRYPT_MODE, publicKey);
279 byte[] output = cipher.doFinal(cipherData);
280 return output;
281 } catch (NoSuchAlgorithmException e) {
282 throw new Exception("无此解密算法");
283 } catch (NoSuchPaddingException e) {
284 e.printStackTrace();
285 return null;
286 } catch (InvalidKeyException e) {
287 throw new Exception("解密公钥非法,请检查");
288 } catch (IllegalBlockSizeException e) {
289 throw new Exception("密文长度非法");
290 } catch (BadPaddingException e) {
291 throw new Exception("密文数据已损坏");
292 }
293 }
294
295 /**
296 * 字节数据转十六进制字符串
297 * @param data 输入数据
298 * @return 十六进制内容
299 */
300 public static String byteArrayToString(byte[] data) {
301 StringBuilder stringBuilder = new StringBuilder();
302 for (int i = 0; i < data.length; i++) {
303 // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
304 stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
305 // 取出字节的低四位 作为索引得到相应的十六进制标识符
306 stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
307 if (i < data.length - 1) {
308 stringBuilder.append(' ');
309 }
310 }
311 return stringBuilder.toString();
312 }
313 }
签名及校验类:
1 package me.hao0.trace.order;
2
3 import java.security.KeyFactory;
4 import java.security.PrivateKey;
5 import java.security.PublicKey;
6 import java.security.Signature;
7 import java.security.spec.PKCS8EncodedKeySpec;
8 import java.security.spec.X509EncodedKeySpec;
9
10
11
12 /**
13 * RSA签名验签类
14 */
15 public class RSASignature{
16
17 /**
18 * 签名算法
19 */
20 public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
21
22 /**
23 * RSA签名
24 * @param content 待签名数据
25 * @param privateKey 商户私钥
26 * @param encode 字符集编码
27 * @return 签名值
28 */
29 public static String sign(String content, String privateKey, String encode){
30 try{
31 PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
32
33 KeyFactory keyf = KeyFactory.getInstance("RSA");
34 PrivateKey priKey = keyf.generatePrivate(priPKCS8);
35
36 Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
37 signature.initSign(priKey);
38 signature.update( content.getBytes(encode));
39
40 byte[] signed = signature.sign();
41
42 return Base64.encode(signed);
43 }catch (Exception e){
44 e.printStackTrace();
45 }
46
47 return null;
48 }
49
50 public static String sign(String content, String privateKey){
51 try{
52 PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
53 KeyFactory keyf = KeyFactory.getInstance("RSA");
54 PrivateKey priKey = keyf.generatePrivate(priPKCS8);
55 Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
56 signature.initSign(priKey);
57 signature.update( content.getBytes());
58 byte[] signed = signature.sign();
59 return Base64.encode(signed);
60 }
61 catch (Exception e){
62 e.printStackTrace();
63 }
64 return null;
65 }
66
67 /**
68 * RSA验签名检查
69 * @param content 待签名数据
70 * @param sign 签名值
71 * @param publicKey 分配给开发商公钥
72 * @param encode 字符集编码
73 * @return 布尔值
74 */
75 public static boolean doCheck(String content, String sign, String publicKey,String encode){
76 try{
77 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
78 byte[] encodedKey = Base64.decode(publicKey);
79 PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
80
81 Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
82 signature.initVerify(pubKey);
83 signature.update( content.getBytes(encode) );
84
85 boolean bverify = signature.verify( Base64.decode(sign) );
86 return bverify;
87
88 }catch (Exception e){
89 e.printStackTrace();
90 }
91 return false;
92 }
93
94 public static boolean doCheck(String content, String sign, String publicKey){
95 try{
96 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
97 byte[] encodedKey = Base64.decode(publicKey);
98 PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
99
100
101 Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
102 signature.initVerify(pubKey);
103 signature.update( content.getBytes() );
104
105 boolean bverify = signature.verify( Base64.decode(sign) );
106 return bverify;
107
108 }catch (Exception e){
109 e.printStackTrace();
110 }
111
112 return false;
113 }
114
115 }
再来一个Base64的类,当然你也可以用commons-codec-1.9.jar
1 package me.hao0.trace.order;
2
3 public final class Base64 {
4
5 static private final int BASELENGTH = 128;
6 static private final int LOOKUPLENGTH = 64;
7 static private final int TWENTYFOURBITGROUP = 24;
8 static private final int EIGHTBIT = 8;
9 static private final int SIXTEENBIT = 16;
10 static private final int FOURBYTE = 4;
11 static private final int SIGN = -128;
12 static private final char PAD = '=';
13 static private final boolean fDebug = false;
14 static final private byte[] base64Alphabet = new byte[BASELENGTH];
15 static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
16
17 static {
18 for (int i = 0; i < BASELENGTH; ++i) {
19 base64Alphabet[i] = -1;
20 }
21 for (int i = 'Z'; i >= 'A'; i--) {
22 base64Alphabet[i] = (byte) (i - 'A');
23 }
24 for (int i = 'z'; i >= 'a'; i--) {
25 base64Alphabet[i] = (byte) (i - 'a' + 26);
26 }
27
28 for (int i = '9'; i >= '0'; i--) {
29 base64Alphabet[i] = (byte) (i - '0' + 52);
30 }
31
32 base64Alphabet['+'] = 62;
33 base64Alphabet['/'] = 63;
34
35 for (int i = 0; i <= 25; i++) {
36 lookUpBase64Alphabet[i] = (char) ('A' + i);
37 }
38
39 for (int i = 26, j = 0; i <= 51; i++, j++) {
40 lookUpBase64Alphabet[i] = (char) ('a' + j);
41 }
42
43 for (int i = 52, j = 0; i <= 61; i++, j++) {
44 lookUpBase64Alphabet[i] = (char) ('0' + j);
45 }
46 lookUpBase64Alphabet[62] = (char) '+';
47 lookUpBase64Alphabet[63] = (char) '/';
48
49 }
50
51 private static boolean isWhiteSpace(char octect) {
52 return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
53 }
54
55 private static boolean isPad(char octect) {
56 return (octect == PAD);
57 }
58
59 private static boolean isData(char octect) {
60 return (octect < BASELENGTH && base64Alphabet[octect] != -1);
61 }
62
63 /**
64 * 将十六进制点编码成Base64
65 * @param binaryData 二进制数据的数组
66 * @return Encoded Base64 array
67 */
68 public static String encode(byte[] binaryData) {
69
70 if (binaryData == null) {
71 return null;
72 }
73
74 int lengthDataBits = binaryData.length * EIGHTBIT;
75 if (lengthDataBits == 0) {
76 return "";
77 }
78
79 int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
80 int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
81 int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
82 char encodedData[] = null;
83
84 encodedData = new char[numberQuartet * 4];
85
86 byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
87
88 int encodedIndex = 0;
89 int dataIndex = 0;
90 if (fDebug) {
91 System.out.println("number of triplets = " + numberTriplets);
92 }
93
94 for (int i = 0; i < numberTriplets; i++) {
95 b1 = binaryData[dataIndex++];
96 b2 = binaryData[dataIndex++];
97 b3 = binaryData[dataIndex++];
98
99 if (fDebug) {
100 System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
101 }
102
103 l = (byte) (b2 & 0x0f);
104 k = (byte) (b1 & 0x03);
105
106 byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
107 byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
108 byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
109
110 if (fDebug) {
111 System.out.println("val2 = " + val2);
112 System.out.println("k4 = " + (k << 4));
113 System.out.println("vak = " + (val2 | (k << 4)));
114 }
115
116 encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
117 encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
118 encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
119 encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
120 }
121
122 // form integral number of 6-bit groups
123 if (fewerThan24bits == EIGHTBIT) {
124 b1 = binaryData[dataIndex];
125 k = (byte) (b1 & 0x03);
126 if (fDebug) {
127 System.out.println("b1=" + b1);
128 System.out.println("b1<<2 = " + (b1 >> 2));
129 }
130 byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
131 encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
132 encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
133 encodedData[encodedIndex++] = PAD;
134 encodedData[encodedIndex++] = PAD;
135 } else if (fewerThan24bits == SIXTEENBIT) {
136 b1 = binaryData[dataIndex];
137 b2 = binaryData[dataIndex + 1];
138 l = (byte) (b2 & 0x0f);
139 k = (byte) (b1 & 0x03);
140
141 byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
142 byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
143
144 encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
145 encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
146 encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
147 encodedData[encodedIndex++] = PAD;
148 }
149
150 return new String(encodedData);
151 }
152
153 /**
154 * 将BASE64数据解码为八进制
155 * @param encoded Base64数据的字符串
156 * @return 数组包含解码数据。
157 */
158 public static byte[] decode(String encoded) {
159
160 if (encoded == null) {
161 return null;
162 }
163
164 char[] base64Data = encoded.toCharArray();
165 //移除空字符
166 int len = removeWhiteSpace(base64Data);
167
168 //应该被4整除
169 if (len % FOURBYTE != 0) {
170 return null;
171 }
172
173 int numberQuadruple = (len / FOURBYTE);
174
175 if (numberQuadruple == 0) {
176 return new byte[0];
177 }
178
179 byte decodedData[] = null;
180 byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
181 char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
182
183 int i = 0;
184 int encodedIndex = 0;
185 int dataIndex = 0;
186 decodedData = new byte[(numberQuadruple) * 3];
187
188 for (; i < numberQuadruple - 1; i++) {
189
190 // 如果找到“没有数据”,只返回空
191 if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
192 || !isData((d3 = base64Data[dataIndex++]))
193 || !isData((d4 = base64Data[dataIndex++]))) {
194 return null;
195 }
196
197 b1 = base64Alphabet[d1];
198 b2 = base64Alphabet[d2];
199 b3 = base64Alphabet[d3];
200 b4 = base64Alphabet[d4];
201
202 decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
203 decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
204 decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
205 }
206 //如果找到“没有数据”,只返回空
207 if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
208 return null;
209 }
210
211 b1 = base64Alphabet[d1];
212 b2 = base64Alphabet[d2];
213
214 d3 = base64Data[dataIndex++];
215 d4 = base64Data[dataIndex++];
216 if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
217 if (isPad(d3) && isPad(d4)) {
218 if ((b2 & 0xf) != 0)//last 4 bits should be zero
219 {
220 return null;
221 }
222 byte[] tmp = new byte[i * 3 + 1];
223 System.arraycopy(decodedData, 0, tmp, 0, i * 3);
224 tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
225 return tmp;
226 } else if (!isPad(d3) && isPad(d4)) {
227 b3 = base64Alphabet[d3];
228 if ((b3 & 0x3) != 0)//last 2 bits should be zero
229 {
230 return null;
231 }
232 byte[] tmp = new byte[i * 3 + 2];
233 System.arraycopy(decodedData, 0, tmp, 0, i * 3);
234 tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
235 tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
236 return tmp;
237 } else {
238 return null;
239 }
240 } else { //No PAD e.g 3cQl
241 b3 = base64Alphabet[d3];
242 b4 = base64Alphabet[d4];
243 decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
244 decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
245 decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
246
247 }
248
249 return decodedData;
250 }
251
252 /**
253 * 从包含编码的Base64数据的MIME中移除空白
254 * @param data Base64数据的字节数组
255 * @return the new length
256 */
257 private static int removeWhiteSpace(char[] data) {
258 if (data == null) {
259 return 0;
260 }
261
262 // 计算不是空白的字符
263 int newSize = 0;
264 int len = data.length;
265 for (int i = 0; i < len; i++) {
266 if (!isWhiteSpace(data[i])) {
267 data[newSize++] = data[i];
268 }
269 }
270 return newSize;
271 }
272 }
测试类:需要再D盘下建 rsa的文件夹,并在该文件夹下新建两个文件。
1 package me.hao0.trace.order;
2
3 import me.hao0.trace.order.Base64;
4 import me.hao0.trace.order.RSAEncrypt;
5 import me.hao0.trace.order.RSASignature;
6
7 import java.net.URL;
8
9 public class MainTest {
10
11 public static void main(String[] args) throws Exception {
12 String filepath="D:/rsa/";
13 //随机生成密钥对,并把公钥私钥写入对应的文件夹内
14 RSAEncrypt.genKeyPair(filepath);
15
16 System.out.println("--------------公钥加密私钥解密过程-------------------");
17 String plainText="测试_公钥加密私钥解密";
18 //公钥加密过程
19 byte[] cipherData= RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),plainText.getBytes());
20 String cipher= Base64.encode(cipherData);
21 //私钥解密过程
22 byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));
23 String restr=new String(res);
24 System.out.println("原文:"+plainText);
25 System.out.println("加密:"+cipher);
26 System.out.println("解密:"+restr);
27 System.out.println();
28
29 System.out.println("--------------私钥加密公钥解密过程-------------------");
30 plainText="测试_私钥加密公钥解密";
31 //私钥加密过程
32 cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),plainText.getBytes());
33 cipher=Base64.encode(cipherData);
34 //公钥解密过程
35 res=RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), Base64.decode(cipher));
36 restr=new String(res);
37 System.out.println("原文 :"+plainText);
38 System.out.println("加密 :"+cipher);
39 System.out.println("解密 :"+restr);
40 System.out.println();
41
42 System.out.println("---------------私钥签名过程------------------");
43 String content="测试_这是用于签名的原始数据";
44 String signstr= RSASignature.sign(content,RSAEncrypt.loadPrivateKeyByFile(filepath));
45 System.out.println("签名原串 :"+content);
46 System.out.println("签名串 :"+signstr);
47 System.out.println();
48
49 System.out.println("---------------公钥校验签名------------------");
50 System.out.println("签名原串 :"+content);
51 System.out.println("签名串 :"+signstr);
52
53 System.out.println("验签结果 :"+RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));
54 System.out.println();
55
56 }
57 }