Javascript RSA加密密码Java JSP解密示例

该博客展示了如何使用Java实现RSA加密过程,包括生成密钥对、存储公钥并用其加密密码。在用户登录时,前端通过JavaScript加密密码,然后发送到后端进行解密验证。博客还包含了验证码功能的实现,确保了安全性。
摘要由CSDN通过智能技术生成
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
%>

<%@page import="java.security.*"%>
<%@page import="java.util.Base64"%>
<%
class RSAKeyPairGenerator {

	private PrivateKey privateKey;
	private PublicKey publicKey;

	public RSAKeyPairGenerator() throws NoSuchAlgorithmException {
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(1024);
		KeyPair pair = keyGen.generateKeyPair();
		this.privateKey = pair.getPrivate();
		this.publicKey = pair.getPublic();
	}

	public PrivateKey getPrivateKey() {
		return privateKey;
	}

	public PublicKey getPublicKey() {
		return publicKey;
	}

}
%>
<!DOCTYPE html>
<html>
<head>
<title>请登录</title>

<script src="jsencrypt.min.js"></script>

<script type="text/javascript">
	function reloadImg() {
		var timestamp = new Date().getTime();
		document.getElementById("captcha").src = "simpleCaptcha.jpg?"
				+ timestamp;
	}

	function encryptPassword() {
		var password = document.getElementById('password').value;
		var publicKey = document.getElementById('PublicKey').value;
		let RSAEncrypt = new JSEncrypt();
		RSAEncrypt.setPublicKey(publicKey);
		let encryptedPass = RSAEncrypt.encrypt(password);
		document.getElementById('password').value = encryptedPass;
	}
</script>
</head>
<body>
	<form id="form" method="post" action="validate.jsp"
		onsubmit="encryptPassword()">
		<input id="PublicKey" name="PublicKey" type="hidden"
			value="<%RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator();
out.print(String.format("%s", Base64.getEncoder().encodeToString(keyPairGenerator.getPublicKey().getEncoded())));
//out.println(String.format("Private Key : %s",
//		Base64.getEncoder().encodeToString(keyPairGenerator.getPrivateKey().getEncoded())));
session.setAttribute("PrivateKey", Base64.getEncoder().encodeToString(keyPairGenerator.getPrivateKey().getEncoded()));%>">
		<%
		System.out.println(String.format("PublicKey : %s",
				Base64.getEncoder().encodeToString(keyPairGenerator.getPublicKey().getEncoded())));
		System.out.println(String.format("PrivateKey : %s",
				Base64.getEncoder().encodeToString(keyPairGenerator.getPrivateKey().getEncoded())));
		%>
		<center>
			<table border="1" cellpadding="5" cellspacing="2">
				<thead>
					<tr>
						<th colspan="2">请输入用户名密码登录</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td>用户名</td>
						<td><input id="username" type="text" name="username" required /></td>
					</tr>
					<tr>
						<td>密码</td>
						<td><input id="password" type="password" name="password"
							required /></td>
					</tr>
					<tr>
						<td>验证码</td>
						<td><img id="captcha" src="simpleCaptcha.jpg" /><br /> <a
							href="javascript:reloadImg()">刷新验证码</a> <br /> <input
							type="text" name="answer" /><br></td>
					</tr>
					<tr>
						<td colspan="2" align="center"><input type="submit"
							value="登录" /> &nbsp;&nbsp; <input type="reset" value="重置" /></td>
					</tr>
				</tbody>
			</table>
		</center>
	</form>
</body>
</html>
<%@page language="java" pageEncoding="UTF-8"%>
<%@page contentType="text/html;charset=UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.security.MessageDigest"%>
<%@page import="java.security.NoSuchAlgorithmException"%>
<%@page import="java.security.NoSuchProviderException"%>
<%@page import="java.security.SecureRandom"%>

<%@page import="nl.captcha.Captcha"%>

<%@page import="java.security.*"%>
<%@page import="java.security.spec.InvalidKeySpecException"%>
<%@page import="java.security.spec.PKCS8EncodedKeySpec"%>
<%@page import="java.security.spec.X509EncodedKeySpec"%>
<%@page import="java.util.Base64"%>

<%@page import="javax.crypto.BadPaddingException"%>
<%@page import="javax.crypto.Cipher"%>
<%@page import="javax.crypto.IllegalBlockSizeException"%>
<%@page import="javax.crypto.NoSuchPaddingException"%>



<%
class RSAUtil {

	public PublicKey getPublicKey(String base64PublicKey) {
		PublicKey publicKey = null;
		try {
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	publicKey = keyFactory.generatePublic(keySpec);
	return publicKey;
		} catch (NoSuchAlgorithmException e) {
	e.printStackTrace();
		} catch (InvalidKeySpecException e) {
	e.printStackTrace();
		}
		return publicKey;
	}

	public PrivateKey getPrivateKey(String base64PrivateKey) {
		PrivateKey privateKey = null;
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()));
		KeyFactory keyFactory = null;
		try {
	keyFactory = KeyFactory.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
	e.printStackTrace();
		}
		try {
	privateKey = keyFactory.generatePrivate(keySpec);
		} catch (InvalidKeySpecException e) {
	e.printStackTrace();
		}
		return privateKey;
	}

	public byte[] encrypt(String data, String publicKey) throws BadPaddingException, IllegalBlockSizeException,
	InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
		return cipher.doFinal(data.getBytes());
	}

	public String decrypt(byte[] data, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException,
	InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return new String(cipher.doFinal(data));
	}

	public String decrypt(String data, String base64PrivateKey) throws IllegalBlockSizeException, InvalidKeyException,
	BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
		return decrypt(Base64.getDecoder().decode(data.getBytes()), getPrivateKey(base64PrivateKey));
	}

}
String encryptedString = request.getParameter("password");
String privateKey = (String) session.getAttribute("PrivateKey");
RSAUtil rsaUtil = new RSAUtil();
String decryptedString = rsaUtil.decrypt(encryptedString, privateKey);
String password = decryptedString;

Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
request.setCharacterEncoding("UTF-8");
String answer = request.getParameter("answer");
if (captcha.isCorrect(answer)) {
%>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值