借鉴https://my.oschina.net/chaun/blog/519105
1 @GetMapping("/login")2 public String login(Model model,HttpServletRequest request) throwsIOException {3 try{4 model.addAttribute("result","login");5 HashMap 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) throwsIOException {26 model.addAttribute("result","registes");27
28 return "registe";29 }30 @PostMapping("/login")31 public String dologin(Model model,HttpServletRequest request) throwsIOException {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=newGetdata();40 user user=getdata.GetUser(username, password);41 if(user==null) {42 model.addAttribute("result","fail");43 HashMap 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 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 端
pageEncoding="UTF-8"%>
Insert title herehtml,body{
margin:0 auto;
background:#f4f4f4;
text-align:center;
width:100%;
height:100%;
}
#formdiv{
margin:0 auto;
text-align:center;
box-shadow:0px 0px 5px #ddd;
background:#fff;
width:100%;
height:75%;
}
input{
height:45px;
width:75%;
}
#surebt{
padding-top:5px;
text-align:center;
color:#000;
width:150px;
height:45px;
display:inline-block;
background:#fff;
border-radius:5px;
}
Login
信息错误请重新登陆!!!
else if(request.getAttribute("result").equals("success"))
{ %>
登陆成功!!!
RSAUtils.setMaxDigits(200);
var key = new RSAUtils.getKeyPair("${publicKeyExponent}", "", "${publicKeyModulus}");
document.getElementById("surebt").οnclick=function(){
var encrypedPwd = RSAUtils.encryptedString(key,document.getElementById("password").value.split("").reverse().join(""));
document.getElementById("password").value=encrypedPwd;
document.getElementById("form1").submit();
}
工具类
1 packagez.talent;2
3 importjava.math.BigInteger;4 importjava.security.KeyFactory;5 importjava.security.KeyPair;6 importjava.security.KeyPairGenerator;7 importjava.security.NoSuchAlgorithmException;8 importjava.security.Security;9 importjava.security.interfaces.RSAPrivateKey;10 importjava.security.interfaces.RSAPublicKey;11 importjava.security.spec.RSAPrivateKeySpec;12 importjava.security.spec.RSAPublicKeySpec;13 importjava.util.HashMap;14
15 importjavax.crypto.Cipher;16
17 public classRSATools {18 /**
19 * 生成公钥和私钥20 *@throwsNoSuchAlgorithmException21 *22 */
23 public static HashMap getKeys() throwsNoSuchAlgorithmException{24 Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());25 HashMap map = new HashMap();26 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", neworg.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 returnmap;34 }35 /**
36 * 使用模和指数生成RSA公钥37 *@parammodulus 模38 *@paramexponent 指数39 *@return
40 */
41 public staticRSAPublicKey getPublicKey(String modulus, String exponent) {42 Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());43 try{44 BigInteger b1 = newBigInteger(modulus);45 BigInteger b2 = newBigInteger(exponent);46 KeyFactory keyFactory = KeyFactory.getInstance("RSA", neworg.bouncycastle.jce.provider.BouncyCastleProvider());47 RSAPublicKeySpec keySpec = newRSAPublicKeySpec(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/NoPadding58 *@parammodulus 模59 *@paramexponent 指数60 *@return
61 */
62 public staticRSAPrivateKey getPrivateKey(String modulus, String exponent) {63 try{64 Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());65 BigInteger b1 = newBigInteger(modulus);66 BigInteger b2 = newBigInteger(exponent);67 KeyFactory keyFactory = KeyFactory.getInstance("RSA", neworg.bouncycastle.jce.provider.BouncyCastleProvider());68 RSAPrivateKeySpec keySpec = newRSAPrivateKeySpec(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 *@paramdata80 *@parampublicKey81 *@return
82 *@throwsException83 */
84 public staticString encryptByPublicKey(String data, RSAPublicKey publicKey)85 throwsException {86 Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());87 Cipher cipher = Cipher.getInstance("RSA", neworg.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 returnmi;99 }100
101 /**
102 * 私钥解密103 *104 *@paramdata105 *@paramprivateKey106 *@return
107 *@throwsException108 */
109 public staticString decryptByPrivateKey(String data, RSAPrivateKey privateKey)110 throwsException {111 Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());112 Cipher cipher = Cipher.getInstance("RSA", neworg.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 += newString(cipher.doFinal(arr));124 }125 returnming;126 }127 /**
128 * ASCII码转BCD码129 *130 */
131 public static byte[] ASCII_To_BCD(byte[] ascii, intasc_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 returnbcd;139 }140 public static byte asc_to_bcd(byteasc) {141 bytebcd;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 returnbcd;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 newString(temp);167 }168 /**
169 * 拆分字符串170 */
171 public static String[] splitString(String string, intlen) {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
191 *拆分数组192 */
193 public static byte[][] splitArray(byte[] data,intlen){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
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 getKeys() throws NoSuchAlgorithmException{ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); HashMap map = new HashMap(); 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
}