实现RSA时,发现后台生成的公钥转化为16进制传到前端时出错

Choee-z 2016-11-08 12:19:09
后台生成公私钥后需要转化成16进制传到前端
但是原来的bigint转化的16进制数不等于原数值

前端公钥解密使用的是网上用的多的Barrett.js,BigInt.js和RSA.js应该没什么问题

前端代码:

<%@ 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>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='scripts/jquery-1.9.1.min.js'></script>
<script type='text/javascript' src='scripts/Barrett.js'></script>
<script type='text/javascript' src='scripts/BigInt.js'></script>
<script type='text/javascript' src='scripts/RSA.js'></script>
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.get("<%=path%>/rsaMethod", function(data) {
var arr = eval(data);
$("#Modulus").val(arr[0]);
$("#PublicExponent").val(arr[1]);
alert(data);
});
$("form").css({
"display" : "block"
});
});

$("#submitbtn").click(function() {
var name=$("#name").val();
var password=$("#password").val();
var rsa_e = $("#PublicExponent").val();
var rsa_m = $("#Modulus").val();
setMaxDigits(130);
var key = new RSAKeyPair(rsa_e,'', rsa_m,1024);
password = encryptedString(key, encodeURIComponent(password));
alert(password);
var arr={};
arr.name=name;
arr.password=password;
$.post("<%=path%>/rsaMethod",arr,function(data){
alert(data);
});
});
})
</script>
<button id="btn">click</button>
<form action="" method="post" style="display: none;">
name:<input type="text" id="name"><br>
password:<input type="text" id="password">
<input type="hidden" id="Modulus">
<input type="hidden" id="PublicExponent">
<button id="submitbtn">submit</button>
</form>
</body>
</html>

后台servlet



@WebServlet("/rsaMethod")
public class rsaMethod extends HttpServlet {
private static final long serialVersionUID = 1L;

private static KeyPairGenerator keypairgenerator;
private static KeyPair keypair;
private static RSAPublicKey rsapublicKey;
private static RSAPrivateKey rsaprivateKey;

private String message = "123";

public rsaMethod() throws NoSuchAlgorithmException {
super();
keypairgenerator = KeyPairGenerator.getInstance("RSA");
keypairgenerator.initialize(1024);
keypair = keypairgenerator.generateKeyPair();
rsapublicKey = (RSAPublicKey) keypair.getPublic();
rsaprivateKey = (RSAPrivateKey) keypair.getPrivate();
}

/*
* // rsa加密
* public byte[] Encode() throws Exception {
* X509EncodedKeySpec x509encodedkeyspec = new X509EncodedKeySpec(rsapublicKey.getEncoded());
* KeyFactory keyfactory = KeyFactory.getInstance("RSA");
* PublicKey publickey = keyfactory.generatePublic(x509encodedkeyspec);
* System.out.println(publickey);
*
* Cipher cipher = Cipher.getInstance("RSA");
* cipher.init(cipher.ENCRYPT_MODE, publickey);
* byte[] result = cipher.doFinal(message.getBytes());
* System.out.println(Base64.getEncoder().encodeToString(result));
* return result;
*
* }
*
* // rsa解密
* public void Decode(byte[] arr) throws Exception {
* PKCS8EncodedKeySpec pkcs8encodedkeyspec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());
* KeyFactory keyfactory =KeyFactory.getInstance("RSA");
* PrivateKey privatekey = keyfactory.generatePrivate(pkcs8encodedkeyspec);
*
* Cipher cipher = Cipher.getInstance("RSA");
* cipher.init(cipher.DECRYPT_MODE, privatekey);
* byte[] result = cipher.doFinal(arr);
* System.out.println(new String(result));
* }
*/

// 获取公钥
public PublicKey getPublickey() throws Exception {
X509EncodedKeySpec x509encodedkeyspec = new X509EncodedKeySpec(rsapublicKey.getEncoded());
KeyFactory keyfactory = KeyFactory.getInstance("RSA");
PublicKey publickey = keyfactory.generatePublic(x509encodedkeyspec);

System.out.println(((RSAPublicKey)publickey).getPublicExponent());

return publickey;
}

// 获取私钥
public PrivateKey getPrivatekey() throws Exception {
PKCS8EncodedKeySpec pkcs8encodedkeyspec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded());
KeyFactory keyfactory = KeyFactory.getInstance("RSA");
PrivateKey privatekey = keyfactory.generatePrivate(pkcs8encodedkeyspec);

System.out.println(((RSAPrivateKey)privatekey).getPrivateExponent());

return privatekey;
}

// 判断钥匙文件是否存在,是否有内容
public void JudgeNone(String path) throws Exception {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
if (file.length() == 0) {
outputkeyTofile(file);
}
}

// 向文件中写入公私钥
public void outputkeyTofile(File file) throws Exception {
PublicKey publickey = getPublickey();
PrivateKey privatekey = getPrivatekey();

System.out.println(publickey);
System.out.println(privatekey);

OutputStream os = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(publickey);
oos.writeObject(privatekey);
oos.writeObject(null);
oos.close();
}

//文件中读取公钥
public PublicKey getPubkeyfromFile(String pathname) throws Exception{
InputStream ins=new FileInputStream(pathname);
ObjectInputStream oins=new ObjectInputStream(ins);
Object obj=oins.readObject();
oins.close();
ins.close();
return (PublicKey)obj;
}

//公钥中读取modulus和publicPublicExponent
public JSONArray getpublicKey(String pathname) throws Exception {
JSONArray arr = new JSONArray();
PublicKey publickey = getPubkeyfromFile(pathname);
arr.add(((RSAPublicKey) publickey).getModulus().toString(16));

System.out.println("原来:"+((RSAPublicKey) publickey).getModulus());
System.out.println("16新的:"+((RSAPublicKey) publickey).getModulus().toString(16));

arr.add(((RSAPublicKey) publickey).getPublicExponent().toString(16));
return arr;
}

//从文件中读取私钥
public PrivateKey getPrikeyfromFile(String pathname) throws Exception{
InputStream ins=new FileInputStream(pathname);
ObjectInputStream oins=new ObjectInputStream(ins);
Object obj=oins.readObject();
obj=oins.readObject();
oins.close();
ins.close();
return (PrivateKey)obj;
}

//私钥解密
public String Decode(String pathname,String value) throws Exception{
PrivateKey privatekey=getPrikeyfromFile(pathname);

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(cipher.DECRYPT_MODE, privatekey);
byte[] result = cipher.doFinal(value.getBytes());
System.out.println(new String(result));

return new String(result);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pathname = request.getSession().getServletContext().getRealPath("/key.txt");
try {
JudgeNone(pathname);
JSONArray arr = getpublicKey(pathname);
response.getWriter().write(arr + "");
} catch (Exception e) {
e.printStackTrace();
}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// String pathname = request.getSession().getServletContext().getRealPath("/key.txt");
// String password=request.getParameter("password");
//
// try {
// password=Decode(pathname,password);
// response.getWriter().write(password);
// } catch (Exception e) {
// e.printStackTrace();
// }
String password=request.getParameter("password");

String pathname = request.getSession().getServletContext().getRealPath("/key.txt");
PublicKey publickey;
try {
publickey = getPubkeyfromFile(pathname);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(cipher.ENCRYPT_MODE, publickey);
byte[] result = cipher.doFinal("123".getBytes());
System.out.println(Base64.getEncoder().encodeToString(result));
System.out.println(password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
...全文
180 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧