一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Java-web中利用RSA進行加密解密操作的方法示例

Java-web中利用RSA進行加密解密操作的方法示例

2021-05-24 13:47niemingming Java教程

這篇文章主要給大家介紹了關(guān)于在Java-web中利用RSA進行加密解密操作的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

最近在看,網(wǎng)絡(luò)安全方面的問題,我們可以使用rsa進行非對稱加密防止,獲取用戶信息。首先我們看下java下操作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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.jb.test;
 
import java.security.invalidkeyexception;
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.nosuchalgorithmexception;
import java.security.privatekey;
import java.security.publickey;
import java.security.securerandom;
 
import javax.crypto.badpaddingexception;
import javax.crypto.cipher;
import javax.crypto.illegalblocksizeexception;
import javax.crypto.nosuchpaddingexception;
 
import org.apache.commons.codec.binary.hex;
 
public class rsaentry {
 
 /**
 * @title: main
 * @description: rsa加密算法,解密算法
 * @param args
 * void
 * @throws nosuchalgorithmexception
 * @throws nosuchpaddingexception
 * @throws invalidkeyexception
 * @throws badpaddingexception
 * @throws illegalblocksizeexception
 *
 * @throws
 */
 public static void main(string[] args) throws nosuchalgorithmexception, nosuchpaddingexception, invalidkeyexception, illegalblocksizeexception, badpaddingexception {
// security.getproviders();//獲取所有支持的加密算法
 //采用非對稱加密解密算法
 //生成密鑰實例
 keypairgenerator keygen = keypairgenerator.getinstance("rsa");
 securerandom random = new securerandom();
 random.setseed(system.currenttimemillis());//設(shè)置隨機種子
 keygen.initialize(512, random);//設(shè)置密鑰長度,應(yīng)為64的整數(shù)倍
 //生成密鑰公鑰對
 keypair keypair = keygen.generatekeypair();
 //獲取公鑰
 publickey pubkey = keypair.getpublic();
 //獲取私鑰
 privatekey prikey = keypair.getprivate();
 //測試數(shù)據(jù)
 string data = "測試數(shù)據(jù)";
 //使用公鑰進行加密
 //構(gòu)建加密解密類
 cipher cipher = cipher.getinstance("rsa");
 cipher.init(cipher.encrypt_mode, pubkey);//設(shè)置為加密模式
 byte[] jmdata = cipher.dofinal(data.getbytes());
 //打印加密后數(shù)據(jù)
 system.out.println(new string(hex.encodehex(jmdata)));
 //改為解密模式進行解密
 cipher.init(cipher.decrypt_mode, prikey);//會用私鑰解密
 jmdata = cipher.dofinal(jmdata);
 system.out.println(new string(jmdata));
 
 }
}

在web應(yīng)用中,我們可以通過js進行前端加密,java進行后臺解密,已達到我們的目的。這里需要注意的是,要想實現(xiàn)正確的加密解密算法,需要使用bcprov-ext-jdk15on-147.jar。

首先創(chuàng)建系統(tǒng)的密鑰提供者:

?
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
package com.jb.test;
 
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.privatekey;
import java.security.publickey;
import java.security.securerandom;
 
import org.apache.commons.codec.binary.hex;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.bcrsapublickey;
import org.bouncycastle.jce.provider.bouncycastleprovider;
 
/**
 * rsa初始化類
 * @author nmm
 * 結(jié)合前臺的js使用的話,主要需要指定密鑰提供者,即引入bcprov-ext-jdk15on-147.jar并使用其中的提供者
 */
public class rsainitutil {
 
 private static keypair keypair;
 
 private static rsainitutil util;
 
 private rsainitutil(){
 try {
 if(keypair == null) {
 //如果想要能夠解密js的加密文件,使用此提供者是必須的
 keypairgenerator keygen = keypairgenerator.getinstance("rsa", new bouncycastleprovider());
 securerandom random = new securerandom();
 random.setseed(system.currenttimemillis());
 keygen.initialize(512, random);//設(shè)置512位長度
 keypair = keygen.generatekeypair();
 }
 } catch (exception e) {
 e.printstacktrace();
 }
 }
 
 public static rsainitutil getinstance(){
 synchronized ("rsa") {
 if(util == null) {
 util = new rsainitutil();
 }
 }
 return util;
 }
 
 /**
 *
 * 功能說明:[獲取公鑰]
 * @return
 * 創(chuàng)建者:nmm, aug 19, 2013
 */
 public publickey getpublickey(){
 return keypair.getpublic();
 }
 
 public privatekey getprivatekey(){
 return keypair.getprivate();
 }
 
 /**
 *
 * 功能說明:[獲取公鑰字符串]
 * @return
 * 創(chuàng)建者:nmm, aug 19, 2013
 */
 public string getpublickeystr(){
 //根據(jù)我們的提供者,這里獲取的是該類型公鑰
 bcrsapublickey pk = (bcrsapublickey) getpublickey();
 string str = new string(hex.encodehex(pk.getmodulus().tobytearray()));
 system.out.println(str);
 //獲取入口10001一般都為這個
 string ss = new string(hex.encodehex(pk.getpublicexponent().tobytearray()));
 //獲取轉(zhuǎn)換字符串
 system.out.println(b2hex(pk.getmodulus().tobytearray()));
 return ss + str;
 }
 /**
 *
 * 功能說明:[手動轉(zhuǎn)換]
 * @param bytearray
 * @return
 * 創(chuàng)建者:nmm, aug 19, 2013
 */
 private string b2hex(byte[] bytearray) {
 stringbuilder sb = new stringbuilder();
 for(int i = 0; i < bytearray.length; i++ ) {
 int zhz = bytearray[i];
 if(zhz < 0) {
 zhz += 256;
 }
 if(zhz < 16) {
 sb.append("0");
 }
 sb.append(integer.tohexstring(zhz));
 }
 return sb.tostring();
 }
}

前臺引入rsa.js,bigint.js和barrett.js并采用如下方法加密:

?
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
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@page import="com.jb.test.rsainitutil"%>
<%
 
 rsainitutil rsa = rsainitutil.getinstance();
 string my = rsa.getpublickeystr();
 string exp = my.substring(0,6);
 string mou = my.substring(6);
%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
 <head>
 <title>rsa測試</title>
 <script type="text/javascript" src="rsa.js"></script>
 <script type="text/javascript" src="bigint.js"></script>
 <script type="text/javascript" src="barrett.js"></script>
 </head>
 
 <body>
 </body>
</html>
<script type="text/javascript">
 
 var m = '<%=mou%>';
 var e = '<%=exp%>';
 
 var key = '';
 setmaxdigits(128);
 alert(e);
 key = new rsakeypair(e,'',m);
 var res = encryptedstring(key,encodeuricomponent('測試數(shù)據(jù)'));
 
 window.location.href = 'rsadectry.do?res=' + res;
 
</script>

后臺解密算法為:

?
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
package com.jb.test;
 
import java.net.urldecoder;
import java.security.nosuchalgorithmexception;
 
import javax.crypto.cipher;
import javax.crypto.nosuchpaddingexception;
 
import org.apache.commons.codec.binary.hex;
import org.bouncycastle.jce.provider.bouncycastleprovider;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
 
/**
 * rsa加密的控制層
 * @author nmm
 *
 */
@controller("rsacontroller")
public class rsacontroller {
 
 private rsainitutil rsautil = rsainitutil.getinstance();
 
 /**
 *
 * 功能說明:[解密方法]
 * @param res
 * 創(chuàng)建者:nmm, aug 19, 2013
 * @throws nosuchpaddingexception
 * @throws nosuchalgorithmexception
 */
 @requestmapping("rsadectry.do")
 public void decodetry(string res) throws exception {
 cipher cipher = cipher.getinstance("rsa",new bouncycastleprovider());//必須指定此提供者
 cipher.init(cipher.decrypt_mode, rsautil.getprivatekey());
 system.out.println(res);
 byte[] buff = cipher.dofinal(hex.decodehex(res.tochararray()));
 //將字符串轉(zhuǎn)為字符
 stringbuilder sb = new stringbuilder(new string(buff,"utf-8"));
 //解密后的內(nèi)容是倒敘的
 sb.reverse();
 //進行url解密,主要是為了中文亂碼問題
 string result = urldecoder.decode(sb.tostring(), "utf-8");
 system.out.println(result);
 
 }
}

至此可完成,整個加密解密過程,下面大家可以把rsa相關(guān)的內(nèi)容全部整合到一個工具類中,不用想這里處理。

下面為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
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
package com.jb.framework.filter;
 
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.objectinputstream;
import java.io.objectoutputstream;
import java.math.biginteger;
import java.net.urldecoder;
import java.security.keyfactory;
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.nosuchalgorithmexception;
import java.security.privatekey;
import java.security.publickey;
import java.security.securerandom;
import java.security.spec.rsaprivatekeyspec;
import java.security.spec.rsapublickeyspec;
import java.util.calendar;
 
import javax.crypto.cipher;
 
import org.apache.commons.codec.binary.hex;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.bcrsapublickey;
import org.bouncycastle.jce.provider.bouncycastleprovider;
 
/**
 *
 * @package: com.jb.framework.filter<br>
 * @classname: rsautil<br>
 * @description: rsa加密工具類,這里我們是每次系統(tǒng)啟動時聲稱一套公鑰,私鑰,因此不能將加密串存入數(shù)據(jù)庫中,如果要這么做可以預(yù)先生成密鑰隊寫入到文件中<br>
 */
public class rsautil {
 
 private rsautil(){}
 
 public static final string keypubfile = "rsapubkey.bin";
 public static final string keyprifile = "rsaprikey.bin";
 
 private static rsautil rsa;
 //密鑰生成器
 private publickey publickey;
 //密鑰隊
 private privatekey privatekey;
 
 
 public static rsautil getinstance(){
 synchronized ("rsa") {
 if(rsa == null) {
 rsa = new rsautil();
 rsa.init();
 }
 }
 return rsa;
 }
 /**
 *
 * @title: init
 * @description: 初始化方法
 * void
 * @throws
 */
 private void init() {
 //構(gòu)建rsa算法
 try {
 keypairgenerator kengen = keypairgenerator.getinstance("rsa",new bouncycastleprovider());
 //構(gòu)建隨機種子
 securerandom random = new securerandom();
 random.setseed(calendar.getinstance().gettimeinmillis());
 kengen.initialize(512, random);//采用512位加密
 keypair keypair = kengen.generatekeypair();
 publickey = keypair.getpublic();
 privatekey = keypair.getprivate();
 } catch (nosuchalgorithmexception e) {
 e.printstacktrace();
 }
 }
 /**
 *
 * @title: getpublickey
 * @description: 獲取公鑰
 * @return
 * publickey
 * @throws
 */
 public publickey getpublickey(){
 return this.publickey;
 }
 /**
 *
 * @title: getprivatekey
 * @description: 獲取私鑰
 * @return
 * privatekey
 * @throws
 */
 public privatekey getprivatekey(){
 return this.privatekey;
 }
 /**
 *
 * @title: getpublickeystr
 * @description: 獲取系統(tǒng)公鑰字符串,前6位為exponentk,后面為modlus
 * @return
 * string
 * @throws
 */
 public string getpublickeystr(){
 bcrsapublickey pk = (bcrsapublickey) getpublickey();
 string pubstr = "";
 pubstr += b2hex(pk.getpublicexponent().tobytearray());
 pubstr += b2hex(pk.getmodulus().tobytearray());
 return pubstr;
 }
 /**
 *
 * @title: entrytext
 * @description: 使用默認公鑰進行加密
 * @param text
 * @return
 * string
 * @throws
 */
 public string encrytext(string text) {
 return encrytext(text,getpublickey());
 }
 /**
 *
 * @title: entrytext
 * @description: 使用指定公鑰進行加密,解決長字符串加密
 * @param text
 * @param publickey2
 * @return
 * string
 * @throws
 */
 public string encrytext(string text, publickey pk) {
 try {
 cipher cipher = cipher.getinstance("rsa",new bouncycastleprovider());
 cipher.init(cipher.encrypt_mode, pk);
 int block = cipher.getblocksize();//獲取最大加密塊
 int j = 0;
 stringbuilder sb = new stringbuilder();
 byte[] targetdata = text.getbytes("utf-8");
 while (targetdata.length - j*block > 0) {
 byte[] jmdata = cipher.dofinal(targetdata,j*block,math.min(targetdata.length - j*block, block));
 sb.append(b2hex(jmdata));
 j++;
 }
 return sb.tostring();
 } catch (exception e) {
 e.printstacktrace();
 }
 return null;
 }
 /**
 *
 * @title: decrytext
 * @description: 使用默認的私鑰進行解密解密算法
 * @param text
 * @return
 * string
 * @throws
 */
 public string decrytext(string text) {
 return decrytext(text,getprivatekey());
 }
 /**
 *
 * @title: decrytext
 * @description: 指定私鑰進行解密,增加對于大字符串的解密操作
 * @param text
 * @param privatekey2
 * @return
 * string
 * @throws
 */
 public string decrytext(string text, privatekey pk) {
 try {
 cipher cipher = cipher.getinstance("rsa", new bouncycastleprovider());
 cipher.init(cipher.decrypt_mode, pk);
 byte[] targetbuff = hex.decodehex(text.replace(" ", "").tochararray());
 int block = cipher.getblocksize();
 int j = 0;
 stringbuilder sb = new stringbuilder();
 while (targetbuff.length - j * block > 0) {
 byte[] jmdata = cipher.dofinal(targetbuff,j*block,block);
 sb.append(new string(jmdata,"utf-8"));
 j++;
 }
 return sb.tostring();
 
 } catch (exception e) {
 e.printstacktrace();
 }
 return null;
 }
 /**
 *
 * @title: decrytextbyurl
 * @description: 解密前臺傳遞的加密串,為防止中文亂碼,前臺字符串最好使用encodeuricomponent方法進行url編碼
 * @param text
 * @return
 * string
 * @throws
 */
 public string decrytextbyurl(string text) {
 try {
 cipher cipher = cipher.getinstance("rsa", new bouncycastleprovider());
 cipher.init(cipher.decrypt_mode, getprivatekey());
 byte[] targetbuff = hex.decodehex(text.replace(" ", "").tochararray());
 int block = cipher.getblocksize();
 int j = 0;
 stringbuilder sb = new stringbuilder();
 while (targetbuff.length - j * block > 0) {//處理大字符串的加密解密處理
 byte[] jmdata = cipher.dofinal(targetbuff,j*block,block);
 sb.append(new stringbuilder(new string(jmdata,"utf-8")).reverse());
 j++;
 }
 string res = urldecoder.decode(sb.tostring(), "utf-8");
 return res;
 
 } catch (exception e) {
 e.printstacktrace();
 }
 return null;
 }
 /**
 *
 * @title: createpubkey
 * @description: 根據(jù)指定的冪和模式生成公鑰
 * @param exponent
 * @param modules
 * @return
 * publickey
 * @throws
 */
 public publickey createpubkey(byte[] exponent,byte[]modules) {
 try {
 keyfactory keyfactory = keyfactory.getinstance("rsa", new bouncycastleprovider());
 rsapublickeyspec rsaks = new rsapublickeyspec(new biginteger(modules),new biginteger(exponent));
 return keyfactory.generatepublic(rsaks);
 
 } catch (exception e) {
 e.printstacktrace();
 }
 
 return null;
 }
 /**
 *
 * @title: createpubkey
 * @description: 根據(jù)指定的冪和模式生成公鑰
 * @param exponent
 * @param modules
 * @return
 * publickey
 * @throws
 */
 public privatekey createprikey(byte[] exponent,byte[]modules) {
 try {
 keyfactory keyfactory = keyfactory.getinstance("rsa", new bouncycastleprovider());
 rsaprivatekeyspec rsaks = new rsaprivatekeyspec(new biginteger(modules),new biginteger(exponent));
 return keyfactory.generateprivate(rsaks);
 
 } catch (exception e) {
 e.printstacktrace();
 }
 return null;
 }
 /**
 *
 * @title: savekeytofile
 * @description: 保存公鑰和私鑰到文件中
 * void
 * @throws
 */
 public void savekeytofile() {
 publickey pk = getpublickey();
 privatekey prik = getprivatekey();
 
 string path = rsautil.class.getclassloader().getresource("").getpath();
 objectoutputstream outpub = null;
 objectoutputstream outpri = null;
 try {
 system.out.println(path + keypubfile);
 outpub = new objectoutputstream(new fileoutputstream(path + keypubfile));
 outpri = new objectoutputstream(new fileoutputstream(path + keyprifile));
 outpub.writeobject(pk);
 outpri.writeobject(prik);
 } catch (exception e) {
 e.printstacktrace();
 }finally {
 try {
 outpub.close();
 outpri.close();
 } catch (ioexception e) {
 e.printstacktrace();
 }
 
 }
 }
 /**
 *
 * @title: readkey
 * @description: 讀取密鑰
 * @param ispub
 * @return
 * object
 * @throws
 */
 public object readkey(boolean ispub) {
 string path = rsautil.class.getclassloader().getresource("").getpath();
 objectinputstream in = null;
 try {
 if(ispub) {
 path += keypubfile;
 in = new objectinputstream(new fileinputstream(path));
 publickey pk = (publickey) in.readobject();
 return pk;
 }else {
 path += keyprifile;
 in = new objectinputstream(new fileinputstream(path));
 privatekey pk = (privatekey) in.readobject();
 return pk;
 }
 } catch (exception e) {
 e.printstacktrace();
 }finally {
 try {
 in.close();
 } catch (ioexception e) {
 e.printstacktrace();
 }
 }
 return null;
 }
 
 
 /**
 *
 * @title: b2hex
 * @description: 將二進制轉(zhuǎn)為16進制字符串
 * @param buff
 * @return
 * string
 * @throws
 */
 public string b2hex(byte[] buff) {
 stringbuilder sb = new stringbuilder();
 for(int i = 0; i < buff.length; i++) {
 int z = buff[i];
 if(z < 0) {
 z+= 256;
 }
 if(z < 16) {
 sb.append("0");
 }
 sb.append(integer.tohexstring(z));
 }
 return sb.tostring();
 }
}

下載:rsajar.rar

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。

原文鏈接:https://blog.csdn.net/niemingming/article/details/10082975

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲精品乱码久久久久久蜜桃欧美 | 91久久偷偷做嫩草影院电 | 精品精品国产自在香蕉网 | 日韩 国产 欧美 精品 在线 | 国内在线观看 | 麻豆在线传煤 | 校花被扒开尿口折磨憋尿 | 无耻三级在线观看 | 日本大尺度动漫在线观看缘之空 | 日韩黄色录像 | 成人一级黄色大片 | 色哟哟在线视频 | 99热久久国产精品这里 | 423hk四虎| 果冻传媒林予曦图片 | 精品国产日韩一区三区 | 国产激情视频网站 | 91精品国产免费久久国语蜜臀 | 好紧好爽范冰冰系列 | 36美女厕所撒尿全过程 | a级免费在线观看 | 国产成人亚洲精品一区二区在线看 | 紧缚束缚调教丨vk | 亚洲欧美专区精品久久 | 沉香如屑西瓜视频免费观看完整版 | 国产精品免费小视频 | jk制服白丝超短裙流白浆 | 国产小视频在线 | 亚洲一级特黄 | 国产日韩欧美精品在线 | a4yy欧美一区二区三区 | 紧致肉肉高h | 99精品视频免费在线观看 | 亚洲国产成人久久精品影视 | 好大好爽好硬我要喷水了 | 欧美白人猛性xxxxx69交 | 国产无限免费观看黄网站 | 男人香蕉好大好爽视频 | 亚洲精品国产国语 | 外国xxx| 亚洲色图二区 |