java web学习-----rsa登陆加密入门篇

借鉴https://my.oschina.net/chaun/blog/519105

 1  @GetMapping("/login")
 2         public String login(Model model,HttpServletRequest request) throws IOException {
 3             try {
 4                 model.addAttribute("result","login");
 5                 HashMap<String, Object> map = RSATools.getKeys();
 6                //生成公钥和私钥  
 7                RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
 8                RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
 9              //私钥保存在session中,用于解密
10                HttpSession session=request.getSession();
11                session.setAttribute("private", privateKey);
12                //公钥信息保存在页面,用于加密
13                String publicKeyExponent = publicKey.getPublicExponent().toString(16);
14                String publicKeyModulus = publicKey.getModulus().toString(16);
15                request.setAttribute("publicKeyExponent", publicKeyExponent);
16                request.setAttribute("publicKeyModulus", publicKeyModulus);    
17                System.out.println(publicKeyExponent);
18                     } catch (Exception e) {
19                         // TODO Auto-generated catch block
20                         e.printStackTrace();
21                     }
22             return "login";
23         }
24         @GetMapping("/registe")
25         public String registe(Model model,HttpServletRequest request) throws IOException {
26             model.addAttribute("result","registes");
27             
28             return "registe";
29         }
30         @PostMapping("/login")
31         public String dologin(Model model,HttpServletRequest request) throws IOException {
32             try {
33                 //model.addAttribute("result","login");
34                 HttpSession session=request.getSession();
35                 RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("private");
36                String username=request.getParameter("username");
37                 String password = RSATools.decryptByPrivateKey(request.getParameter("password"), privateKey); 
38                System.err.println(password);
39                Getdata getdata=new Getdata();
40                user user=getdata.GetUser(username, password);
41                if(user==null) {
42                    model.addAttribute("result","fail"); 
43                    HashMap<String, Object> map = RSATools.getKeys();
44                    //生成公钥和私钥  
45                    RSAPublicKey publicKey2 = (RSAPublicKey) map.get("public");
46                    RSAPrivateKey privateKey2 = (RSAPrivateKey) map.get("private");
47                  //私钥保存在session中,用于解密
48                    HttpSession session2=request.getSession();
49                    session2.setAttribute("private", privateKey2);
50                    //公钥信息保存在页面,用于加密
51                    String publicKeyExponent = publicKey2.getPublicExponent().toString(16);
52                    String publicKeyModulus = publicKey2.getModulus().toString(16);
53                    request.setAttribute("publicKeyExponent", publicKeyExponent);
54                    request.setAttribute("publicKeyModulus", publicKeyModulus);    
55                    System.out.println(publicKeyExponent);
56                }
57                else{
58                  String checkusername=user.getUsername();
59                  String checkpassword=user.getPassword();
60                  if(checkpassword.equals(password)&&checkusername.equals(username)) {
61                      model.addAttribute("result","success");
62                      return "index";
63                  }
64                  else {
65                      model.addAttribute("result","fail"); 
66                      HashMap<String, Object> map1 = RSATools.getKeys();
67                      //生成公钥和私钥  
68                      RSAPublicKey publicKey1 = (RSAPublicKey) map1.get("public");
69                      RSAPrivateKey privateKey1 = (RSAPrivateKey) map1.get("private");
70                    //私钥保存在session中,用于解密
71                      HttpSession session1=request.getSession();
72                      session1.setAttribute("private", privateKey1);
73                      //公钥信息保存在页面,用于加密
74                      String publicKeyExponent = publicKey1.getPublicExponent().toString(16);
75                      String publicKeyModulus = publicKey1.getModulus().toString(16);
76                      request.setAttribute("publicKeyExponent", publicKeyExponent);
77                      request.setAttribute("publicKeyModulus", publicKeyModulus);    
78                      System.out.println(publicKeyExponent);
79                  }
80                }
81             } catch (Exception e) {
82                 // TODO Auto-generated catch block
83                 e.printStackTrace();
84             }
85             
86             return "login";
87         }

登陆处理代码如上除了 解密  和秘钥放入 session外  其他就是基本的   登陆验证咯

接下来  jsp 端

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport"  content="initial-scale=1;width=device-width;">
<title>Insert title here</title>
<script type='text/javascript' src="image/RSA.js"></script>
<style>
	html,body{
		margin:0 auto;
		background:#f4f4f4;
		text-align:center;
		100%;
		height:100%;
	}
	#formdiv{
	    margin:0 auto;
	    text-align:center;
		box-shadow:0px 0px 5px #ddd; 
		background:#fff;
		100%;
		height:75%;
	}
	input{
		height:45px;
		75%;
	}
	#surebt{
			padding-top:5px;
        	text-align:center;
       		color:#000;
        	150px;
        	height:45px;
        	display:inline-block;
        	background:#fff;
        	border-radius:5px;
	}
</style>
</head>
<body>
	<div style="font-size:33pt;text-align:left;">ZhangTalent</div>
<div id="formdiv">
	<p style="font-size:23pt;text-align:left;padding-left:20px;">Login</p>
	<%if(request.getAttribute("result").equals("fail")) {%>
		信息错误请重新登陆!!!
		<form action="registe" method="post" id="form1">
	   <div class="lab" >用户名   :</div><input name="username"/><br><br>
	   <div class="lab" >密      码:</div><input id="password"   name="password" type="password"/><br><br>
	   <button id="surebt" value="登录" type="button"></button>
		</form>
		<% } 
		else if(request.getAttribute("result").equals("success"))
	{ %>
		登陆成功!!!
	<% }else{ %>
	<form action="login" method="post" id="form1">
	   <div class="lab" >用户名   :</div><input name="username"/><br><br>
	   <div class="lab" >密      码:</div><input id="password"   name="password" type="password"/><br><br>
	   <button id="surebt" value="登录" type="button"></button>
		</form>
		<%} %>
</div>
  <script>
    RSAUtils.setMaxDigits(200);
    var key = new RSAUtils.getKeyPair("${publicKeyExponent}", "", "${publicKeyModulus}");
        document.getElementById("surebt").onclick=function(){
    		var encrypedPwd = RSAUtils.encryptedString(key,document.getElementById("password").value.split("").reverse().join(""));
    		document.getElementById("password").value=encrypedPwd;
    		document.getElementById("form1").submit();
    		}
        </script>
</body>
</html>

  工具类

  1 package z.talent;
  2 
  3 import java.math.BigInteger;
  4 import java.security.KeyFactory;
  5 import java.security.KeyPair;
  6 import java.security.KeyPairGenerator;
  7 import java.security.NoSuchAlgorithmException;
  8 import java.security.Security;
  9 import java.security.interfaces.RSAPrivateKey;
 10 import java.security.interfaces.RSAPublicKey;
 11 import java.security.spec.RSAPrivateKeySpec;
 12 import java.security.spec.RSAPublicKeySpec;
 13 import java.util.HashMap;
 14 
 15 import javax.crypto.Cipher;
 16 
 17 public class RSATools {
 18     /** 
 19      * 生成公钥和私钥 
 20      * @throws NoSuchAlgorithmException  
 21      * 
 22      */  
 23     public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{
 24         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 25         HashMap<String, Object> map = new HashMap<String, Object>();  
 26         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());  
 27         keyPairGen.initialize(1024);  
 28         KeyPair keyPair = keyPairGen.generateKeyPair();  
 29         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
 30         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
 31         map.put("public", publicKey);  
 32         map.put("private", privateKey);  
 33         return map;  
 34     }  
 35     /** 
 36      * 使用模和指数生成RSA公钥 
 37      * @param modulus  模 
 38      * @param exponent  指数 
 39      * @return 
 40      */  
 41     public static RSAPublicKey getPublicKey(String modulus, String exponent) {  
 42         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 43         try {  
 44             BigInteger b1 = new BigInteger(modulus);  
 45             BigInteger b2 = new BigInteger(exponent);  
 46             KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());  
 47             RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);  
 48             return (RSAPublicKey) keyFactory.generatePublic(keySpec);  
 49         } catch (Exception e) {  
 50             e.printStackTrace();  
 51             return null;  
 52         }  
 53     }  
 54   
 55     /** 
 56      * 使用模和指数生成RSA私钥 
 57      * /None/NoPadding
 58      * @param modulus     模 
 59      * @param exponent   指数 
 60      * @return 
 61      */  
 62     public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {  
 63         try {  
 64             Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 65             BigInteger b1 = new BigInteger(modulus);  
 66             BigInteger b2 = new BigInteger(exponent);  
 67             KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());  
 68             RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);  
 69             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);  
 70         } catch (Exception e) {  
 71             e.printStackTrace();  
 72             return null;  
 73         }  
 74     }  
 75   
 76     /** 
 77      * 公钥加密 
 78      *  
 79      * @param data 
 80      * @param publicKey 
 81      * @return 
 82      * @throws Exception 
 83      */  
 84     public static String encryptByPublicKey(String data, RSAPublicKey publicKey)  
 85             throws Exception {  
 86         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 87         Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());  
 88         cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
 89         // 模长  
 90         int key_len = publicKey.getModulus().bitLength() / 8;  
 91         // 加密数据长度 <= 模长-11  
 92         String[] datas = splitString(data, key_len - 11);  
 93         String mi = "";  
 94         //如果明文长度大于模长-11则要分组加密  
 95         for (String s : datas) {  
 96             mi += bcd2Str(cipher.doFinal(s.getBytes()));  
 97         }  
 98         return mi;  
 99     }  
100   
101     /** 
102      * 私钥解密 
103      *  
104      * @param data 
105      * @param privateKey 
106      * @return 
107      * @throws Exception 
108      */  
109     public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)  
110             throws Exception { 
111         Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
112         Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());  
113         cipher.init(Cipher.DECRYPT_MODE, privateKey);  
114         //模长  
115         int key_len = privateKey.getModulus().bitLength() / 8;  
116         byte[] bytes = data.getBytes();  
117         byte[] bcd = ASCII_To_BCD(bytes, bytes.length);  
118         //System.err.println(bcd.length);  
119         //如果密文长度大于模长则要分组解密  
120         String ming = "";  
121         byte[][] arrays = splitArray(bcd, key_len);  
122         for(byte[] arr : arrays){  
123             ming += new String(cipher.doFinal(arr));  
124         }  
125         return ming;  
126     }  
127     /** 
128      * ASCII码转BCD码 
129      *  
130      */  
131     public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {  
132         byte[] bcd = new byte[asc_len / 2];  
133         int j = 0;  
134         for (int i = 0; i < (asc_len + 1) / 2; i++) {  
135             bcd[i] = asc_to_bcd(ascii[j++]);  
136             bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));  
137         }  
138         return bcd;  
139     }  
140     public static byte asc_to_bcd(byte asc) {  
141         byte bcd;  
142   
143         if ((asc >= '0') && (asc <= '9'))  
144             bcd = (byte) (asc - '0');  
145         else if ((asc >= 'A') && (asc <= 'F'))  
146             bcd = (byte) (asc - 'A' + 10);  
147         else if ((asc >= 'a') && (asc <= 'f'))  
148             bcd = (byte) (asc - 'a' + 10);  
149         else  
150             bcd = (byte) (asc - 48);  
151         return bcd;  
152     }  
153     /** 
154      * BCD转字符串 
155      */  
156     public static String bcd2Str(byte[] bytes) {  
157         char temp[] = new char[bytes.length * 2], val;  
158   
159         for (int i = 0; i < bytes.length; i++) {  
160             val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);  
161             temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');  
162   
163             val = (char) (bytes[i] & 0x0f);  
164             temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');  
165         }  
166         return new String(temp);  
167     }  
168     /** 
169      * 拆分字符串 
170      */  
171     public static String[] splitString(String string, int len) {  
172         int x = string.length() / len;  
173         int y = string.length() % len;  
174         int z = 0;  
175         if (y != 0) {  
176             z = 1;  
177         }  
178         String[] strings = new String[x + z];  
179         String str = "";  
180         for (int i=0; i<x+z; i++) {  
181             if (i==x+z-1 && y!=0) {  
182                 str = string.substring(i*len, i*len+y);  
183             }else{  
184                 str = string.substring(i*len, i*len+len);  
185             }  
186             strings[i] = str;  
187         }  
188         return strings;  
189     }  
190     /** 
191      *拆分数组  
192      */  
193     public static byte[][] splitArray(byte[] data,int len){  
194         int x = data.length / len;  
195         int y = data.length % len;  
196         int z = 0;  
197         if(y!=0){  
198             z = 1;  
199         }  
200         byte[][] arrays = new byte[x+z][];  
201         byte[] arr;  
202         for(int i=0; i<x+z; i++){  
203             arr = new byte[len];  
204             if(i==x+z-1 && y!=0){  
205                 System.arraycopy(data, i*len, arr, 0, y);  
206             }else{  
207                 System.arraycopy(data, i*len, arr, 0, len);  
208             }  
209             arrays[i] = arr;  
210         }  
211         return arrays;  
212     }
213 
214 }

用到的文件 如下rsa.js

http://bmob-cdn-5412.b0.upaiyun.com/2018/01/21/13a9060c4069bfff80fc0000a6299f15.js

jar包自己百度下载

bcprov-jdk16-146.jar

保证复制就能用

接下来就是   加上个base加密了.......hahahahahha

package z.talent;
import java.math.BigInteger;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.Security;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.RSAPrivateKeySpec;import java.security.spec.RSAPublicKeySpec;import java.util.HashMap;
import javax.crypto.Cipher;
public class RSATools {/**      * 生成公钥和私钥      * @throws NoSuchAlgorithmException       *      */      public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());        HashMap<String, Object> map = new HashMap<String, Object>();          KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());          keyPairGen.initialize(1024);          KeyPair keyPair = keyPairGen.generateKeyPair();          RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();          RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();          map.put("public", publicKey);          map.put("private", privateKey);          return map;      }      /**      * 使用模和指数生成RSA公钥      * @param modulus  模      * @param exponent  指数      * @return      */      public static RSAPublicKey getPublicKey(String modulus, String exponent) {      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());        try {              BigInteger b1 = new BigInteger(modulus);              BigInteger b2 = new BigInteger(exponent);              KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());              RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);              return (RSAPublicKey) keyFactory.generatePublic(keySpec);          } catch (Exception e) {              e.printStackTrace();              return null;          }      }        /**      * 使用模和指数生成RSA私钥      * /None/NoPadding     * @param modulus     模      * @param exponent   指数      * @return      */      public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {          try {          Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());            BigInteger b1 = new BigInteger(modulus);              BigInteger b2 = new BigInteger(exponent);              KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());              RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);              return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);          } catch (Exception e) {              e.printStackTrace();              return null;          }      }        /**      * 公钥加密      *       * @param data      * @param publicKey      * @return      * @throws Exception      */      public static String encryptByPublicKey(String data, RSAPublicKey publicKey)              throws Exception {      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());        Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());          cipher.init(Cipher.ENCRYPT_MODE, publicKey);          // 模长          int key_len = publicKey.getModulus().bitLength() / 8;          // 加密数据长度 <= 模长-11          String[] datas = splitString(data, key_len - 11);          String mi = "";          //如果明文长度大于模长-11则要分组加密          for (String s : datas) {              mi += bcd2Str(cipher.doFinal(s.getBytes()));          }          return mi;      }        /**      * 私钥解密      *       * @param data      * @param privateKey      * @return      * @throws Exception      */      public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)              throws Exception {     Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());        Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());          cipher.init(Cipher.DECRYPT_MODE, privateKey);          //模长          int key_len = privateKey.getModulus().bitLength() / 8;          byte[] bytes = data.getBytes();          byte[] bcd = ASCII_To_BCD(bytes, bytes.length);          //System.err.println(bcd.length);          //如果密文长度大于模长则要分组解密          String ming = "";          byte[][] arrays = splitArray(bcd, key_len);          for(byte[] arr : arrays){              ming += new String(cipher.doFinal(arr));          }          return ming;      }      /**      * ASCII码转BCD码      *       */      public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {          byte[] bcd = new byte[asc_len / 2];          int j = 0;          for (int i = 0; i < (asc_len + 1) / 2; i++) {              bcd[i] = asc_to_bcd(ascii[j++]);              bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));          }          return bcd;      }      public static byte asc_to_bcd(byte asc) {          byte bcd;            if ((asc >= '0') && (asc <= '9'))              bcd = (byte) (asc - '0');          else if ((asc >= 'A') && (asc <= 'F'))              bcd = (byte) (asc - 'A' + 10);          else if ((asc >= 'a') && (asc <= 'f'))              bcd = (byte) (asc - 'a' + 10);          else              bcd = (byte) (asc - 48);          return bcd;      }      /**      * BCD转字符串      */      public static String bcd2Str(byte[] bytes) {          char temp[] = new char[bytes.length * 2], val;            for (int i = 0; i < bytes.length; i++) {              val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);              temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');                val = (char) (bytes[i] & 0x0f);              temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');          }          return new String(temp);      }      /**      * 拆分字符串      */      public static String[] splitString(String string, int len) {          int x = string.length() / len;          int y = string.length() % len;          int z = 0;          if (y != 0) {              z = 1;          }          String[] strings = new String[x + z];          String str = "";          for (int i=0; i<x+z; i++) {              if (i==x+z-1 && y!=0) {                  str = string.substring(i*len, i*len+y);              }else{                  str = string.substring(i*len, i*len+len);              }              strings[i] = str;          }          return strings;      }      /**      *拆分数组       */      public static byte[][] splitArray(byte[] data,int len){          int x = data.length / len;          int y = data.length % len;          int z = 0;          if(y!=0){              z = 1;          }          byte[][] arrays = new byte[x+z][];          byte[] arr;          for(int i=0; i<x+z; i++){              arr = new byte[len];              if(i==x+z-1 && y!=0){                  System.arraycopy(data, i*len, arr, 0, y);              }else{                  System.arraycopy(data, i*len, arr, 0, len);              }              arrays[i] = arr;          }          return arrays;      }
}

原文地址:https://www.cnblogs.com/zhangtalent/p/8325292.html